Search code examples
google-cloud-platformnext.jsauth0google-api-nodejs-clientgoogle-secret-manager

Use Google Cloud Secret Manager to fetch AUTH0_CLIENT_SECRET and use with nextjs-auth0


I have a Next.js application where authentication is set up with the Auth0 Next.js SDK.

Currently the AUTH0_CLIENT_SECRET is being set as an environment variable when deploying.

I would like to use Google Cloud Secret Manager to get the AUTH0_CLIENT_SECRET during runtime and set it using the initAuth0 method.

I'm following this example: https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#create-your-own-instance-of-the-sdk

But I can't figure out how I can await the response from secret manager when I need to have the secret ready for calling the method initAuth0({clientSecret...}) and I need that in place to setup the auth end points with auth0.handleAuth().

This is my attempt: /pages/api/auth/[...auth].ts

import { initAuth0 } from "@auth0/nextjs-auth0";

const asyncHandleAuth = async () => {
  const clientSecret = await getSecret("AUTH0_CLIENT_SECRET");

  const auth0 = initAuth0({ 
    clientSecret // The rest of the config is set with environment variables
  }); 

  return auth0.handleAuth();
};

export default asyncHandleAuth();

Solution

  • After some hair pulling I found the problem. Next.js expects the export default function to be of type NextApiHandler but I was returning Promise<NextApiHandler>. I solved it by wrapping it in another function that takes the request and response arguments and use them to call handleAuth before returning it.

    This worked for me:

    const asyncHandleAuth =
      () => async (req: NextApiRequest, res: NextApiResponse) => {
        const clientSecret = await getSecret("AUTH0_CLIENT_SECRET");
    
        const auth0 = initAuth0({
          clientSecret, // The rest of the config is set with environment variables
        });
        
        return auth0.handleAuth()(req, res);
      };
    
    export default asyncHandleAuth();