Adding an auth token to $fetch only works after full page refresh, how to fix?

Hi, I am trying to add my auth token to fetch requests if the user is authenticated, and I have created a Nuxt plugin for this that exposes a custom $fetch instance.

import { useUserStore } from "@/store/user.store";

export default defineNuxtPlugin({
    setup() {
        const userStore = useUserStore();
        const token = computed(() => userStore.readToken);

        console.log("TOKEN ", token.value);

        const api = $fetch.create({
            baseURL: useRuntimeConfig().public.apiUrl,
            headers: {
                "Content-Type": "application/json",
                ...(token && token.value ? { Authorization: `${token.value}` } : {}),
            },
        });

        return {
            provide: {
                api,
            },
        };
    },
});


However, when I run this code it works only after I perform a full page refresh after loggin in. When logging in and navigating to a page that makes a request that requires a token, the token is not included. Only when I fully refresh the page, the token seems to be added.

How can I fix this?
Was this page helpful?