Skip to content

auto logout function when there is authentication error #104

Discussion options

You must be logged in to vote

Hello, @creative2113
we can use interceptor axiosHandler for solving this problem.
Here is an example code:

import axios from "axios";

const axiosHandler = axios.create({
  baseURL: process.env.REACT_APP_BASE_URL,
  headers: {
    Accept: "application/json",
  },
});

axiosHandler.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers["Authorization"] = "Bearer " + token;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  }
);

//axiosHandler.interceptors.response

export default axiosHandler;

in error case, we can add code for logout action in the Error handler field of interceptor.
This cod…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@creative2113
Comment options

creative2113 Sep 11, 2024
Collaborator Author

@creative2113
Comment options

creative2113 Sep 11, 2024
Collaborator Author

@creative2115
Comment options

Answer selected by creative2113
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants