nextjs-auth0 icon indicating copy to clipboard operation
nextjs-auth0 copied to clipboard

withMiddlewareAuthRequired does not consider Next.js baseUrl when redirecting

Open Dalimil opened this issue 9 months ago • 1 comments

Checklist

  • [X] The issue can be reproduced in the nextjs-auth0 sample app (or N/A).
  • [X] I have looked into the Readme, Examples, and FAQ and have not found a suitable solution or answer.
  • [X] I have looked into the API documentation and have not found a suitable solution or answer.
  • [X] I have searched the issues and have not found a suitable solution or answer.
  • [X] I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • [X] I agree to the terms within the Auth0 Code of Conduct.

Description

withMiddlewareAuthRequired logic doesn't work for a custom auth0 instance with custom base URL set.

https://github.com/auth0/nextjs-auth0/blob/951a24864c61eec98702f91eb7784555d54916da/src/helpers/with-middleware-auth-required.ts#L93

It should be redirecting to /foo/api/auth/login/ instead of /api/auth/login when baseURL is set in auth0 config.

The issue comes from the fact that req.pathname that is used inside the function doesn't contain Nextjs base url prefix. In your code you are first checking that in the ignorePaths the login url doesn't match the pathname. And then you use the same login url to redirect. So your logic will break either during the ignorePath matching or later when you redirect (depending on whether in your config you have the base url part of the login url or not). This was already mentioned here: https://github.com/auth0/nextjs-auth0/issues/1118

Reproduction

  1. create an auth0 instance with initAuth0(config) where you set the baseURL to your custom url such as localhost:3000/foo
  2. use withMiddlewareAuthRequired inside your middleware.ts
  3. Access your app, you will be redirected to /api/auth/login instead of /foo/api/auth/login/

Additional context

Already discussed here: https://github.com/auth0/nextjs-auth0/issues/1118

nextjs-auth0 version

3.5.0

Next.js version

13.4.12

Node.js version

18.17.1

Dalimil avatar Apr 30 '24 23:04 Dalimil