omar
omar
NNuxt
Created by omar on 5/5/2024 in #❓・help
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,
},
};
},
});
2 replies