Can't authenticate Nextjs 13 (app router) api routes using the Auth0 withMiddlewareAuthRequired

Auth0 withMiddlewareAuthRequired doesn’t authenticate api routes even though I pass access token. What am I doing wrong?

I am making a full stack application using Next.js 13 (app router). I have the api folder inside the app folder.

The setup: I have middleware.ts like this

export default withMiddlewareAuthRequired(async function middleware(req) {
    const res = NextResponse.next();
    const { pathname } = req.nextUrl;
    const { accessToken } = await getAccessToken(req, res);
    const requestHeaders = new Headers(req.headers);
    console.log(accessToken);
    requestHeaders.set('Authorization', `Bearer ${accessToken}`);
    const url = new URL(pathname, 'http://localhost:3000');

    console.log('############ API HANDLER');
    console.log(pathname);
    //return res;
    return NextResponse.rewrite(url, {
        request: {
            headers: requestHeaders,
        },
    });
  }
 );

What withMiddlewareAuthRequired does correctly:

  1. If user isn’t logged in, the baseurl will directly redirect to /login endpoint.
  2. If user logged in, it shows all the ui.

However th problem is:

  1. All api routes give 401 error, even though I passed the access token, as you can see above. (The Ui never required access token, I added it only to authorize the api routes but it doesn’t work).

  2. THE BIG CONFUSION:

If the user is logged in, and when I access a sample GET endpoint in the browser, it works. I can see the json output. Only in the application it gives 401 error?

NOTE: I have registered the api in auth0 dashboard and have also passed audience parameter hence my access token is a jwt.

NOTE 2: When I try via postman and pass the access token as bearer it still gives 401 error.

{
    "error": "not_authenticated",
    "description": "The user does not have an active session or is not authenticated"
}

So my question is how to write a proper auth0 middleware for my nextjs 13 app router application such that I don’t get the 401 error in the application while accessing the api routes.

2 Likes