How to get a Authorization Bearer Token from Response Headers with Axios?

The backend is sending me a Bearer token inside the response headers and I want to store it inside the redux store as most of the APIs require that token to be sent back inside the headers.

I’m encountering an issue when I’m attempting to save the token from the response because it comes as undefined.

This is the code that I’ve got so far

  const onLogin = async () => {
    try {
      const response = await axiosInstance.post('/api/auth/login', userData);
      push("https://stackoverflow.com/");
      const token = response.headers['Authorization'];

      console.log('token', token);

      dispatch(userToken(token));
    } catch (error: any) {
      console.log('Login Error', error.message);
    }
  };

The login works. I get status code 200 and can also see the token inside the network tab in the console. But if I try to console.log it, it shows as undefined, so I imagine it’s also not stored in the redux store.

How can I get that token and save it to the redux store?

you can use like:

const { Bearer } = response

if response has Bearer = …….

you can get Bearer

Leave a Comment