How to handle auth token refresh with HTTP only cookies during SSR page load
nuxt4nitro🔓authnuxt3
I have an access token and refresh token. Both HTTP only cookies set by the Nuxt server after login.
If my access token expires while the user has left the site, when they re-visit during the initial SSR page load I:
- attempt to call /api/profile. This will return a 401 - in the fetch onResponse call /api/auth/refresh using requestFetch() to include the refresh cookie - /api/auth/refresh sets the 2 new HTTP only cookie tokens in the header response - /api/profile retries it's request again automatically because of fetch's config of
retry: 1, retryStatusCodes: [401]
retry: 1, retryStatusCodes: [401]
- /api/profile returns a 401 again because the access token from the intial page load is still missing (we've not yet returned the refresh response headers to the client)
This is all inside the SSR request lifecycle, I can't figure out how to utilise the new cookie response headers while making subsequent API calls that seem to fallback to using the original client cookies when the lifecycle started.
await $fetch<T>(url, { baseURL: config.public.platformApiBaseUrl, credentials: 'include', retry: 1, retryStatusCodes: [401], async onResponseError({ response }) { // // 401 may return from the /profile endpoint if (responseCode === 401) { await refreshTokens() } }, })
await $fetch<T>(url, { baseURL: config.public.platformApiBaseUrl, credentials: 'include', retry: 1, retryStatusCodes: [401], async onResponseError({ response }) { // // 401 may return from the /profile endpoint if (responseCode === 401) { await refreshTokens() } }, })