1

I have a backend where the user gets a JSON Web Token if he is logged in successfully. This token is needed for other API calls and I want to store it application-wide to access it from every point in the application. What is the best point to store it and access it from anywhwere?

LarsDev
  • 37
  • 6

3 Answers3

0

You can store it on local storage on login like

export async function login(username, password) {
  const { data: jwt } = await http.post(apiEndpoint, { username, password });
  localStorage.setItem("token", jwt.token);
}

and than you can access it every time like

export function getCurrentUser() {
try {
    const jwt = localStorage.getItem("token");
    return jwtDecode(jwt);
  } catch (error) {
    return null;
  }
}

I have used widely this approach and works like charm.

Adnand
  • 562
  • 1
  • 8
  • 25
0

I'd highly suggest not to store in localStorage. I'd highly recommend cookies.

See this link. In addition, also See another link.

Rashed Rahat
  • 2,357
  • 2
  • 18
  • 38
-1

Storing JWT token in localstorage or session storage of a browser is not preferable, as it can be accessed easily by anyone who has even a little knowledge of browser developer options (especially developers like us).

I suggest you use http only cookie to store them, that way it can be accessed whenever you send a HTTP request.

You can read about it more - https://blog.logrocket.com/jwt-authentication-best-practices/

Viraj Jadhav
  • 84
  • 1
  • 2
  • 6