Search code examples
next.jsauth0

Next.js App Router with auth0 library causes an error: TypeError: Cannot read properties of undefined (reading 'headers')


I'm implementing auth0 using this library

"@auth0/nextjs-auth0": "^3.0.1"

I made a route.ts file under this path /app/api/auth/[auth0]/route.ts

import { handleAuth, handleLogin, handleLogout } from '@auth0/nextjs-auth0';
import { NextApiRequest, NextApiResponse } from 'next';

export const GET = handleAuth({
  async login(req: NextApiRequest, res: NextApiResponse) {
    await handleLogin(req, res, {
      returnTo: `http://localhost:3000/home`,
    });
  },
    async logout(req: NextApiRequest, res: NextApiResponse) {
      await handleLogout(req, res, {
        returnTo: `http://localhost:3000/home`,
      });
    },
});

export const dynamic = 'force-dynamic';

This didn't work. When I try to login an error occurs. The error is

- error TypeError: Cannot read properties of undefined (reading 'headers')
    at eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:265:61)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Any advise?


Solution

  • Needed to add return

    import { handleAuth, handleLogin, handleLogout } from '@auth0/nextjs-auth0';
    import { NextApiRequest, NextApiResponse } from 'next';
    
    export const GET = handleAuth({
      async login(req: NextApiRequest, res: NextApiResponse) {
        return await handleLogin(req, res, {
          returnTo: `http://localhost:3000/home`,
        });
      },
        async logout(req: NextApiRequest, res: NextApiResponse) {
          return await handleLogout(req, res, {
            returnTo: `http://localhost:3000/home`,
          });
        },
    });
    
    export const dynamic = 'force-dynamic';