Axios interceptors are default configurations that are added automatically to every request or response. They allow you to check response status codes, handle authentication tokens, and standardize error handling across your application.
Interceptors are methods triggered before or after the main request or response. There are two types:
- Request interceptor: Allows you to execute code before a request is sent
- Response interceptor: Allows you to process the response before it reaches the calling code
The code examples below use modern JavaScript patterns and can be adapted for any React project. Our engineering team uses these patterns across production applications to handle auth tokens, error standardization, and API request logging.
Production Use Cases
Axios interceptors are essential for production React applications. Key use cases include:
- Authentication: Automatically attaching bearer tokens to requests
- Token refresh: Handling expired access tokens by refreshing them silently
- Error standardization: Converting API errors to consistent formats
- Request logging: Tracking API calls for debugging
- Request/response transformation: Standardizing data formats
Auth and Token Refresh
The most common production pattern involves automatic token management:
import axios from 'axios'
import LocalStorageService from './services/storage/localstorageservice'
const localStorageService = LocalStorageService.getService()
axios.interceptors.request.use(
config => {
const token = localStorageService.getAccessToken()
if (token) {
config.headers['Authorization'] = 'Bearer ' + token
}
return config
},
error => {
return Promise.reject(error)
}
)
For token refresh on 401 errors:
axios.interceptors.response.use(
response => response,
function (error) {
const originalRequest = error.config
if (
error.response.status === 401 &&
originalRequest.url === 'http://127.0.0.1:3000/v1/auth/token'
) {
router.push('/login')
return Promise.reject(error)
}
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true
const refreshToken = localStorageService.getRefreshToken()
return axios
.post('/auth/token', {
refresh_token: refreshToken
})
.then(res => {
if (res.status === 201) {
localStorageService.setToken(res.data)
axios.defaults.headers.common['Authorization'] =
'Bearer ' + localStorageService.getAccessToken()
return axios(originalRequest)
}
})
}
return Promise.reject(error)
}
)
For teams comparing frontend frameworks, our Next.js comparison guide covers how interceptors work differently in server-side rendered applications.
API Error Strategy
Use interceptors to capture and enhance errors before they reach your components:
const axios = require('axios')
axios.interceptors.response.use(
res => res,
err => {
throw new Error(err.response.data.message)
}
)
This approach ensures all API errors follow a consistent structure across your application.
Common Mistakes
- Not handling retry loops: When token refresh fails, ensure you don’t retry indefinitely
- Modifying original requests: Be careful not to mutate request objects in ways that break downstream code
- Missing error handling in request interceptors: Always return the config or reject the promise
- Not handling network errors: Response interceptors should handle both HTTP errors and network failures
For teams needing frontend engineering support, Lightrains provides React development services and web app development. Our team helps design reliable API layers and frontend architectures.
Conclusion
Axios interceptors allow you to intercept every request, update it with authorization headers or API keys, and forward the request. Once resolved, you can process the response with predefined checks before returning it to complete the request.
This article originally appeared on lightrains.com
Leave a comment
To make a comment, please send an e-mail using the button below. Your e-mail address won't be shared and will be deleted from our records after the comment is published. If you don't want your real name to be credited alongside your comment, please specify the name you would like to use. If you would like your name to link to a specific URL, please share that as well. Thank you.
Comment via email