Search code examples
typescriptnext.jsnext.js13next-authapp-router

NextAuth Get Session in App Router API Route


I'm using NextAuth and Next.js's App Router. I've created an API route in my /app/api folder. However, I am unable to retrieve the session corresponding to the request.

Here is my API route, which I am calling with the get(url) method:

export async function GET(req: NextApiRequest) {
    const session = await getServerSession(req);

    console.log(session);

    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}

However, when this runs, I get the following error on the server:

[next-auth][error][JWT_SESSION_ERROR] 
https://next-auth.js.org/errors#jwt_session_error Invalid Compact JWE {
  message: 'Invalid Compact JWE',
  stack: 'JWEInvalid: Invalid Compact JWE\n' +
    '    at compactDecrypt (webpack-internal:///(rsc)/./node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js:18:15)\n' +
    '    at jwtDecrypt (webpack-internal:///(rsc)/./node_modules/jose/dist/node/cjs/jwt/decrypt.js:10:61)\n' +
    '    at Object.decode (webpack-internal:///(rsc)/./node_modules/next-auth/jwt/index.js:44:52)\n' +
    '    at async Object.session (webpack-internal:///(rsc)/./node_modules/next-auth/core/routes/session.js:25:34)\n' +
    '    at async AuthHandler (webpack-internal:///(rsc)/./node_modules/next-auth/core/index.js:161:37)\n' +
    '    at async getServerSession (webpack-internal:///(rsc)/./node_modules/next-auth/next/index.js:126:21)\n' +
    '    at async GET (webpack-internal:///(rsc)/./app/api/newwatchlist/route.ts:11:21)\n' +
    '    at async D:\\Coding Projects\\market-pulse\\node_modules\\next\\dist\\compiled\\next-server\\app-route.runtime.dev.js:6:61856',
  name: 'JWEInvalid'
}

session is then null.

I don't have access to a response object to pass the normal getServerSession(req, res, authOptions) method (as far as I know).

How do I get the session corresponding to the HTTP request with Next's new API routes?

Note: I am using the MongoDB adapter.

Update: I also tried taking res: NextApiResponse as a parameter and then fetching the session with const session = await getServerSession(req, res, authOptions);. However, this results in TypeError: res.getHeader is not a function.


Solution

  • Turns out I just need to pass authOptions and neither res nor req: const session = await getServerSession(authOptions);

    Then, my whole function looks like this:

    export async function GET(req: NextApiRequest) {
        const session = await getServerSession(authOptions);  
        console.log(session);
        return NextResponse.json({ error: "Unauthorized" }, { status: 401 }; 
    }