Issue with JWT auth in Nuxt 3 SSR
Hello everyone!
I'm experiencing an issue with JWT authentication in my Nuxt 3 SSR application. The problem occurs when trying to access protected routes directly (by entering the URL) rather than navigating through the app.
Current setup:
- Using middleware to check if a user is logged in and redirect to login if necessary
- Access token is stored in an auth store (Pinia)
- Refresh token is stored in an HttpOnly cookie
- Auth middleware checks token validity and refreshes if needed (sends a request to refresh token endpoint with refresh token cookie)
The issue:
When navigating within the app using Nuxt Link, everything works as expected. If the access token is invalid, a request is sent to refresh it, and I can access protected routes normally.
However, when I try to access a protected route directly by entering its URL, the middleware seems to run on the server-side without access to the HttpOnly cookie containing the refresh token. As a result, the refresh request fails, and I'm unable to access the protected route.
Could you please help me what's the best way to fix it?
middleware/auth.ts:
STORE/auth.ts
3 Replies
I used useCookie() in refreshToken function and it's working good. But is it a good way to do auth?
I have exactly the same question, did you manage the refresh token on SSR?
I am unable to find the resources, but it seems that Pinia cannot be accessed during server-side rendering (SSR), so you will need to create a plugin. I am currently using
auth.server.ts
under plugins. You can use functions such as useRequestEvent()
, appendResponseHeader
, and parseCookies
from "h3". You can utilize cookies with these functions. Instead of Pinia, I am using useState
because it is the safest way for Nuxt payloads, and it works on both the server and client sides.
For HttpOnly cookies, here is an example:
Auth cookie string is gathered from parseCookies
.