Search code examples
reactjscookiesjwtlocal-storagetoken

What's a secure way to store token & auth state?


Here's my scenario:

When a user logs in, an API call is made and if his credentials are valid, a token is returned. I need to store the authentication state (to keep the user logged in) and the token somewhere. The token will be used to make other API calls.

I've read these posts: 1, 2, 3 (and some others) which all seem to contradict each other; whether it's localStorage, cookies or JWT, all are being deemed as unsafe by different people. I have also read about react-redux too but I'm not sure about it.

For now I am completely lost on which solution best suits my needs since I am new to reactJs. So, what is the proper way to go on about this?


Solution

  • The most common practice is storing your token in cookie and set HttpOnly to true, so that any javascript code cannot read your token programmatically.

    I suppose you are using axios as ajax client, you can make a request like this

    axios.get('https://example.com/api', {
      withCredentials: true
    })
    

    by doing this, axios will send your cookies to remote server automatically