Published: September 26 2021

Vue 2/3 + Axios - Interceptor to Set Auth Header for API Requests if User Logged In

This is a quick example of how to automatically set the HTTP Authorization header for requests sent with axios from a Vue.js (v2 or v3) app to an API when the user is authenticated.

The code snippet in this tutorial is used a couple of Vue Facebook Login tutorials I posted a little while ago, one built with Vue.js v2 and the other with Vue 3, to see the code running in a live demo app check out the following posts:

RxJS is used in the Vue tutorials to store the current authenticated user state in the accountService, but RxJS isn't required if your Vue.js app uses another way to store the user's logged in state such as Vuex or something else. The only requirement is that you can check if the user is logged in from the axios interceptor function below (jwtInterceptor()).

 

Axios JWT Interceptor

Path: /src/_helpers/jwt.interceptor.js

The JWT Interceptor intercepts http requests from the application to add a JWT auth token to the HTTP Authorization header if the user is logged in and the request is to the Vue app's API url (process.env.VUE_APP_API_URL).

It's implemented as an axios request interceptor, by passing a callback function to axios.interceptors.request.use() you can intercept and modify requests before they get sent to the server. For more info on axios interceptors see https://github.com/axios/axios#interceptors.

The jwtInterceptor() function is executed just before app startup to enable the axios interceptor.

import axios from 'axios';

import { accountService } from '@/_services';

export function jwtInterceptor() {
    axios.interceptors.request.use(request => {
        // add auth header with jwt if account is logged in and request is to the api url
        const account = accountService.accountValue;
        const isLoggedIn = account?.token;
        const isApiUrl = request.url.startsWith(process.env.VUE_APP_API_URL);

        if (isLoggedIn && isApiUrl) {
            request.headers.common.Authorization = `Bearer ${account.token}`;
        }

        return request;
    });
}
 


Subscribe or Follow Me For Updates

Subscribe to my YouTube channel or follow me on Twitter, Facebook or GitHub to be notified when I post new content.

Other than coding...

I'm currently attempting to travel around Australia by motorcycle with my wife Tina on a pair of Royal Enfield Himalayans. You can follow our adventures on YouTube, Instagram and Facebook.


Need Some Vue Help?

Search fiverr to find help quickly from experienced Vue developers.



Supported by