How to use AWS Secrets Manager with @auth0/nextjs-auth0?

  • Which SDK this is regarding: @auth0/nextjs-auth0
  • SDK Version: 1.9.1

Hello, we have a couple teams that are hoping to use AWS Secrets Manager to periodically rotate the clientSecret config. However, we are not seeing how to reinitialize the auth configuration. One team has tried the following:

// /lib/auth.js

import { initAuth0 } from "@auth0/nextjs-auth0";
import { SecretsManagerClient, GetSecretValueCommand } from "@aws-sdk/client-secrets-manager";

const config = async () => {
  const smClient = new SecretsManagerClient(...);
  const smCommand = new GetSecretValueCommand(...);
  const response = await smClient.send(smCommand);
  const json = JSON.parse(response?.SecretString);

  return {
    secret: "...",
    baseURL: "...",
    issuerBaseURL: "...",
    clientID: json.client_id,
    clientSecret: json.client_secret,
  }
}

export default initAuth0(await config());
// /pages/api/auth/[...auth0].js

import auth from "../../../lib/auth";

export default auth.handleAuth();

This works initially, however, once the secret has rotated it no longer does. We are not seeing how we can tell the library to “reinitialize” using the rotated secret values. Hoping it’s something simple that we are overlooking. Thank you.

I did find next.js - Use Google Cloud Secret Manager to fetch AUTH0_CLIENT_SECRET and use with nextjs-auth0 - Stack Overflow which I implemented as the following:

// /pages/api/auth/[...auth0].js

import { initAuth0 } from "@auth0/nextjs-auth0";
import {
  SecretsManagerClient,
  GetSecretValueCommand,
} from "@aws-sdk/client-secrets-manager";

export default async function handler(req, res) {
  // TODO: Determine if we can optimize by memoizing the `authHandler` when the secret has not yet rotated. Otherwise...

  // Get values from Secrets Manager.
  const smClient = new SecretsManagerClient(...);
  const smCommand = new GetSecretValueCommand(...);
  const response = await smClient.send(smCommand);
  const json = JSON.parse(response?.SecretString);

  // Create auth0 instance. Any values not included here will default back to the corresponding environment variables.
  const auth0 = initAuth0({
    secret: "...",
    baseURL: "...",
    issuerBaseURL: "...",
    clientID: json.client_id,
    clientSecret: json.client_secret,
  });

  // Get auth0's dynamic API route handler.
  const auth0Handler = auth0.handleAuth();

  // Delegate the API route request and response to the auth0 handler.
  return auth0Handler(req, res);
}

Seems to be working, but I’m wondering about the performance of re-initializing on every auth API route request. Hopefully there would be a way to memoize the handler until the secret actually rotates.

Or, is there a better/official way to accomplish this?