Sign in

Customize the Client

This guide shows how to create custom MonoCloudBackendNodeClient instances and use them with protectApi() hook instances.

When to use a custom client

By default, each protectApi() call creates its own client. Use custom clients when:

  • You want to reuse a single configuration across multiple hook instances
  • You need to share cached JWKS and metadata across hooks
  • You protect multiple APIs with different audiences and want separate client instances with explicit configuration

Before you begin

This guide assumes you've completed the installation guide.

You should already have:

  • A Fastify project
  • The @monocloud/backend-node SDK installed
  • Environment variables configured in .env

Create and reuse custom clients

Create MonoCloudBackendNodeClient instances and pass them to protectApi(). Each client manages its own configuration, JWKS cache, and metadata cache.

src/server.ts
import "dotenv/config";
import Fastify from "fastify";
import {
  MonoCloudBackendNodeClient,
  protectApi,
  type AuthenticatedFastifyRequest,
} from "@monocloud/backend-node/fastify";

const app = Fastify();

// Create a public API client - reads from environment variables
const publicClient = new MonoCloudBackendNodeClient();

// Create an admin API client
const adminClient = new MonoCloudBackendNodeClient({
  tenantDomain: process.env.ADMIN_API_TENANT_DOMAIN,
  audience: process.env.ADMIN_API_AUDIENCE
});

const protectPublicApi = protectApi(publicClient);
const protectAdminApi = protectApi(adminClient);

// Public API
app.get("/api/data", { onRequest: protectPublicApi() }, async (request) => {
  const { claims } = request as AuthenticatedFastifyRequest;
  return { claims };
});

// Admin API
app.get(
  "/api/admin", { onRequest: protectAdminApi() }, async (request) => {
    const { claims } = request as AuthenticatedFastifyRequest;
    return { claims };
  }
);

app.listen({ port: 3000 });

How it works:

  • MonoCloudBackendNodeClient manages JWKS and metadata caching internally
  • publicClient uses configuration from environment variables
  • adminClient uses an explicit tenant domain and audience
  • protectPublicApi and protectAdminApi use separate client instances with independent caches and configuration
  • Each hook factory still applies its own route protection options, such as scopes and groups
© 2024 MonoCloud. All rights reserved.