N
Nuxt8mo ago
omar

Auto importing custom $fetch plugin globally

Hey Nuxters, I've been following the guide by @manniL / TheAlexLichter on how to create a custom $fetch function by creating a plugin that provides my custom instance and I just need to expose it globally, any idea how to do it so it's just similar to $fetch?
export default defineNuxtPlugin({
setup() {
const { baseURL } = useRuntimeConfig().public;
const store = useAuthenticationStore();

const api = $fetch.create({
baseURL,
headers: {
Locale: "en",
},
onRequest({ options }) {
if (store.isAuthticated) {
options.headers = options.headers || {};
(
options.headers as Record<string, string>
).Authorization = `Bearer ${store.session.token}`;
}
},
});

return {
provide: {
api,
},
};
},
});
export default defineNuxtPlugin({
setup() {
const { baseURL } = useRuntimeConfig().public;
const store = useAuthenticationStore();

const api = $fetch.create({
baseURL,
headers: {
Locale: "en",
},
onRequest({ options }) {
if (store.isAuthticated) {
options.headers = options.headers || {};
(
options.headers as Record<string, string>
).Authorization = `Bearer ${store.session.token}`;
}
},
});

return {
provide: {
api,
},
};
},
});
1 Reply
manniL
manniL8mo ago
just answered @ https://github.com/nuxt/nuxt/discussions/27063 Right now you need the extra line
GitHub
Auto importing custom $fetch plugin globally · nuxt nuxt · Discussi...
Hey Nuxters, I've been following the guide by @manniL on how to create a custom $fetch function by creating a plugin that provides my custom instance and I just need to expose it globally, any ...
Want results from more Discord servers?
Add your server