Axios Config with Auth Header, best practise?

Viewed 495

I am setting up JWT authentication, everything is working fine but I got stuck at the last piece where I am not sure what I should do.

I have set up my Axios Config as this:

const token = ""

export const axios = Axios.create({
    baseURL: "http://localhost:8080",
    headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${token}`
      },
});

so here are few problems I have ..

  1. if I want to log in, I need to have the "Auth" field to be gone, since I am not sending any cookie, if I do so, my backend fires an Exception since the cookie is not complete
  2. How should I go about the Axios config, should I fill the "token" variable OR should I work here with the cookie in the local storage?
  3. Is it a good practice to have multiple configs and use them simultaneously depending on the situation?

hope anyone can help me out! :)

1 Answers

For anyone coming accross this question, to handle such situations i use axios.interceptors which let you access a certain event inbetween the request and response, that way you can handle the Auth Token and also in case of the "need" to refresh the token, it also should be handled here.

Multiple Axios Configs are also a way to go, but not necessary for that case, pointing out here.

Related