如何为next.js中间件创建动态的受保护路由

6ie5vjzr  于 2023-01-05  发布在  其他
关注(0)|答案(1)|浏览(196)

我创建了一个文件routes.ts来存储我想要保护的路由。这对常规路由有效,比如我的“/profile”路由,但是当我尝试添加动态url时,它不起作用(未经身份验证的用户仍然可以查看这些路由)。
routes.ts

export const protectedRoutes = ["/profile", "/profile/[id]", "/timeline/[id]", "/"];
export const authRoutes = ["/login"];
export const publicRoutes = [];

middleware.ts

export function middleware(request: NextRequest) {
  const currentUser = request.cookies.get("currentUser")?.value;

  if (
    protectedRoutes.includes(request.nextUrl.pathname) &&
    (!currentUser || Date.now() > JSON.parse(currentUser).expiredAt)
  ) {
    request.cookies.delete("currentUser");
    const response = NextResponse.redirect(new URL("/login", request.url));
    response.cookies.delete("currentUser");

    return response;
  }

  if (authRoutes.includes(request.nextUrl.pathname) && currentUser) {
    return NextResponse.redirect(new URL("/profile", request.url));
  }
}```


I have logged out of my application and tried to view the dynamic routes. If my code was correct, I should have been rerouted to my login page, however, it still shows the data even though I am not authenticated. To make sure the protected routes work, I viewed my static routes, and was successfully rerouted to the login page.
holgip5t

holgip5t1#

尝试在中间件中创建一个config变量,并将中间件应用到您要保护的路由上。例如,您可以将此变量添加到动态路由的middleware中:

export const config = {
    matcher: ["/profile/:path*", "/timeline/:path*"]
};

请注意,如果在中间件中包含config,中间件将只应用于matcher数组中的路由。我只是为您的动态路由添加了上述代码作为示例。
matcher是要在其上应用中间件的路由数组。它支持通配符语法,因此您可以为动态路由匹配一组路由。例如,/profile/:path*部分将在以/profile开头的所有路由上应用中间件。它将匹配/profile/123等路由。了解有关configmatcherhere的更多信息。

相关问题