Middleware cho nextjs 16
nextjs16_middleware\src\middleware.ts có tác dụng bảo vệ lớp đầu cho app :
import next from "next";
import { NextRequest, NextResponse } from "next/server";
const protectedRoutes = ["/dashboard", "/admin"];
export function middleware(req: NextRequest) {
const pathname = req.nextUrl.pathname;
console.log(pathname);
if (protectedRoutes.some(path => pathname.startsWith(path))) {
const token = req.cookies.get('token');
const loginUrl = new URL('/login', req.url);
if (!token) {
// redirect sang login nếu chưa có token
const loginUrl = new URL("/login", req.url);
return NextResponse.redirect(loginUrl);
}
return NextResponse.next(); // có token, cho phép tiếp tục
} else {
return NextResponse.next()
}
}
export const config = {
matcher: ["/admin/:path*"]
}
Kiểm tra token trong cookie nếu có thì có thể truy cập bên cạnh đó chưa kiểm tra thời gian hết hạn của token