N
Nuxt8mo ago
plechelmus

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,
},
};
},
});
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?
1 Reply
plechelmus
plechelmus8mo ago
I think I solved it with:
onRequest({ options }) {
const { token } = useAuth();
if (token && token.value) {
options.headers = { Authorization: `${token.value}` };
}
},
onRequest({ options }) {
const { token } = useAuth();
if (token && token.value) {
options.headers = { Authorization: `${token.value}` };
}
},
Where useAuth() is the sidebase/nuxt-auth package
Want results from more Discord servers?
Add your server