DEV Community

Mark Anderson
Mark Anderson

Posted on

5

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) {
            router.push("/logout");
            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.

Image of Bright Data

Ensure Data Quality Across Sources – Manage and normalize data effortlessly.

Maintain high-quality, consistent data across multiple sources with our efficient data management tools.

Manage Data

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay