This guide shows how to cache validated access token claims to avoid re-validating the same token on every request.
Use caching when:
This guide assumes you've completed the installation guide.
You should already have:
@monocloud/backend-node SDK installed.envThe SDK accepts any cache that implements the ICache interface.
import type { AccessTokenClaims, ICache } from "@monocloud/backend-node/express";
const store = new Map<string, { claims: AccessTokenClaims; expiresAt: number }>();
export const cache: ICache = {
async set(token: string, claims: AccessTokenClaims, expiresAt: number): Promise<void> {
store.set(token, { claims, expiresAt });
},
async get(token: string): Promise<AccessTokenClaims | null> {
const entry = store.get(token);
if (!entry) {
return null;
}
if (Date.now() >= entry.expiresAt * 1000) {
store.delete(token);
return null;
}
return entry.claims;
},
async delete(token: string): Promise<void> {
store.delete(token);
},
};
How the interface works:
set(token, claims, expiresAt) — stores validated claims. expiresAt is the access token expiry time as a Unix epoch timestamp in seconds.get(token) — retrieves cached claims, or returns null if the entry does not exist or has expired.delete(token) — removes an entry from the cache.Pass the cache to protectApi() through the options:
import "dotenv/config";
import express from "express";
import {
MonoCloudBackendNodeClient,
protectApi,
type AuthenticatedExpressRequest,
} from "@monocloud/backend-node/express";
import { cache } from "./cache";
const app = express();
app.use(express.json());
const client = new MonoCloudBackendNodeClient({ cache });
const protect = protectApi(client);
app.use(protect());
app.get("/api/data", (req, res) => {
const { claims } = req as AuthenticatedExpressRequest;
res.json({ claims });
});
app.listen(3000);
How it works: