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 new Fetch API client, jump to the legacy clients section.
Below is an example request interceptor
js
import { client } from '@hey-api/client-fetch';
client.interceptors.request.use((request, options) => {
request.headers.set('Authorization', 'Bearer <my_token>');
return request;
});
js
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
js
import { client } from '@hey-api/client-fetch';
client.interceptors.response.use((response, request, options) => {
trackAnalytics(response);
return response;
});
js
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()
.
Legacy Clients
The following section applies to legacy clients generated by @hey-api/openapi-ts
. Below is an example request interceptor
js
OpenAPI.interceptors.request.use((request) => {
doSomethingWithRequest(request);
return request; // <-- must return request
});
js
OpenAPI.interceptors.request.eject((request) => {
doSomethingWithRequest(request);
return request; // <-- must return request
});
and an example response interceptor
js
OpenAPI.interceptors.response.use(async (response) => {
await doSomethingWithResponse(response); // async
return response; // <-- must return response
});
js
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.