2

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?

1 Answer 1

6

If you want global ofetch then you can create a plugin that injects an instance of an ofetch setup to your liking. Essentially similar to what you're doing.

Ultimately, you'll end up having a plugin that looks like

export default defineNuxtPlugin((nuxtApp) => {
  const instance = ofetch.create({
    baseURL: '/api',
    headers: {
      Accept: 'application/json'
    }
  })

  // You can also just do this instead of returning
  // nuxtApp.provide('ofetch', instance)

  return {
    provide: {
      ofetch: instance
    }
  }
})

And use it like

// Take note that whatever key you provide,
// it'll be prepended with `$` when injecting it
const { $ofetch } = useNuxtApp()

Ofetch docs: https://github.com/unjs/ofetch#%EF%B8%8F-create-fetch-with-default-options

Nuxt plugin docs: https://nuxt.com/docs/guide/directory-structure/plugins#automatically-providing-helpers

Nuxt provide docs: https://nuxt.com/docs/api/composables/use-nuxt-app#provide-name-value

The autocomplete/typescript guide is also included in Nuxt's doc.


There's no global listener to ofetch. You might want to use axios instead where you can add default options to the global "instance".

The best practice I guess is to document it and let people know about it or make an "sdk" or api library that abstracts requests to your backend e.g:

// users.ts
export default {
  getAll() {

  },

  getById(id) {
  },

  create() {
  }
}

In which case, you'd still tell people to use this instead of manually executing a request themselves like:

users.getAll()
users.getById(id)

instead of

axios.get('/users')
axios.get(`/users/${id})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.