-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Runtime Error: Authentication crash when using PrismaAdapter (mongodb) - TypeError: Cannot read properties of undefined (reading 'exec') #12731
Comments
The @auth/prisma-adapter version ^2.8.0 is not compatible with next-auth version ^5.0.0-beta.25. To resolve this issue, revert to @auth/prisma-adapter version 2.7.2 and install it without the ^ symbol to prevent unintended updates. |
Thanks I will try it |
I am having the same error with a similar stack :
using PostgreSQL / Neon (I don't think the actual DB is related to this issue). Thankfully, I got this error at build time, this was a bit more explicit than your logs :
For reference, the source of the related files // Following this guide
// https://authjs.dev/getting-started/adapters/prisma
import { PrismaAdapter } from "@auth/prisma-adapter";
import type { PrismaNeon } from "@prisma/adapter-neon";
import type { PrismaClient } from "@prisma/client";
import type { NextAuthConfig } from "next-auth";
import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";
import prisma from "@/lib/prisma";
export const { handlers, auth, signIn, signOut } = NextAuth({
providers: [GitHub],
callbacks: {
session({ session, user }) {
// As seen on https://authjs.dev/guides/role-based-access-control
if (user?.id) session.user.id = user.id;
if (user?.role) session.user.role = user.role;
return session;
},
},
adapter: PrismaAdapter(
prisma as PrismaClient<{ adapter: PrismaNeon }>,
) as NextAuthConfig["adapter"], // Need to type cast as we extend the payload of session
});
// Only one middleware, used to refresh the token
export { auth as middleware } from "@/lib/auth"; @activemonkeys @th3f0r3ign3r not that it fixes the current problem, in my case I was able to lock version |
I almost forgot my problem is solved |
Great 👍 I will try |
Shit like this is exactly why I hate but also love NextAuth, Auth.js, whatever we call it today. |
@th3f0r3ign3r I am not sure why you consider this issue solved, I think prisma-adapter |
my bad though |
Same here, for PrismaAdapter with Postgres |
This comment has been minimized.
This comment has been minimized.
Thanks for pointing this out! I was facing the same issue, and downgrading |
Great! After wrestling with this issue the whole weekend in a newly created NextJS project, this was the solution. Initially thought it was a NextJS v15 problem. |
@Lucas070713 I end up creating my own middleware to handle the authentication instead of relying on the one provided by auth.js and that work for me if you want, I can share that with you as well. |
@i-naeem generator client {
provider = "prisma-client-js"
previewFeatures = ["driverAdapters"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
} What kind of middleware should be implemented that does not depend on auth.js? |
This is the one I am referring to. try to remove the middleware for a moment and see if your app works correctly. export { auth as middleware } from "@/auth";
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* Feel free to modify this pattern to include more paths.
*/
{
source:
"/((?!api|webhook|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|mp3)$).*)",
missing: [
{ type: "header", key: "next-router-prefetch" },
{ type: "header", key: "purpose", value: "prefetch" },
],
},
],
}; |
@i-naeem callbacks: {
authorized({ request: { nextUrl }, auth }) {
const isLoggedIn = !!auth?.user;
const { pathname } = nextUrl;
const role = auth?.user.role || "GUEST";
const publicPaths = ["/auth/signin", "/auth/signout"];
console.log(nextUrl, auth);
if (!isLoggedIn || role === "GUEST") {
if (!publicPaths.includes(pathname)) {
return Response.redirect(new URL("/auth/signin", nextUrl));
}
}
return !!auth;
},
jwt({ token, user }) {
if (user) {
token.id = user.id as string;
token.role = user.role as string;
}
return token;
},
session({ session, token }) {
session.user.id = token.id;
session.user.role = token.role;
return session;
},
}, |
You will have to check out these two links if you want to make this middleware from auth.js to work Otherwise here is the middleware I wrote which worked for me. You can modify this one to add RBAC mechanism as well. import { NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';
const protectedRoutes = ['/dashboard'];
const authRoutes = ['/login', '/register']; // Routes to restrict for logged-in users
export async function middleware(req) {
const sessionToken = req.cookies.get('authjs.session-token')?.value;
const currentPath = req.nextUrl.pathname;
// Check if user is authenticated
let isAuthenticated = false;
if (sessionToken) {
try {
const decodedToken = await getToken({ req, secret: process.env.AUTH_SECRET });
isAuthenticated = !!decodedToken;
} catch (error) {
console.error('Failed to decode session token:', error);
}
}
// Redirect unauthorized users trying to access protected routes
if (protectedRoutes.some(route => currentPath.startsWith(route))) {
if (!isAuthenticated) {
return NextResponse.redirect(new URL('/login', req.url));
}
}
// Redirect logged-in users away from login or register pages
if (isAuthenticated && authRoutes.includes(currentPath)) {
return NextResponse.redirect(new URL('/dashboard', req.url)); // Redirect to dashboard or another page
}
return NextResponse.next();
}
export const config = {
matcher: ['/dashboard/:path*', '/login', '/register'], // Apply middleware to relevant routes
}; |
@i-naeem middleware.ts import { getToken } from "next-auth/jwt";
import { NextRequest, NextResponse } from "next/server";
const publicPaths = ["/auth/signin", "/auth/signout"];
const authPaths = ["/auth/signin"];
export async function middleware(req: NextRequest) {
const sessionToken = req.cookies.get("authjs.session-token")?.value;
const currentPath = req.nextUrl.pathname;
console.log(sessionToken);
let isAuthenticated = false;
if (sessionToken) {
try {
const decodedToken = await getToken({
req,
secret: process.env.AUTH_SECRET,
});
console.log(decodedToken);
isAuthenticated = !!decodedToken;
} catch (error) {
console.error("Failed to decode session token:", error);
}
}
console.log(isAuthenticated);
if (!publicPaths.includes(currentPath)) {
if (!isAuthenticated) {
return NextResponse.redirect(new URL("/auth/signin", req.url));
}
}
if (isAuthenticated && authPaths.includes(currentPath)) {
return NextResponse.redirect(new URL("/", req.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* Feel free to modify this pattern to include more paths.
*/
{
source:
"/((?!api|webhook|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|mp3)$).*)",
missing: [
{ type: "header", key: "next-router-prefetch" },
{ type: "header", key: "purpose", value: "prefetch" },
],
},
],
}; |
Resolved. |
good to hear and I am happy that I could help a little. |
Thank you so much for the help! I had the same issue, and following your suggestion to revert to @auth/prisma-adapter version 2.7.2 without the ^ fixed the problem. It worked perfectly! I really appreciate your guidance. |
Environment
Reproduction URL
https://github.com/th3f0r3ign3r/authjs-issue.git
Describe the issue
I have setting up Auth.js with Github Oauth and I decided to add PrismaAdapter with (mongodb) to save user account information. Without adding the adapter everything working great. But when I added the Adapter to
@/auth
it crashCleanShot.2025-03-04.at.19.35.44.mp4
How to reproduce
npx prisma generate
src/auth/index.ts
comment the adapters lineclear && npm run dev
don’t forget to runnpm i
Signin with GitHub
If you follow all these steps normally you will have the same error
Expected behavior
Normally they should not have any error. Instead I am doing something wrong but I follow the guide line per line. 😩😩😩
The text was updated successfully, but these errors were encountered: