2

I know this question has been asked many times but there is no clear answer so far and the suggested options (cookies, local storage etc..) have all pros and cons. I'm new to React SPA and I'm very confused about the right method to adopt.

For now I've based my application on the "cookie-to-header token" premise. The API I work with returns a token meant to be used with the Authorization header for the POST PUT and DELETE requests.

So on the login page a cookie is created in order to store the token value:

const login = { email, password };
const [error, setError] = useState(null);

fetch('https://apidomain.net/api/login', {
  method: 'POST',
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(login)
}).then((res) => {
    if (!res.ok) {
        throw Error('Could not fetch the data for this resource. Status: '+res.status+' Message: '+res.statusText);
    }

    return res.json();
})
.then((data) => {
    document.cookie = "auth_token="+data.auth_token;
}).catch((err) => {
    setError(err.message);
});

Then, the token value is retrieved by Javascript whenever a POST PUT or DELETE request is sent:

fetch('https://apidomain.net/api/post/4', {
    method: 'DELETE',
    headers: { 'Authorization': 'Bearer '+getAuthToken()}
 })

It works fine but is it safe ?
Is there a better way to do that ?

Duddy67
  • 836
  • 2
  • 10
  • 26
  • Does this answer your question? [Where to store access-token in react.js?](https://stackoverflow.com/questions/48983708/where-to-store-access-token-in-react-js) – Damian Busz Mar 23 '22 at 07:29
  • @DamianBusz Partialy. The 2 cookies trick is interesting but it required jwt. I'm also thinking about storing the token in a frontend database like SQLite or IndexedDB but I'm not sure it's efficient regarding security and performance. – Duddy67 Mar 23 '22 at 07:58

0 Answers0