NuxtN
Nuxt16mo ago
patchamamma

Nuxt Plugin using `useCookie` composable error.

Hi, I have a custom Auth fetch nuxt Plugin for fetching data behind a authentication. But I keep getting errors about using Nuxt composables.
I am using the useCookie composable. How should I run this function?:
Error:
 [nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug. Find out more at https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables.

My custom fetch plugin:
import { useAuthStore } from '~/store/auth';

export default defineNuxtPlugin((nuxtApp) => {
    const config = useRuntimeConfig()
    const store= useAuthStore()

    const $authFetch = $fetch.create({
        baseURL: config.public.apiBaseURL,
        onRequest: async function ({request, options, error}) {

            let userSession = useCookie('authToken').value;

            if(!userSession?.token || (!userSession?.expiration || new Date(userSession.expiration) <= new Date())) {
                console.log("RETRIEVE A NEW TOKEN PLEASE:")
                const refreshed = await store.refreshTokenAction();
                if(!refreshed) throw new Error('Token refresh failed. Aborting request.');
            }
            // Retrieve again, I could use refreshCookie()
            userSession = useCookie('authToken').value;

            if (userSession.token) {
                options.headers = options.headers || {}
                options.headers.Authorization = `Bearer ${userSession.token}`
            }
        },
        onRequestError({ request, options, error }) {
        },
        onResponseError({ request, response, options }) {
        }
        })
    return { provide: { authFetch: $authFetch }
    }
})


example page that retrieves the data using the authFetch.
<script lang="ts" setup>
    const { data, error } = await useAuthFetch(`user/blog/${blogGuid}`);

Does somebody know how I can fix this? This might be a SRR issue?
Was this page helpful?