bearer option
I use ky almost every day at work. And I'm constantly annoyed by having to manually write headers for bearer tokens.
So I made this option, as I think it will be convenient to use.
I'm a bad developer, so sorry if the implementation is not as good as the other code in this library.
The main goal is to have a convenient thing.
In my opinion, this is very well covered by ky's beforeRequest hook as covered in the docs: https://github.com/sindresorhus/ky?tab=readme-ov-file#hooksbeforerequest
By creating a wrapper around ky and using that for network requests, you don't have to manually write the authorization header constantly; you do it once.
In other words: this already exists in a more powerful and flexible feature in the form of beforeRequest hooks.
@kleinfreund Of course. beforeHooks is powerful thing, no doubt.
But realization with simple .bearer(...) requires less code, that is main reason.
ky.create({
bearer: "...",
});
vs
ky.create({
hooks: {
beforeRequest: [
request => {
request.headers.set('Authorization', `Bearer ${"..."}`);
}
]
}
});
The whole point of ky is to make things easier to understand, easier to write and avoid all the clutter. I vote for supporting the bearer property, as this is the defacto way to share security tokens.
Are you complaining for writing 3 extra LOC? Sorry, mate, but the goal of "Ky" is to be lightweight. I've been using Ky in more than 10 projects, and I never got any issue with the extra headers for the token. This looks like a skill issue.
I can see how this would be convenient. However, it is a very specific solution to a very specific problem. If we were to implement shortcuts for tokens, I would want it to be more generic and/or powerful. For example, this option could be handled by a re-usable hook rather than the core library. It could handle other aspects of authentication and authorization, too. Such as handling 401 and 403 responses by refreshing the token or redirecting to a home page or login page. We could ship it as a optional import, making it easy to register if you need it, while also not having any overhead if you don't need it.
I'm going to close this for now due to inactivity. If anyone wants to try implementing this as a hook, I'd be happy to take a look. It would be used like...
import ky, { auth } from 'ky';
const api = ky.extend({
hooks : [
auth({ bearer : 'xyz' })
]
});
await api.post('/foo');
There could then be additional options for a refresh URL, etc. Either implemented right away or in a separate PR in the future.