Nuxt 3: How to add default parameters and headers to $fetch

Viewed 310

Trying to add any default parameters or headers (in this case a json web token as authentication header) to the $fetch composable so that i dont have to do

await $fetch('/api/example', {
  headers: {
    // authentication header and jwt here
  }
});

on every single request. i found a way to do this by wrapping $fetch in another composable (in this case as $api) but this removed any typings on the api response, so this is not something i want to do.

Even a simplified api.ts composable like this

export const $api = (url: string) => {
  return $fetch(url);
}

does not give me the response typings from the api result that a blank $fetch in my frontend would give me.

Can i inject default values in $fetch somehow? maybe through a module/plugin/interceptor? if not, is there a way to wrap $fetch in a composable and still keep the response typings?

i'm using nuxt3 with $fetch being ohmyfetch and i'm not using the @nuxt/auth package btw

0 Answers
Related