Next.js Discord

Discord Forum

Is my next-auth options written correctly?

Answered
Alligator mississippiensis posted this in #help-forum
Open in Discord
Alligator mississippiensisOP
[next/js ^12.3.4, next-auth ^4.12.3, prisma 5.3.1, next-auth/prisma-adapter 1.0.7]

I have a bug where using next-auth getSession works in the server (getServerSideProps):

export async function getServerSideProps(context) { const session = await getSession(context); }


But does not work on my api routes:
export default async function handler(req, res) { const session = await getSession({ req, res }); if (!session) { res.status(401).json({ message:No session found, }); } }

What happens: When I use the api file, it returns 401 for no session was found.
It happens even though the session exists in the client (was loaded using getServerSideProps).

So I wonder, is my auth-options written incorrectly?

import { PrismaAdapter } from '@next-auth/prisma-adapter'; import GoogleProvider from 'next-auth/providers/google'; import prisma from 'prisma/index'; import { getPaymentAccountRecord } from 'pages/api/customer/get-payment-account'; export const authOptions = { adapter: PrismaAdapter(prisma), session: { strategy: 'jwt', }, pages: { error: '/', signIn: '/login', }, providers: [ GoogleProvider({ clientId: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID, clientSecret: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_SECRET, }), ], callbacks: { session: async ({ token, session }) => { if (token) { session.user.id = token.id; session.user.name = token.name; session.user.email = token.email; } return session; }, async jwt({ token, user }) { const dbUser = await prisma.user.findFirst({ where: { email: token.email, }, }); if (!dbUser) { token.id = user.id; return token; } return { id: dbUser.id, name: dbUser.name, email: dbUser.email, }; }, }, secret: process.env.NEXT_PUBLIC_NEXTAUTH_SECRET || null, };
Answered by Satin Angora
https://next-auth.js.org/configuration/nextjs#in-api-routes

Use getServerSession in serverside components / api routes.
const session = await getServerSession(authOptions)
View full answer

3 Replies

Alligator mississippiensisOP
up
Satin Angora
https://next-auth.js.org/configuration/nextjs#in-api-routes

Use getServerSession in serverside components / api routes.
const session = await getServerSession(authOptions)
Answer