Ollie1700
Advice on authentication guards with server middleware
Hi everyone, I was hoping to get some advice on how to handle custom auth within Nuxt. (It's worth noting we're deliberately not using a package, because we have a lot of auth code already that is custom and being re-used for this app)
Right now, I have four pieces set up:
- Various
server
auth endpoints to login, set session cookie, verify session
- Composable useUserSession
that gets the session with a useFetch('/api/session')
- Nuxt middleware that redirects to /login
if not logged in / expired token
- Server middleware that checks if the token is valid (for API routes that will be called from the client)
The problem I have is that the server middleware is hit before any Nuxt middleware, so any request is blocked with a 401 immediately - even the login page. And I know I should not be redirecting in server middleware because then we look at an infinite loop on the middleware.
I added "allowed routes" to the middleware, but then that means I'd have to add every single frontend page to the allowed routes in order for them to then be correctly redirected via nuxt middleware.
I know this can't be the answer - am I missing an obvious development pattern here?
Thanks very much in advance for your advice.7 replies