nuxt-open-fetch icon indicating copy to clipboard operation
nuxt-open-fetch copied to clipboard

Add dynamic headers

Open schillerenrico opened this issue 1 year ago • 4 comments

Describe the feature

Is there a way to add and remove headers for all request? Instead of adding the auth header each time I do a request I want the default request have my dynamically generated header added or removed while runtime

Additional information

  • [X] Would you be willing to help implement this feature?

Final checks

schillerenrico avatar Jul 11 '24 10:07 schillerenrico

You should be able to do that via a Custom Client

Based on the example from the docs that adds the logging:

export default defineNuxtPlugin({
  enforce: 'pre', // clients will be ready to use by other plugins, Pinia stores etc.
  setup() {
    const clients = useRuntimeConfig().public.openFetch
    const localFetch = useRequestFetch()

    return {
      provide: Object.entries(clients).reduce((acc, [name, options]) => ({
        ...acc,
        [name]: createOpenFetch(localOptions => ({
          ...options,
          ...localOptions,
          onRequest(ctx) {
            ctx.options.headers = {
              ...ctx.options.headers || {},
              // Add the Authorization header to all requests
              Authorization: `Bearer ${session.token}`, // Wherever your token comes from
            }
            return localOptions?.onRequest?.(ctx)
          }
        }), localFetch)
      }), {})
    }
  }
})

adamdehaven avatar Jul 12 '24 00:07 adamdehaven

Thanks for the fast reply! You are definitly right and it should be the right approch. I replaced the Bearer input as your comment said too.

I just have some issues by using this code.

First of all there is 1 typescript error: image

and when implementing the code the frontend shows a 500 with the message: Cannot redefine property: $[InsertOpenFetchClientNameHere] image

schillerenrico avatar Jul 12 '24 08:07 schillerenrico

For the "Cannot redefine property" error, you'll also need to disable the nuxt plugin:

export default defineNuxtConfig({
  openFetch: {
    disableNuxtPlugin: true,
    // ...
  },
})

adamdehaven avatar Jul 12 '24 13:07 adamdehaven

the main problem is solved, thanks a lot @adamdehaven only the typescript error remains dont know if we should keep this issue open for it

schillerenrico avatar Jul 12 '24 17:07 schillerenrico