I already have a public REST API (PHP/Nginx) which is live and already being consumed, lets call it https://example.com/api/..
.
Now there has to come a GUI with authentication, to manage the API resources. The GUI should be accessible through the API’s main URL https://example.com
. I decided to use Next.js and next-auth 4.
next-auth 4’s routing uses /api/auth/*
by default. This works fine locally.
Now the problem is the deployment. When I go to https://example.com
, I see the UI build. As soon as I click on the login button, a route change to https://example.com/api/auth/error
happens, but showing the error output of the REST API (PHP/Nginx). This behavior makes sense for now, since the Webserver is configured in that way, that all /api
requests are calling the REST API entrypoint.
What I don’t want is to configure the webserver in such a way, that /api/auth
is ignored for calling the REST API entrypoint. Because it’s not only a webserver, its in a Kubernetes cluster, and this is complicated (we are using helmfile, helmcharts, etc.).
What I would like is the ability to customize the next-auth default authentication routing.
I tried with the basePath stuff, but I just get 404 errors, until I realized (if I unterstood correctly) that this feature is anyway only for when the entire UI has to come in a subpath, which is not in my case.
Is there any way to customize the next-auth /api/auth/*
path, without changing the basePath
?
When I just put pages/api
into pages/foo/api
, obviously on a page refresh I get GET http://localhost:3000/api/auth/session 404 (Not Found)
, because next-auth expects the api
folder to be in pages/
.
2
Answers
I guess it is not possible with next-auth 4 and the app router, at least this combination is not well documented.
It worked with next-auth 5 (still beta) and the app router:
app/api/auth
up toapp/auth
AUTH_URL
tohttp://my-host/auth
As far as I know, you just need to set the
NEXTAUTH_URL
env to whatever you want. In your case, something like:vercel
dev
This should change your requests to things like
http://localhost:3000/foo/api/auth/session
Now, for the Next.JS app to answer on this URL, you would need to add a
basePath
with the Pages router which you seem to use. As far as I know, Pages router only allows APIs in theapi
folder directly underpages
.With the new App router, you can create a folder path
app/foo/api/auth/[...nextauth]/route.ts
that should catch these. The good news is that you can combine both routers in the same app.