Middleware is not working in Next js v15.4.0

import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";

export async function middleware(request: NextRequest) {
const sessionCookie = getSessionCookie(request, {
cookieName: "session_token",
cookiePrefix: "auth_token",
// useSecureCookies:
// request.nextUrl.protocol === "https:" ||
// process.env.NODE_ENV === "production",
});

const { pathname } = request.nextUrl;

const publicRoutes = [
"/signup",
"/login",
"/forgot-password",
"/reset-password",
"/",
];

// If the user is logged in, prevent access to /signup and /login
if (sessionCookie && publicRoutes.includes(pathname)) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}

// If the user is NOT logged in, protect the /dashboard route
if (!sessionCookie && pathname.startsWith("/dashboard")) {
return NextResponse.redirect(new URL("/login", request.url));
}

return NextResponse.next();
}

export const config = {
matcher: [
"/",
"/dashboard/:path*",
"/signup",
"/login",
"/forgot-password",
"/reset-password",
],
};
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";

export async function middleware(request: NextRequest) {
const sessionCookie = getSessionCookie(request, {
cookieName: "session_token",
cookiePrefix: "auth_token",
// useSecureCookies:
// request.nextUrl.protocol === "https:" ||
// process.env.NODE_ENV === "production",
});

const { pathname } = request.nextUrl;

const publicRoutes = [
"/signup",
"/login",
"/forgot-password",
"/reset-password",
"/",
];

// If the user is logged in, prevent access to /signup and /login
if (sessionCookie && publicRoutes.includes(pathname)) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}

// If the user is NOT logged in, protect the /dashboard route
if (!sessionCookie && pathname.startsWith("/dashboard")) {
return NextResponse.redirect(new URL("/login", request.url));
}

return NextResponse.next();
}

export const config = {
matcher: [
"/",
"/dashboard/:path*",
"/signup",
"/login",
"/forgot-password",
"/reset-password",
],
};
1 Reply
Anuj
AnujOP3mo ago
Issue resolved by this example import { betterFetch } from "@better-fetch/fetch"; import type { auth } from "@/lib/auth"; import { NextRequest, NextResponse } from "next/server"; type Session = typeof auth.$Infer.Session; export async function middleware(request: NextRequest) { const { data: session } = await betterFetch<Session>("/api/auth/get-session", { baseURL: request.nextUrl.origin, headers: { cookie: request.headers.get("cookie") || "", // Forward the cookies from the request }, }); if (!session) { return NextResponse.redirect(new URL("/sign-in", request.url)); } return NextResponse.next(); } export const config = { matcher: ["/dashboard"], // Apply middleware to specific routes };

Did you find this page helpful?