Report this

What is the reason for this report?

Nuxt 3 app using Httponly cookies losing authentification after page refresh

Posted on November 10, 2023
Sam

By Sam

Hi all,

I have a Nuxt 3 frontend and Django backend deployed on DigitalOcean App platform. Authentication is implemented using HttpOnly cookies, and the application works correctly locally. However, in the production environment, when a user refreshes the page, there is a slight delay during which it appears as though the user is not logged in.

// /plugins/auth.ts

import { useAuthUser } from "../composables/useAuthUser"

export default defineNuxtPlugin(async () => {
    const user = useAuthUser()

    if(!user.value) {
        const { fetchUser } = useAuth();

        await fetchUser();
    }
});

  1. The issue is specifically observed during page refresh in the production environment.
  2. The authentication state, managed by HttpOnly cookies, appears to resolve with a slight delay, leading to a brief period where it seems the user is not logged in.
  3. The problem does not occur in the local development environment.

Tested with Node.js versions 16.x and 20.x. The issue persists with both versions.

"engines": {
    "node": "20.x"
}

Thank you for any insights or suggestions provided.



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hey Sam,

This sounds like a hydration mismatch issue on page load, it happens when auth state is fetched async and the initial render doesn’t have it yet.

Since you’re using HttpOnly cookies, the client can’t read them directly, so useAuthUser() likely returns null on the first render, and only updates after fetchUser() completes. That delay is what causes the “not logged in” flash.

One way to reduce the flicker is to handle the user fetch during server-side rendering (if you’re not already), or delay rendering parts of the UI that depend on the auth state until fetchUser() completes.

Not 100% sure if it’s Nuxt config or timing-related, but might be worth double-checking how and when fetchUser() is called on the server vs client.

- Bobby

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.