The goal is to set a global header for all outgoing queries
Since its now recommended not to use axios anymore in nuxt 3 i wanted to switch to the ofetch of Nuxt3. As i read, the nuxt3 team implementing this did not consider to implement an option to globally set information like headers for all requests, as we could in axios. Thats unfortunate, because its very common to have api data that all requests consume.
My current workaround is to create a composable to get the request there and modify it. Since its possible to expose the api data stored in the process.env in the runtime config section of the nuxt.config like so:
export default defineNuxtConfig({
runtimeConfig: { public: { apiKey: process.env.API_KEY, } },
})
we can access it in the composable i named useFoo.ts using useRuntimeConfig() and modify the header as needed
const opts = {
async onRequest({ request, options }:any) {
const runtimeConfig = useRuntimeConfig()
options.headers = { 'apiToken': runtimeConfig.apiKey};
},
};
export const useFoo = () => $fetch.create(opts);
now, in a random component, i just import the composable and replace the §fetch method with my custom method
const foo = useFoo();
foo("apiroute", {
retry: 0,
})
.then((response: any) => {
console.log(response.data);
})
.catch((error: any) => {
console.log(error);
});
This does work, but its still per-call and not global, which is suboptimal, because as some already pointed out, wed have to explain the custom functions to every dev working on it.
Isnt there for example a way to create a global ofetch "listener", for any fetch call made in the entire app at any time, that we can attach the onRequest to? Or Maybe there is another best practise for this using middleware or sth?