Using NextAuth v5 with a middleware

In this post, we'll see how to set up NextAuth v5 with middleware to protect specific pages in our application.

Implementing Middleware for Page Protection

To ensure that certain pages in our application are only accessible to authenticated users, we'll utilize middleware. This middleware will automatically direct users to the login page if they're not logged in, or redirect them to a designated page if they're already authenticated.

Begin by creating a middleware.ts file at the root of your project. Import the necessary dependencies:

import authConfig from "@/auth.config";
import NextAuth from "next-auth";

Here, we import authConfig from @/auth.config and the NextAuth module from the "next-auth" package.

Configure NextAuth by invoking the NextAuth function with the authConfig object:

const { auth } = NextAuth(authConfig);

The resulting object provides various functions and properties, including auth, which facilitates request authentication.

Define an array, authRoutes, containing the paths for login and registration pages:

const authRoutes = ["/auth/login", "/auth/register"];

Next, implement the middleware function:

export default auth((req) => {
  const isLoggedIn = !!req.auth;
  const isAuthRoute = authRoutes.includes(req.nextUrl.pathname);
  const isApiAuthRouter = req.nextUrl.pathname.startsWith("/api/auth");

  if (isApiAuthRouter) {
    return;
  }

  if (isAuthRoute) {
    if (isLoggedIn) {
      return Response.redirect(new URL("/dashboard", req.nextUrl));
    }
    return;
  }

  if (!isLoggedIn && !isAuthRoute) {
    return Response.redirect(new URL("/auth/login", req.nextUrl));
  }

  return;
});

Inside the middleware function, the following logic is executed:

  • Check if the request targets an API authentication route (/api/auth). If so, skip further processing.
  • Verify if the requested path is an authentication route (/auth/login or /auth/register). If it is and the user is logged in (isLoggedIn), redirect them to the dashboard page (/dashboard).
  • If the requested path is not an authentication route and the user is not logged in, redirect them to the login page (/auth/login).
  • If none of the above conditions are met, the middleware function doesn't perform any redirection.

Finally, export a configuration object specifying a matcher pattern to determine which routes should be intercepted by the middleware. Here, we match all routes except those starting with /api, _next/static, _next/image, or favicon.ico:

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
};

This setup ensures that the middleware effectively protects the specified pages while allowing seamless authentication flow for users accessing the application.

In this post, we have seen how to set up NextAuth v5 with middleware to protect specific pages in our application. You can read the full tutorial from this link.


  • Date: