Axios: Interceptors and Base URL
Create an Axios instance with a baseURL, attach auth tokens in request interceptors, and handle 4xx/5xx errors in response interceptors.
Axios: Interceptors and Base URL is a free Frontend Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Frontend Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Use Axios?
Axios is a popular HTTP client built on XMLHttpRequest. It adds: automatic JSON, request/response interceptors, baseURL config, timeout, and request cancellation tokens. Many teams still prefer it over fetch.
Installing Axios
Install via npm. Browser bundle is around 14KB gzipped.
npm install axiosBasic GET and POST
Axios auto-stringifies JSON bodies and auto-parses JSON responses — no manual JSON.stringify or .json() calls.
import axios from 'axios';
const { data } = await axios.get('/api/users');
console.log(data); // already parsed
const res = await axios.post('/api/users', { name: 'Alice' });
console.log(res.data, res.status);Creating an Axios Instance
Create a configured instance for your API to avoid repeating the base URL, headers, and timeout on every call.
import axios from 'axios';
export const api = axios.create({
baseURL: import.meta.env.VITE_API_URL,
timeout: 10000,
headers: { 'Content-Type': 'application/json' }
});
// Use it:
const { data } = await api.get('/users');
const res = await api.post('/users', { name: 'Alice' });Request Interceptor: Auth Token
Inject the auth token on every request without repeating yourself.
api.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});Response Interceptor: Global Errors
Centralise error handling for all responses: redirect on 401, show toast on 5xx, etc.
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
window.location.href = '/login';
}
if (error.response?.status >= 500) {
toast.error('Server error. Please try again.');
}
return Promise.reject(error);
}
);Token Refresh on 401
Use a response interceptor to detect 401, refresh the token, and retry the original request transparently.
api.interceptors.response.use(null, async (error) => {
const originalRequest = error.config;
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
const newToken = await refreshToken();
localStorage.setItem('token', newToken);
originalRequest.headers.Authorization = `Bearer ${newToken}`;
return api(originalRequest); // retry
}
return Promise.reject(error);
});URL Parameters and Query
Axios accepts a params object — it serialises to a query string automatically.
const { data } = await api.get('/search', {
params: { q: 'react hooks', page: 2 }
});
// GET /search?q=react+hooks&page=2Timeouts
Set a request timeout to avoid hanging on a slow server.
api.get('/slow-endpoint', { timeout: 5000 })
.catch(err => {
if (err.code === 'ECONNABORTED') {
console.log('Request took too long');
}
});Cancelling Requests
Use AbortController (modern Axios) or a CancelToken (older API).
const controller = new AbortController();
api.get('/big-data', { signal: controller.signal })
.catch(err => {
if (axios.isCancel(err)) console.log('cancelled');
});
controller.abort();Error Object Shape
Axios errors have error.response (server replied with an error status), error.request (no response received), or neither (request setup failed).
Axios vs Fetch — When to Choose
Axios: cleaner API, interceptors built in, smaller error handling. Fetch: native, smaller bundle, modern streaming support. New projects often pick fetch + a thin wrapper; existing Axios projects rarely migrate.
Quick Check
What feature of Axios lets you add an Authorization header to every request without modifying each individual call?
Recap: Axios
axios.create() for configured instances with baseURL and timeout. Auto-parsed JSON responses (res.data). Request interceptors attach tokens; response interceptors handle errors and refresh tokens. params object for query strings. AbortController for cancellation. Choose Axios for cleanliness; fetch + wrapper for smaller bundle.
Frequently asked questions
Is the “Axios: Interceptors and Base URL” lesson free?
Yes — the full text of “Axios: Interceptors and Base URL” is free to read here on the web, and the Frontend Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Frontend Academy course, upgrade to CoddyKit PRO.
What will I learn in “Axios: Interceptors and Base URL”?
Create an Axios instance with a baseURL, attach auth tokens in request interceptors, and handle 4xx/5xx errors in response interceptors. You practise Frontend Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Frontend Academy?
No prior experience is required. Frontend Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Axios: Interceptors and Base URL” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Frontend Academy lesson?
Yes. Every Frontend Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Fetch API: GET POST PUT DELETE
- Axios: Interceptors and Base URL
- Error Handling: HTTP Status Codes
- SWR and React Query for Data Caching