The browser and React · Question 14 of 50

Cookies, localStorage or sessionStorage: where do you keep an auth token?

What they're checking

The security trade-off between XSS and CSRF.

The answer

Cookies are sent automatically with every request to their site, and can be HttpOnly (JavaScript cannot read them), Secure (HTTPS only) and SameSite (limits sending them from other sites). localStorage holds about 5 MB per origin until it is cleared, readable by any script on the page; sessionStorage is the same, per tab, cleared when the tab closes.

For a session or refresh token, an HttpOnly, Secure, SameSite=Lax cookie is the usual choice: an XSS bug cannot read it, and SameSite plus a CSRF token deals with cross-site requests. A token in localStorage can be read by any script that gets injected into the page.

The picture

                 sent with requests   JS can read      lasts
cookie           yes, automatically   not if HttpOnly  until it expires
localStorage     no                   yes              until cleared
sessionStorage   no                   yes              until the tab closes
The follow-up they'll ask

What is CSRF?

Show the answer

Another site makes the user's browser send a request to your site with the user's cookies attached. SameSite cookies and CSRF tokens stop it.

Your progress stays on this device.