Home > Back-end >  How to create dynamic, protected routes for next.js middleware
How to create dynamic, protected routes for next.js middleware

Time:01-04

I have created a file, routes.ts that stores routes I would like to protect. This works for regular routes, such as my '/profile' route, but when I try to add a dynamic url, it does not work (a user that is not authenticated can still view these routes).

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.

CodePudding user response:

Try creating a config variable in the middleware and apply the middleware on the routes you want to protect. For example you can add this to the middleware for the dynamic routes:

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

Please note if include the config in your middleware, the middleware will ONLY be applied to the routes in the matcher array. I just added the above code for the dynamic routes you had as an example.

The matcher is an array of routes to apply the middleware on. It supports the wildcard syntax so you can match a group of routes for the dynamic routes. For example, the /profile/:path* part will Apply the middleware on all the routes that starts with /profile. It will match the routes like /profile/123. Read more about config and matcher here.

  • Related