Customize the Client
Create custom MonoCloudBackendNodeClient instances for use with protectApi() middleware instances in an Express API.
This guide shows how to create custom MonoCloudBackendNodeClient instances and use them with protectApi() middleware 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 middleware instances
- You need to share cached JWKS and metadata across middleware
- 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:
- An Express project
- The
@monocloud/backend-nodeSDK 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.
import "dotenv/config";
import express from "express";
import {
MonoCloudBackendNodeClient,
protectApi,
type AuthenticatedExpressRequest,
} from "@monocloud/backend-node/express";
const app = express();
app.use(express.json());
// 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", protectPublicApi(), (req, res) => {
const { claims } = req as AuthenticatedExpressRequest;
res.json({ claims });
});
// Admin API
app.get("/api/admin", protectAdminApi(), (req, res) => {
const { claims } = req as AuthenticatedExpressRequest;
res.json({ claims });
});
app.listen(3000);How it works:
MonoCloudBackendNodeClientmanages JWKS and metadata caching internallypublicClientuses configuration from environment variablesadminClientuses an explicit tenant domain and audienceprotectPublicApiandprotectAdminApiuse separate client instances with independent caches and configuration- Each middleware factory still applies its own route protection options, such as scopes and groups