Middleware Advanced
Middleware Advanced ~10 mins - nextjs

Middleware - Checking paths

   
export async function middleware(request: NextRequest) {

console.log("Middleware request url: " + request.url);
const path = request.nextUrl.pathname;
// logic
}

1. Allow Internal Paths

    const PUBLIC_FILE = /\.(.*)$/;
if (
path.startsWith("/_next") ||
path.startsWith("/api") ||
path.startsWith("/static") ||
PUBLIC_FILE.test(path)
) {

return NextResponse.next();

}

2. Public Paths

    const publicPaths = ["/"];
const isPublicPath = publicPaths.includes(path);
if (isPublicPath) {
return;
}

3. Private Paths

    const unAuthenticatedRoute = [
"/login",
"/signup",
];
const isUnAuthenticatedPath = unAuthenticatedRoute.includes(path);

4. Token Exists Check

    const token = request.cookies.get("token")?.value || "";
console.log("Token:" + token );
if( token != null && token != "" ){
return NextResponse.next();
}else{
return NextResponse.redirect(new URL("/login", request.nextUrl));
}

5. Role Check

    const role = localStorage.getItem("role");
if(role == "ADMIN"){
return NextResponse.redirect(new URL("/admin/dashboard", req.nextUrl));
}else if (role=="USER"){
return NextResponse.redirect(new URL("/user/dashboard", req.nextUrl));
}else {
return NextResponse.redirect(new URL("/login", request.nextUrl));
}
    if ( role == "ADMIN" && path.includes("admin")) {
return NextResponse.next();
} else if ( role == "USER" && path.includes("user")) {
return NextResponse.next();
} else {
return NextResponse.redirect(new URL("/", req.nextUrl));
}

Configurations

    export const config = {
matcher: [
// Auth routes
"/",
"/login",
"/signup",

// Admin routes
"/admin/:path*",

// user routes
"/user/:path*",
],
};