Skip to content
Discussion options

You must be logged in to vote
const api = got.extend({
	hooks: {
		beforeRequest: [
			options => {
				if (!options.context.token) {
					options.context.token = getToken();
				}
				options.headers.authorization = `Bearer ${options.context.token}`;
			}
		]
	}
});

// use it
await api('https://example.com/endpoint', {
	context: {token: 'my-token'}
});

context is never frozen, so you can always modify it. you can also update the token in mutable defaults:

const api = got.extend({
	mutableDefaults: true,
	context: {token: 'initial-token'}
});

// later, update the token
api.defaults.options.context.token = 'new-token';

Replies: 2 comments 1 reply

Comment options

You must be logged in to vote
1 reply
@shootingsupplies
Comment options

Comment options

You must be logged in to vote
0 replies
Answer selected by sindresorhus
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants