Skip to content

v4: Mounted routes are not reached with trailingSlash: true in next.config.js #1938

@kkowalczuk

Description

@kkowalczuk

Checklist

Description

After following the V4 migration guide and enabling route protection via middleware:

export async function middleware(request: NextRequest) {
  const authRes = await auth0.middleware(request)

  // authentication routes — let the middleware handle it
  if (request.nextUrl.pathname.startsWith("/auth")) {
    return authRes
  }

  const { origin } = new URL(request.url)
  const session = await auth0.getSession()

  // user does not have a session — redirect to login
  if (!session) {
    return NextResponse.redirect(`${origin}/auth/login`)
  }

  return authRes
}

All the unauthorized requests (when there's no session data yet - user is not logged in) end up hitting /auth/login/ (note the trailing slash) which resolves in 404 (Not Found) page being displayed when trailingSlash: true option is enabled in next.config.js. Removing the trailingSlash configuration or setting it to false fixes the problem, but I do not think the library clients should be forced to disable it.

Reproduction

  1. Use the middleware from V4 migration guide to protect the routes and redirect to /auth/login when the session data is missing;
  2. Add trailingSlash: true option to your next.config.js;
  3. Hit any of your application's routes (or <your_app_url>/auth/login directly) in Incognito;
  4. Expect the generic 404 (or custom /_not-found page) to be displayed and <your_app_url>/auth/login/ in the URL bar after being redirected to <your_app_url>/auth/login.

Additional context

When trailingSlash option is set to true, req.nextUrl.pathname contains the trailing slash, hence this exact pathname check from auth-client.ts evaluates to false and does not intercept the request with the handleLogin call. Same happens with other URL-based conditions defined in handler.

nextjs-auth0 version

4.0.2

Next.js version

14.2.13

Node.js version

20.18.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions