Sign in

Add a Custom Cache

This guide shows how to cache validated access token claims to avoid re-validating the same token on every request.

When to use caching

Use caching when:

  • You receive multiple requests with the same access token
  • Token validation adds noticeable latency (especially with introspection)
  • You want to reduce the number of requests to the OIDC provider

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

Implement the ICache interface

The SDK accepts any cache that implements the ICache interface.

In-memory cache

src/cache.ts
import type { AccessTokenClaims, ICache } from "@monocloud/backend-node/fastify";

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.

Use the cache with protectApi()

Pass the cache to protectApi() through the options:

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

const app = Fastify();

const client = new MonoCloudBackendNodeClient({ cache });

const protect = protectApi(client);

app.addHook("onRequest", protect());

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

app.listen({ port: 3000 });

How it works:

  • After successful validation, claims are stored in the cache using the token as the cache key
  • Subsequent requests with the same token return cached claims without re-validation
  • Cached entries expire when the token expires
© 2024 MonoCloud. All rights reserved.