Search code examples
reactjsauthenticationrect

I want a simple authentication with bearer token and rest api which should be stored in local storage and be refresh in given time in REACT


I want a simple authentication with bearer token and rest API which should be stored in local storage and be refreshed in the given time in REACt. as I know react is a library and tends to do simple work that concerns on Effective UI and Ux. What about HTTPS request stuff and also authentication . I guess Axios should be the fine approach for HTTP request but using third-party library is sick n RWACt especially if you are a beginner who doesn't have a much understanding of promises than react makes you have a nightmare. Any Solution will be great.


Solution

  • Use axios for this purpose. you can use it like this :

    axios.post('/login', data)
        .then(response => {
            localStorage.setItem('token', response.data.token);
        });
    

    Also you can use axios interceptors for this purpose. It will run for every request call. for validating and setting headers to requests like this:

    const config = {url:'https://...',timeout:10000}
    
    const instance = axios.create({
      baseURL: config.url,
      timeout: config.timeout
    });
    instance.interceptors.request.use(
      config => {
        const token =  localStorage.getItem('token')
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      error => Promise.reject(error)
    );