N
Nuxt5mo ago
Guillaume

Shared API client wrapper cookie token

Hello, I've a plugins/api.client.ts file that defines a Nuxt plugin to provide my httpClient (it is a library that wraps all my REST APIs). However, I need to initialize it with the token stored in the browser cookie. The problem is that when I change the page, the token becomes undefined.
export default defineNuxtPlugin(nuxtApp => {
const { setAccount } = useAuthStore();
const userToken = useCookie('token');

if (!userToken) return;

const httpClient = MyAPIWrapper.create({
token: userToken.value!,
version: AvailableVersions.V1,
tenant: Tenants.Default
});

nuxtApp.hook('app:beforeMount', () => {
httpClient.account
.me()
.then(res => setAccount(res.user))
.catch(() => setAccount(null));
});

nuxtApp.provide('httpClient', httpClient);
});

declare module '#app' {
interface NuxtApp {
$httpClient: MyAPIWrapperTypes;
}
}
export default defineNuxtPlugin(nuxtApp => {
const { setAccount } = useAuthStore();
const userToken = useCookie('token');

if (!userToken) return;

const httpClient = MyAPIWrapper.create({
token: userToken.value!,
version: AvailableVersions.V1,
tenant: Tenants.Default
});

nuxtApp.hook('app:beforeMount', () => {
httpClient.account
.me()
.then(res => setAccount(res.user))
.catch(() => setAccount(null));
});

nuxtApp.provide('httpClient', httpClient);
});

declare module '#app' {
interface NuxtApp {
$httpClient: MyAPIWrapperTypes;
}
}
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server