Interceptors
Interceptors (middleware) can be used to modify requests before they're sent or responses before they're returned to the rest of your application. If you're not using the standalone client packages, jump to the legacy clients section.
Fetch API
Fetch API does not have the interceptor functionality, so we implement our own. Below is an example request interceptor
import { client } from '@hey-api/client-fetch';
client.interceptors.request.use((request, options) => {
request.headers.set('Authorization', 'Bearer <my_token>');
return request;
});
import { client } from '@hey-api/client-fetch';
client.interceptors.request.eject((request, options) => {
request.headers.set('Authorization', 'Bearer <my_token>');
return request;
});
and an example response interceptor
import { client } from '@hey-api/client-fetch';
client.interceptors.response.use((response, request, options) => {
trackAnalytics(response);
return response;
});
import { client } from '@hey-api/client-fetch';
client.interceptors.response.eject((response, request, options) => {
trackAnalytics(response);
return response;
});
TIP
To eject, you must provide a reference to the function that was passed to use()
.
Axios
If you're using the new Axios client, refer to the Axios documentation on interceptors. We expose the Axios instance through the instance
field.
import { client } from '@hey-api/client-axios';
client.instance.interceptors.request.use((config) => {
trackAnalytics(config);
return config;
});
Legacy Clients
The following section applies to legacy clients generated by @hey-api/openapi-ts
. Below is an example request interceptor
OpenAPI.interceptors.request.use((request) => {
doSomethingWithRequest(request);
return request; // <-- must return request
});
OpenAPI.interceptors.request.eject((request) => {
doSomethingWithRequest(request);
return request; // <-- must return request
});
and an example response interceptor
OpenAPI.interceptors.response.use(async (response) => {
await doSomethingWithResponse(response); // async
return response; // <-- must return response
});
OpenAPI.interceptors.response.eject(async (response) => {
await doSomethingWithResponse(response); // async
return response; // <-- must return response
});
TIP
To eject, you must provide the same function that was passed to use()
.
WARNING
Angular client does not currently support request interceptors.
Examples
You can view live examples on StackBlitz.