I’m building a Next.js(14.2.5) web app with Auth.js (Next-auth ^5.0.0-beta.20) for authentication and Prisma (client version 5.18.0) as an ORM. I have extended the session to include 2 extra attributes: a list of roles of the authenticated user and a boolean “blocked” attribute. The problem is I also need access to those attributes in the middleware. Since I’m using Prisma I divided the NextAuth() initialization into two different files. Here is how it looks:
Auth.ts
import NextAuth, { type DefaultSession } from "next-auth";
import { PrismaAdapter } from "@auth/prisma-adapter";
import { db } from "@/lib/db";
import { getUserById } from "./services/User";
import { URole } from "@prisma/client";
import authConfig from "./auth.config";
declare module "next-auth" {
interface Session {
user: {
roles: URole[];
blocked: boolean;
} & DefaultSession["user"];
}
}
export const {
handlers: { GET, POST },
signIn,
signOut,
auth,
} = NextAuth({
events: {
async linkAccount({ user }) {
await db.user.update({
where: { id: user.id },
data: { emailVerified: new Date() },
});
},
},
callbacks: {
async signIn({ user, account }) {
if (account?.provider !== "credentials") return true;
let existingUser = null;
if (user.id) {
existingUser = await getUserById(user.id);
} else {
throw new Error("undefined user.id on SignIn");
}
if (!existingUser || !existingUser.emailVerified) {
return false;
}
// add 2fa
return true;
},
async session({ token, session }) {
//console.log({ "session token": token });
if (token.sub && session.user) {
session.user.id = token.sub;
}
if (token.role && session.user) {
//console.log({ TokenLog: token.role });
session.user.roles = token.role as URole[];
session.user.blocked = token.blocked as boolean;
}
return session;
},
async jwt({ token }) {
if (!token.sub) return token;
const existingUser = await getUserById(token.sub);
if (!existingUser) return token;
token.role = existingUser.roles;
token.blocked = existingUser.blocked;
return token;
},
},
adapter: PrismaAdapter(db),
session: { strategy: "jwt" },
...authConfig,
});
auth.config.ts
import type { NextAuthConfig } from "next-auth";
import bcrypt from "bcryptjs";
import Credentials from "next-auth/providers/credentials";
import Google from "next-auth/providers/google";
import { LoginSchema } from "../schemas";
import { getUserByEmail } from "./services/User";
export default {
providers: [
Google({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
Credentials({
credentials: {
username: { label: "name", type: "text" },
password: { label: "password", type: "password" },
},
async authorize(credentials) {
const validateFields = LoginSchema.safeParse(credentials);
if (validateFields.success) {
const { email, password } = validateFields.data;
const user = await getUserByEmail(email);
if (!user || !user.password) {
return null;
}
const passwordMatch = await bcrypt.compare(password, user.password);
if (passwordMatch) {
return user;
}
}
return null;
},
}),
],
} satisfies NextAuthConfig;
middleware.ts
import authConfig from "./auth.config";
import NextAuth from "next-auth";
const { auth } = NextAuth(authConfig);
//import { auth } from "@/auth"
import {
DEFAULT_LOGIN_REDIRECT,
apiAuthPrefix,
authRoutes,
publicRoutes,
} from "@/routes";
import { hasPermission } from "./services/Permission";
export default auth((req) => {
const { nextUrl } = req;
const isLoggedIn = !!req.auth;
const session = req.auth;
const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
const isAuthRoute = authRoutes.includes(nextUrl.pathname);
const isAdminRoute = nextUrl.pathname.includes("/dashboard");
console.log("Route: ", nextUrl.pathname);
console.log(session)
if (isApiAuthRoute) {
return;
}
if (isAuthRoute) {
if (isLoggedIn) {
return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl));
}
return;
}
if (!isLoggedIn && !isPublicRoute) {
return Response.redirect(new URL("/login", nextUrl));
}
if (
session &&
isAdminRoute &&
!hasPermission(session.user, "adminRoutes", "view")
) {
return Response.redirect(new URL("/", nextUrl));
}
});
export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
"/((?!_next|[^?]*\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
// Always run for API routes
"/(api|trpc)(.*)",
],
};
With this configuration, the extra attributes do not appear in the middleware in the “session = req.auth” line. If I move the callbacks from the auth.ts file to the auth.config.ts file (or if I just put everything in one file) everything works as intended but then Prisma sends this warning:
[Error: PrismaClient is not configured to run in Edge Runtime (Vercel Edge Functions, Vercel Edge Middleware, Next.js (Pages Router) Edge API Routes, Next.js (App Router) Edge Route Handlers or Next.js Middleware). In order to run Prisma Client on edge runtime, either:
- Use Prisma Accelerate
- Use Driver Adapters
Is there any workaround to this issue? I do not want to deploy to the edge, however, I understand that next.js middleware runs on edge runtime anyway. Is this correct?
Also I do not directly use the db inside the middleware.ts file.
Any advice will be greatly appreciated.