Middleware for Next Js application(payload cms 3.0)

import { NextRequest, NextResponse } from "next/server";
 
const LOGIN_COOKIE_NAME = "payload-token";
 
export function middleware(request: NextRequest) {
    const { pathname } = request.nextUrl;
 
    // Allow static files and API routes to pass through
    if (
        pathname.startsWith('/_next/') ||
        pathname.startsWith('/static/') ||
        pathname.startsWith('/api/') ||
        pathname === '/login' ||
        pathname === '/forgot-password' ||
        pathname === '/reset-password' ||
        pathname === '/recover-password'
    ) {
        return NextResponse.next();
    }
 
    // Get the login cookie
    const loginCookie = request.cookies.get(LOGIN_COOKIE_NAME);
    // console.log("loginCookie", loginCookie);
 
    // Check if the login cookie is present
    const isLoggedIn = !!loginCookie;
 
    // If logged in and trying to access /login, redirect to the home page
    if (isLoggedIn) {
        return NextResponse.next();
    }
 
    // If not logged in, redirect all routes to /login
    if (!isLoggedIn && pathname !== "/login") {
        return NextResponse.redirect(new URL("/login", request.url));
    }
 
    return NextResponse.next();
}
 
// Configure the middleware to apply to all routes
export const config = {
    matcher: "/:path*",
};

Place this file as middleware.ts in the src directory.

Inly the path starts with  pathname.startsWith(‘/_next/’) ||

        pathname.startsWith(‘/static/’) ||

        pathname.startsWith(‘/api/’) ||

        pathname === ‘/login’ ||

        pathname === ‘/forgot-password’ ||

        pathname === ‘/reset-password’ ||

        pathname === ‘/recover-password’

will be if user is not logged in.

Leave a comment

Your email address will not be published. Required fields are marked *