0Pricing
Vue Academy · Lesson

Authenticated API Calls with Axios Interceptors

Request interceptor for Authorization header, response interceptor for 401 → refresh → retry.

Authenticated API Calls with Axios Interceptors is a free Vue Academy lesson on CoddyKit — lesson 3 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 Vue Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Interceptor Pattern

Rather than attaching auth headers and handling 401s in every call, Axios interceptors centralize this logic. A request interceptor adds the token; a response interceptor handles expiry and refresh transparently.

Creating the Axios Instance

Create a dedicated instance with the API base URL and withCredentials so the httpOnly refresh cookie is sent to the refresh endpoint.

import axios from 'axios'

const api = axios.create({
  baseURL: '/api',
  withCredentials: true // send cookies
})

export default api

Storing the Access Token in Memory

Keep the access token in a module variable (or Pinia store) rather than localStorage. A small accessor pair lets interceptors read and update it.

let accessToken = null

export function setAccessToken(t) { accessToken = t }
export function getAccessToken() { return accessToken }

Request Interceptor: Adding the Header

The request interceptor runs before every request and attaches Authorization: Bearer <token> when a token exists.

api.interceptors.request.use((config) => {
  const token = getAccessToken()
  if (token) {
    config.headers.Authorization = 'Bearer ' + token
  }
  return config
})

Response Interceptor: Catching 401

The response interceptor passes successful responses through untouched, but on a 401 it triggers the refresh flow.

api.interceptors.response.use(
  (response) => response,
  async (error) => {
    const original = error.config
    if (error.response?.status === 401 && !original._retried) {
      // ... refresh and retry (next scenes)
    }
    return Promise.reject(error)
  }
)

Preventing Infinite Retry Loops

Mark the failed request with a flag like _retried so it is only retried once. If the refresh itself returns 401, the request rejects instead of looping forever.

if (error.response?.status === 401 && !original._retried) {
  original._retried = true
  // attempt refresh exactly once for this request
}

Calling the Refresh Endpoint

On 401, POST to /auth/refresh. The browser sends the httpOnly refresh cookie automatically; the server replies with a new access token.

const { data } = await api.post('/auth/refresh')
setAccessToken(data.accessToken)

Retrying the Original Request

After refreshing, update the header on the original config and replay it. The user never sees the interruption.

original.headers.Authorization = 'Bearer ' + data.accessToken
return api(original) // retry the original request

Handling Concurrent 401s

If many requests fail at once, you do not want N parallel refresh calls. Share a single in-flight refresh promise; queued requests await it, then retry with the new token.

let refreshing = null

function refreshOnce() {
  if (!refreshing) {
    refreshing = api.post('/auth/refresh')
      .finally(() => { refreshing = null })
  }
  return refreshing
}

Giving Up: Forcing Logout

If the refresh fails (expired/invalid refresh token), clear the in-memory token and redirect to login. This is the single place that handles session expiry for the whole app.

try {
  await refreshOnce()
} catch {
  setAccessToken(null)
  router.push('/login')
  return Promise.reject(error)
}

Using the Instance in Components

Components just import the configured api instance and make calls. Auth headers, refresh, and retry are fully transparent to component code.

<script setup>
import api from '@/lib/api'
import { ref, onMounted } from 'vue'

const profile = ref(null)
onMounted(async () => {
  const { data } = await api.get('/me')
  profile.value = data
})
</script>

Quick Check

Test your understanding of Axios interceptors.

Recap

You learned authenticated calls with interceptors:

  • Request interceptor adds Authorization: Bearer from the in-memory token
  • Response interceptor catches 401 and refreshes
  • A _retried flag retries the original request exactly once
  • POST /auth/refresh uses the httpOnly cookie to get a new token
  • Share one refresh promise for concurrent 401s; force logout on failure

Frequently asked questions

Is the “Authenticated API Calls with Axios Interceptors” lesson free?

Yes — the full text of “Authenticated API Calls with Axios Interceptors” is free to read here on the web, and the Vue 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 Vue Academy course, upgrade to CoddyKit PRO.

What will I learn in “Authenticated API Calls with Axios Interceptors”?

Request interceptor for Authorization header, response interceptor for 401 → refresh → retry. You practise Vue 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 Vue Academy?

No prior experience is required. Vue Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Authenticated API Calls with Axios Interceptors” 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 Vue Academy lesson?

Yes. Every Vue 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

  1. Fastify Backend for Vue SPAs
  2. JWT Authentication: Login and Refresh
  3. Authenticated API Calls with Axios Interceptors
  4. Deploying Full-Stack Vue to Production
← Back to Vue Academy