Utilizing NextAuth in conjunction with Next.js's App Router, I have established an API route within my /app/api directory. Despite my efforts, I am encountering difficulties retrieving the session associated with the incoming request.
Below is the snippet of my API route, invoked using 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 });
}
Upon executing the code above, the server yields the following error message:
[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'
}
The value of session
is subsequently null.
Regrettably, I lack access to a response object required for the typical
getServerSession(req, res, authOptions)
method.
In this scenario, how can I retrieve the session linked to the HTTP request within Next's new API routes?
Important note: My setup involves using the MongoDB adapter.
Update: I also experimented with introducing res: NextApiResponse
as a parameter, followed by attempting to fetch the session using
const session = await getServerSession(req, res, authOptions);
. Nevertheless, this led to an error TypeError: res.getHeader is not a function
.