Reputation: 93
I'm developing an application using Next.js 13 and Next-Auth. Initially, I configured the JWT strategy with the Google provider and used the Next-Auth middleware to secure routes. My configuration was as follows:
export { default } from "next-auth/middleware"
export const config = { matcher: ['/((?!api/auth|_next/static|_next/image|favicon.ico|login).*)',] }
This setup worked fine until I switched to using the Prisma adapter. After the change, the middleware started rejecting all requests, even with the user signed in. Both getServerSession
and useSession
still return the user data correctly.
Upon reviewing the middleware's implementation, it seems to be designed to work with the JWT strategy. Can anyone confirm if this is accurate?
If so, how should I adapt the middleware for the Prisma adapter? My current workaround involves making an additional fetch request to /auth/session
with the session token cookie for every request as shown below:
import { withAuth } from 'next-auth/middleware'
export default withAuth(
{
callbacks: {
authorized: async ({ req: { cookies } }) => {
const secureCookie = process.env.NEXTAUTH_URL?.startsWith("https://") ?? !!process.env.VERCEL;
const cookieName = secureCookie ? "__Secure-next-auth.session-token" : "next-auth.session-token";
const session = await (await fetch('http://localhost:3000/api/auth/session', { method: 'GET', headers: { 'Cookie': `${cookieName}=${cookies.get(cookieName)?.value}` } })).json();
return !!session.user;
},
},
}
)
export const config = { matcher: ['/((?!api/auth|_next/static|_next/image|favicon.ico|login).*)',] }
Is this the best solution or is there a more efficient way to handle this? Any insights or suggestions would be greatly appreciated. Thank you in advance!
Upvotes: 5
Views: 1349
Reputation: 31
I have the same issue, currently the only solution is forcing a JWT session by explicitly defining "jwt"
in authOption
like this. If you skip to define session and use adapter, it will use session strategy automatically. And seems next-auth/middleware
doesn't handle this scenario.
session: {
strategy: 'jwt',
},
Actually I prefer this way because I don't need to save session token in my database and can leverage JWT features while keep everything else in database (user email, oauth provider etc.)
Here explains why middleware doesn't support database session strategy. https://github.com/nextauthjs/next-auth/discussions/4265
Upvotes: 3