Skip to main content

Interceptors

Interceptors allow you to run custom logic before a request is sent or after a response is received. This is useful for logging, modifying requests, handling errors, and more.

Nitro Fetch supports both request and response interceptors.

What Are Interceptors?​

Interceptors are functions that you can use to intercept and modify HTTP requests and responses. They provide a way to add global behavior to your HTTP client, such as adding authentication tokens, logging, or handling errors.

Benefits of Using Interceptors​

  • Global Behavior: Apply the same logic to all requests or responses.
  • Separation of Concerns: Keep your request/response logic separate from your business logic.
  • Flexibility: Easily add or remove interceptors as needed.

Adding a Request Interceptor​

Request interceptors can modify the request config before the request is sent.

Basic Example​

const id = api.interceptors.request.use(config => {
// Add a custom header
config.headers = config.headers || {};
config.headers['X-Custom-Header'] = 'foobar';
return config;
});

Using Values from Redux Store​

If you're using Redux, you can access the store in your interceptor:

import store from './store';

api.interceptors.request.use(config => {
const token = store.getState().auth.token;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});

Using Local Storage​

You can also use values from local storage:

api.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});

Using Cookies​

Similarly, you can use cookies:

api.interceptors.request.use(config => {
const token = document.cookie.split('; ').find(row => row.startsWith('token='))?.split('=')[1];
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});

Adding a Response Interceptor​

Response interceptors can modify the response or handle errors.

Basic Example​

api.interceptors.response.use(
response => {
// Log all responses
console.log('Response:', response);
return response;
},
error => {
// Handle errors globally
console.error('Global error handler:', error);
return Promise.reject(error);
}
);

Handling 401/403 Responses​

You can use response interceptors to handle specific HTTP status codes, such as 401 (Unauthorized) or 403 (Forbidden):

api.interceptors.response.use(
response => response,
error => {
if (error.response) {
if (error.response.status === 401 || error.response.status === 403) {
// Logout the user or redirect to login page
localStorage.removeItem('token');
window.location.href = '/login';
}
}
return Promise.reject(error);
}
);

Ejecting an Interceptor​

Remove an interceptor by its ID (returned from use).

api.interceptors.request.eject(id);

Clearing All Interceptors​

Remove all interceptors of a type:

api.interceptors.request.clear();
api.interceptors.response.clear();

tip
  • Add authentication tokens
  • Log requests and responses
  • Handle errors globally
  • Modify request/response data