DEV Community

Mark Anderson
Mark Anderson

Posted on

Auto Redirect Vue 401

This is a quick note so I don't lose this. If you need to redirect based on a status code and are using vuex this might be helpful. I have a getter I call api that returns an Axios instance so I can add the JWT to the headers. I needed to handle 401's for bookmarks etc. You will need to import axios and router at the top of your store so you can re-direct. I redirect to log out which takes care of wiping out the old token on the way to the login page. You will want to remove the Authorization header and either set SET_ME values or remove the lines they appear in as well. I think it may help to have them in the code since it's a sample of what can be done. I set the SET_ME values using dot env file variables and process.env if that helps anyone.

api: function (state) {
    const axiosInstance = axios.create({
        baseURL: 'SET_ME',
        timeout: 5000,
        withCredentials: false,
        headers: {
            "Content-Type": "application/json;charset=UTF-8",
            "Accept": "application/json",
            "Access-Control-Allow-Origin": 'SET_ME',
            "Authorization": state.jwt
    axiosInstance.interceptors.response.use(function (response) {
        return response;
    }, function (error) {
        if (401 === error.response.status) {
            return Promise.resolve(error.response);
        } else {
            return Promise.reject(error);
    return axiosInstance;

You can access the api with. this.$store.getters.api but I have it included as api using a mixin the bring common things to each page. Hope this helps.

Top comments (0)