I have successfully integrated Next Auth into a Next Js application, which utilizes apollo client and apollo server with graphql. I have set up OAuth with Google using Next Auth v5 that supports App Router. On the frontend, I am able to handle sign-in, sign-out, and manage sessions. However, when attempting to retrieve the session on the server using express middleware in my apollo express server, I encountered an error after installing 'next-auth@beta':
C:\Users\hamzz\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:851
return old(m, filename);
^
Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Hamza the Developer\ChatApp\next-chat\server\node_modules\next-auth\react.js from C:\Hamza the Developer\ChatApp\next-chat\server\api\index.ts not supported.
Instead change the require of react.js in C:\Hamza the Developer\ChatApp\next-chat\server\api\index.ts to a dynamic import() which is available in all CommonJS modules.
at require.extensions.<computed> [as .js] (C:\Users\hamzz\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:851:20)
at Object.<anonymous> (C:\Hamza the Developer\ChatApp\next-chat\server\api\index.ts:46:17)
at m._compile (C:\Users\hamzz\AppData\Roaming\npm\node_modules\ts-node\dist\index.js:857:29) {
code: 'ERR_REQUIRE_ESM'
}
[nodemon] app crashed - waiting for file changes before starting...
My goal is to access the session on the server using express middleware and getSession() from next-auth@beta.
app.use(
"/api/graphql",
//@ts-ignore
cors<cors.CorsRequest>(corsOptions),
json(),
expressMiddleware(server, {
context: async ({ req }): Promise<IContext> => {
if (!req.headers.cookie) {
return { session: null, prisma, pubsub };
}
const session = await getSession();
return {
session: session as Session,
pubsub,
prisma,
};
},
})
);