Called with the plain request options, right before their normalization.
The second argument represents the current Options instance.
[]
Note:
- This hook must be synchronous.
Note:
- This is called every time options are merged.
Note:
- The
optionsobject may not have theurlproperty. To modify it, use abeforeRequesthook instead.
Note:
- This hook is called when a new instance of
Optionsis created.- Do not confuse this with the creation of
Requestorgot(…).
Note:
- When using
got(url)orgot(url, undefined, defaults)this hook will not be called.
This is especially useful in conjunction with got.extend() when the input needs custom handling.
For example, this can be used to fix typos to migrate from older versions faster.
import got from 'got';
const instance = got.extend({
hooks: {
init: [
plain => {
if ('followRedirects' in plain) {
plain.followRedirect = plain.followRedirects;
delete plain.followRedirects;
}
}
]
}
});
// Normally, the following would throw:
const response = await instance(
'https://example.com',
{
followRedirects: true
}
);
// There is no option named `followRedirects`, but we correct it in an `init` hook.
Or you can create your own option and store it in a context:
import got from 'got';
const instance = got.extend({
hooks: {
init: [
(plain, options) => {
if ('secret' in plain) {
options.context.secret = plain.secret;
delete plain.secret;
}
}
],
beforeRequest: [
options => {
options.headers.secret = options.context.secret;
}
]
}
});
const {headers} = await instance(
'https://httpbin.org/anything',
{
secret: 'passphrase'
}
).json();
console.log(headers.Secret);
//=> 'passphrase'
Called right before making the request with options.createNativeRequestOptions().
This hook is especially useful in conjunction with got.extend() when you want to sign your request.
[]
Note:
- Got will make no further changes to the request before it is sent.
Note:
- Changing
options.jsonoroptions.formhas no effect on the request. You should changeoptions.bodyinstead. If needed, update theoptions.headersaccordingly.
import got from 'got';
const response = await got.post(
'https://httpbin.org/anything',
{
json: {payload: 'old'},
hooks: {
beforeRequest: [
options => {
options.body = JSON.stringify({payload: 'new'});
options.headers['content-length'] = options.body.length.toString();
}
]
}
}
);
Tip:
- You can indirectly override the
requestfunction by early returning aClientRequest-like instance or aIncomingMessage-like instance. This is very useful when creating a custom cache mechanism.- Read more about this tip.
The equivalent of beforeRequest but when redirecting.
Called with a RequestError instance. The error is passed to the hook right before it's thrown.
This is especially useful when you want to have more detailed errors.
[]
import got from 'got';
await got('https://api.github.com/repos/sindresorhus/got/commits', {
responseType: 'json',
hooks: {
beforeError: [
error => {
const {response} = error;
if (response && response.body) {
error.name = 'GitHubError';
error.message = `${response.body.message} (${response.statusCode})`;
}
return error;
}
]
}
});
The equivalent of beforeError but when retrying. Additionally, there is a second argument retryCount, the current retry number.
Each function should return the response. This is especially useful when you want to refresh an access token.
[]
Note:
- When using the Stream API, this hook is ignored.
Note:
- Calling the
retryWithMergedOptionsfunction will triggerbeforeRetryhooks. If the retry is successful, all remainingafterResponsehooks will be called. In case of an error,beforeRetryhooks will be called instead. Meanwhile theinit,beforeRequest,beforeRedirectas well as already executedafterResponsehooks will be skipped.
import got from 'got';
const instance = got.extend({
hooks: {
afterResponse: [
(response, retryWithMergedOptions) => {
// Unauthorized
if (response.statusCode === 401) {
// Refresh the access token
const updatedOptions = {
headers: {
token: getNewToken()
}
};
// Update the defaults
instance.defaults.options.merge(updatedOptions);
// Make a new retry
return retryWithMergedOptions(updatedOptions);
}
// No changes otherwise
return response;
}
],
beforeRetry: [
error => {
// This will be called on `retryWithMergedOptions(...)`
}
]
},
mutableDefaults: true
});
All available hooks of Got.