Deprecation warning in middleware.ts while upgrading Next.js 15 #73156
-
SummaryI recently updated my project from Next.js 14 to Next.js 15. While running the project in development mode, I encountered the following warning:
The middleware in my project follows the documentation exactly. Additional informationNo response ExampleNo response |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
Hi @IlamathiIla Try to move your middleware to Also please check this article https://nextjs.org/docs/messages/invalid-page-config |
Beta Was this translation helpful? Give feedback.
-
The same thing happens to me also. But for some reason only if I add a call to getSessionUser inside the middleware function and then restart the developer server. middleware.ts (inside of the root folder) // 1. Ignore certain paths
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)"],
};
export default async function middleware(req: NextRequest) {
// 2. Get the currently logged in user
const user = await getSessionUser();
// 3. Redirect
if (user) {
if (sharedPages.some((page) => page.path === req.nextUrl.pathname)) return NextResponse.rewrite(new URL("/private/shared" + req.nextUrl.pathname, req.nextUrl));
switch (user.type) {
case "user":
if (userPages.some((page) => page.path === req.nextUrl.pathname)) return NextResponse.rewrite(new URL("/private/user" + req.nextUrl.pathname, req.nextUrl));
break;
case "admin":
if (adminPages.some((page) => page.path === req.nextUrl.pathname)) return NextResponse.rewrite(new URL("/private/admin" + req.nextUrl.pathname, req.nextUrl));
break;
default:
throw new Error(`Invalid user type ${user.type}`);
}
} else return NextResponse.rewrite(new URL("/public", req.nextUrl));
return NextResponse.next();
} // The function that triggers the deprecation warning if called inside middleware.ts - it is imported from a different file
export async function getSessionUser(): Promise<SessionUser | null> {
const cookieStore = await cookies();
const cookie = cookieStore.get(session_cookie_name)?.value;
if (!cookie) return null;
return decryptSessionUser(cookie);
} async function decryptSessionUser(session: string): Promise<SessionUser | null> {
try {
const { payload } = await jwtVerify(session, encodedKey, {
algorithms: ["HS256"],
});
if (typeof payload.id !== "number" || typeof payload.name !== "string" || typeof payload.email !== "string" || userTypes.includes(payload?.type as User["type"]) === false) throw new Error("Invalid session payload");
const user = {
id: payload.id,
name: payload.name as string,
email: payload.email as string,
avatar: (payload.avatar ?? null) as string | null,
type: payload.type as User["type"],
};
return user;
} catch (error) {
return null;
}
} |
Beta Was this translation helpful? Give feedback.
-
This happened to me after upgrading from version 14 to 15. I was trying to figure out which part of my middleware was causing the issue by commenting out code blocks and refreshing the page. Once I commented out the code related to identifying the user's locale: // export function getLocale(request: NextRequest): string {
// // Check for cookie first
// const cookieLocale = request.cookies.get("NEXT_LOCALE");
// if (cookieLocale) {
// if (isEnglishLocale(cookieLocale.value)) {
// return "en";
// }
// if (locales.includes(cookieLocale.value)) {
// return cookieLocale.value;
// }
// }
// // Negotiate based on Accept-Language header
// let headers = new Headers(request.headers);
// let acceptLanguage = headers.get("accept-language");
// if (acceptLanguage) {
// let languages = new Negotiator({
// headers: { "accept-language": acceptLanguage },
// }).languages();
// console.log("acceptLanguage", acceptLanguage);
// const englishLocale = languages.find(isEnglishLocale);
// if (englishLocale) {
// return "en";
// }
// const matched = match(languages, locales, defaultLocale);
// console.log("matched", matched);
// return matched;
// }
// return defaultLocale;
// }
export async function middleware(request: NextRequest) {
// .... YOUR MIDDLEWARE CODE .... //
}
export const config = {
matcher: [
"/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
],
}; the error is gone, and then I just moved the locale logic out of the middleware. |
Beta Was this translation helpful? Give feedback.
-
I encountered the same warning. The weird thing is the warning only showed when I used The version of Next.js is 15.2.4, and next-auth is 5.0.0-beta.25. // middleware.ts
import { auth } from "@/middlewares/auth"
export default auth;
export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$|$).*)']
} // auth.ts
import NextAuth from "next-auth";
import type { NextAuthConfig, User } from "next-auth";
import Credentials from "next-auth/providers/credentials";
import { NextResponse } from "next/server";
import { z } from "zod";
import prisma from "@/lib/database-client";
import bcrypt from "bcryptjs";
export const { auth, signIn, signOut } = NextAuth({
pages: {
signIn: "/login",
},
callbacks: {
authorized({ request: { nextUrl }, auth }) {
const isLoggedIn = !!auth?.user;
if (nextUrl.pathname !== "/login" && nextUrl.pathname !== "/signup") {
return isLoggedIn;
} else if (isLoggedIn) {
return NextResponse.redirect(new URL("/moments", nextUrl));
}
return true;
},
jwt({ token, user }) {
if (user) {
token.id = user.id;
}
return token;
},
session({ session, token }) {
if (token) {
session.user.id = token.id as string;
}
return session;
},
},
providers: [
Credentials({
async authorize(credentials): Promise<User | null> {
const parsedCredentials = z.object({
email: z.string().email(),
password: z.string().min(8),
}).safeParse(credentials);
if (!parsedCredentials.success) {
return null;
}
const { email, password } = parsedCredentials.data;
const user = await prisma.user.findUnique({
where: { email: email }
});
if (!user || !await bcrypt.compare(password, user.password)) {
return null;
}
return {
id: user.userId,
name: user.name,
email: user.email,
};
}
})
],
} satisfies NextAuthConfig); using |
Beta Was this translation helpful? Give feedback.
The same thing happens to me also. But for some reason only if I add a call to getSessionUser inside the middleware function and then restart the developer server.
middleware.ts (inside of the root folder)