Auth0 with next.js is not working with nest.js

Hi i am trying to integrate auth0 with my next.js frontend and nest.js backend the frontend is working fine i am logging in and getting the token how secure it is is questionable because all of my keys are in env witch could be accessed from brouser dev tool

the issue is that now i am trying to integrate it with my nest.js backend but it’s not working it’s returning 401

i have spended houres on this don’t know that i am going wrong here

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    // Log env variables for debugging
    console.log('AUTH0_AUDIENCE:', process.env.AUTH0_AUDIENCE);
    console.log('AUTH0_ISSUER_BASE_URL:', process.env.AUTH0_ISSUER_BASE_URL);

    super({
      secretOrKeyProvider: jwksRsa.passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequests Per Minute: 5,
        jwksUri: `${process.env.AUTH0_ISSUER_BASE_URL}/.well-known/jwks.json`,
      }),
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      audience: process.env.AUTH0_AUDIENCE, // must match one value in the token's "aud" array
      issuer: process.env.AUTH0_ISSUER_BASE_URL, // must match token's "iss"
      algorithms: ['RS256'],
    });
  }

  async validate(payload: any) {
    // Log payload for debugging
    console.log('JWT payload:', payload);
    return payload;
  }
}

this is how i am getting my token:

import { getAccessToken } from '@auth0/nextjs-auth0';

export async function GET(request: Request) {
  try {
    const { accessToken } = await getAccessToken();
    if (!accessToken) {
      return new Response(JSON.stringify({ error: 'No access token' }), {
        status: 401,
      });
    }
    return new Response(JSON.stringify({ accessToken }), { status: 200 });
  } catch (e: any) {
    return new Response(JSON.stringify({ error: e.message }), { status: 500 });
  }
}

this is how i am handeling the login

import { handleAuth, handleLogin } from '@auth0/nextjs-auth0';

if (
  !process.env.AUTH0_BASE_URL ||
  !process.env.AUTH0_SECRET ||
  !process.env.AUTH0_ISSUER_BASE_URL ||
  !process.env.AUTH0_CLIENT_ID ||
  !process.env.AUTH0_CLIENT_SECRET
) {
  throw new Error('Missing Auth0 environment variables');
}

// Note: We do not use `params` in this route handler. The warning can be ignored.

export const GET = handleAuth({
  login: handleLogin({
    authorizationParams: {
      scope: 'openid profile email', // Add any other scopes you need
    },
  }),
});
export const POST = handleAuth();
export const PUT = handleAuth();
export const DELETE = handleAuth();

let me know if i am using auth0 correctly and if i should even use auth0 in the first place

Hi @nicolatesla0987,

Welcome to the Auth0 Community!

The 401 error you encountered typically means that the access token is missing, invalid, or malformed. In this case, it looks like the front end may not be getting a JWT access token because no audience is specified.

To ensure it’s a JWT access token, add one of your API identifiers as the audience for the authorization parameters.

(Reference: https://auth0.com/docs/secure/tokens/access-tokens/get-access-tokens#control-access-token-audience)

After doing so, the access token will be a JWT, and your backend will be able to validate it.

Let me know how this goes for you.

Thanks,
Rueben