Search code examples
regexnext.jsnext-auth

What is the regular expression for all pages except "/"?


I am using NextAuth for Next.js for session management. In addition, I am using the middleware.js to protect my routes from unauthenticated users.

According to https://nextjs.org/docs/advanced-features/middleware#matcher, if we want to exclude a path, we do something like

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - static (static files)
     * - favicon.ico (favicon file)
     */
    '/((?!api|static|favicon.ico).*)',
  ],
}

In this example, we exclude /api, /static,/favicon.icon. However, I want to exclude all path except the home page, "/". What is the regular expression for that? I am tried '/(*)'. It doesn't seem to work.


Solution

  • I will need to exclude the signin page and register page as well. Because, it will cause an infinite loop and an error, if you don't exclude signin page. For register page, you won't be able to register if you are redirected to the signin page.

    So the "/", "/auth/signin", and "/auth/register" will be excluded. Here is what I needed:

    export const config = { 
        matcher: [
            '/((?!auth).*)(.+)'
        ] 
    }