Axios interceptors let you catch and change requests or responses before they reach your app. This helps you add common tasks like adding tokens or handling errors in one place.
Axios interceptors in Vue
axios.interceptors.request.use(function (config) { // modify config before request is sent return config; }, function (error) { // handle request error return Promise.reject(error); }); axios.interceptors.response.use(function (response) { // modify response data return response; }, function (error) { // handle response error return Promise.reject(error); });
The use method takes two functions: one for success and one for error.
Always return the config or response in the success function to continue the flow.
axios.interceptors.request.use(config => {
config.headers.Authorization = 'Bearer mytoken';
return config;
});axios.interceptors.response.use(response => {
return response.data;
});axios.interceptors.response.use(null, error => { alert('Request failed!'); return Promise.reject(error); });
This Vue component uses Axios interceptors to add an authorization header to every request and to catch errors globally. When you click the button, it fetches data and shows loading, data, or error messages.
<template>
<div>
<button @click="fetchData">Fetch Data</button>
<p v-if="loading">Loading...</p>
<pre v-if="data">{{ data }}</pre>
<p v-if="error" style="color: red">{{ error }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
import axios from 'axios';
const data = ref(null);
const error = ref(null);
const loading = ref(false);
// Add request interceptor to add a fake token
axios.interceptors.request.use(config => {
config.headers.Authorization = 'Bearer fake-token-123';
return config;
});
// Add response interceptor to handle errors
axios.interceptors.response.use(
response => response,
err => {
error.value = 'Failed to fetch data';
loading.value = false;
return Promise.reject(err);
}
);
async function fetchData() {
loading.value = true;
error.value = null;
data.value = null;
try {
const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
data.value = JSON.stringify(response.data, null, 2);
} catch {
// error handled by interceptor
} finally {
loading.value = false;
}
}
</script>Interceptors run for every request or response unless removed.
You can eject interceptors if you want to stop them later.
Be careful to handle errors in interceptors to avoid unhandled promise rejections.
Axios interceptors let you change requests or responses before your app sees them.
Use them to add headers, handle errors, or modify data globally.
They help keep your code clean by centralizing common tasks.