nuxt-open-fetch
nuxt-open-fetch copied to clipboard
Add dynamic headers
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
- [X] Read the contribution guide.
- [X] Check existing discussions and issues.
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)
}), {})
}
}
})
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:
and when implementing the code the frontend shows a 500 with the message:
Cannot redefine property: $[InsertOpenFetchClientNameHere]
For the "Cannot redefine property" error, you'll also need to disable the nuxt plugin:
export default defineNuxtConfig({
openFetch: {
disableNuxtPlugin: true,
// ...
},
})
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