Auth0 Access token from next.js is not working in nest.js API returning 401

i am having an issue the auth0 auth is working correctly in the frontend but when i get the auth0 access token and pass it ass bearer token to the backend it’s returning 401 i don’t know why

my payload token payload

{
  "iss": "https://dev-ba1x5rok53uuqkl0.us.auth0.com/",
  "sub": "auth0|680661497b2fa04497f1674b",
  "aud": [
    "http://localhost:8080",
    "https://dev-ba1x5rok53uuqkl0.us.auth0.com/userinfo"
  ],
  "iat": 1745404769,
  "exp": 1745491169,
  "scope": "openid profile email",
  "azp": "M2uAyZhg5X9ecdWiKiYp0PP47NVXNOnD"
}

nest.js jwt strategy

import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import * as jwksRsa from 'jwks-rsa';

@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);
    console.log('API_ENDPOINT:', process.env.API_ENDPOINT);

    super({
      secretOrKeyProvider: jwksRsa.passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequests PerMinute: 5,
        jwksUri: `${process.env.AUTH0_ISSUER_BASE_URL}/.well-known/jwks.json`,
      }),
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      audience: `${process.env.API_ENDPOINT}`, // 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;
  }
}

frontend next.js auth handling

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: {
      audience: process.env.NEXT_PUBLIC_API_URL_AUTH0,
      scope: 'openid profile email', // Add any other scopes you need
    },
  }),
});
export const POST = handleAuth();
export const PUT = handleAuth();
export const DELETE = handleAuth();

frontend next.js token fetching:

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 });
  }
}

Hi @nicolatesla0987,

Could you provide the error message alongside the snippet of code where the request is being made to the API?

Have a good one,
Vlad

hay thanks for helping me
i have fixed the issue it was a typo in my JWT strategy

currently i am having another issue

even after adding email scope i am not getting user email in the jwt payload

JWT Payload: {
  "iss": "https://dev-ba1x5rok53uuqkl0.us.auth0.com/",
  "sub": "auth0|6808ca7135629091a4429fa8",
  "aud": [
    "http://localhost:8080",
    "https://dev-ba1x5rok53uuqkl0.us.auth0.com/userinfo"
  ],
  "iat": 1745503663,
  "exp": 1745590063,
  "scope": "openid profile email",
  "azp": "M2uAyZhg5X9ecdWiKiYp0PP47NVXNOnD"
}

can you help me with this??

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.