Hi,
thanks for a fantastic lib !
I am trying to modify headers with the beforeRequest in hooks, but I can't make it work.
I am having the following code
import ky from 'ky-universal'
const prefixUrl = 'https://jsonplaceholder.typicode.com'
const beforeRequestFns = [
(options) => {
console.log(options.headers)
options.headers.unicorn = 'rainbow'
}
]
const options = {
prefixUrl,
hooks: {
beforeRequest: beforeRequestFns,
},
}
const client = ky.create({ ...options })
client.extend({ headers: { foo: 'bar' } }).get('todos/1')
export default client
From the Network tab in Chrome I don't see my 'unicorn' in the request headers, I see the 'foo' is there alright :)
What I am trying to achieve is that every request towards the defined prefixUrl is supposed to be able add authentication to the headers do to some conditions.
From what I can tell from the readme this should be possible, so I am guessing that I am just doing it wrong ?
Can you help? :) -- thanks
Yes, this is possible to do, it's just not entirely obvious at the moment.
Ky normalizes the headers internally to be a Headers instance, so that we can deal with them in a consistent way.
This is briefly mentioned in beforeRequest documentation:
The hook function receives the normalized options as the first argument.
At the moment, we don't have much documentation related to the normalization process. But in this case, the solution is simply to set the header using the appropriate methods of the Headers class, as assigning a property to the instance won't do anything.
hooks: {
beforeRequest : [
(options) => {
options.headers.set('unicorn', 'rainbow');
}
]
}
Since we already mention overriding headers in the documentation, it would be good to add this as a working example. PRs welcome!
Wauv so close 馃う鈥嶁檪 , thanks for the reply ! I will try it out when I find the time to refactor my current code at some point.
The BeforeRequestHook type is incorrect too (https://github.com/sindresorhus/ky/blob/master/index.d.ts#L5) as it doesn't receive neither Options nor RequestInit but a new type with merged options from both, plus the new headers.
Will open a PR to fix that.
Most helpful comment
Yes, this is possible to do, it's just not entirely obvious at the moment.
Ky normalizes the headers internally to be a Headers instance, so that we can deal with them in a consistent way.
This is briefly mentioned in
beforeRequestdocumentation:At the moment, we don't have much documentation related to the normalization process. But in this case, the solution is simply to set the header using the appropriate methods of the
Headersclass, as assigning a property to the instance won't do anything.Since we already mention overriding headers in the documentation, it would be good to add this as a working example. PRs welcome!