How do you handle authentication tokens in a React app securely?

React data fetching and state libraries · Experienced

Model answer

Prefer HttpOnly, Secure, SameSite cookies set by the server, since JavaScript cannot read them, which reduces token theft through XSS. Storing tokens in localStorage is simple but exposed to XSS. Protect against XSS (escape output, use a content security policy), add CSRF protection when using cookies, and keep short-lived access tokens with refresh.

The server must enforce authorisation. The client only controls what is shown.

Learn this topic

TanStack Query (React Query): Fetching, Caching and Updating Server Data in the course React.js Full Course: Beginner to Advanced.

Sign in to add your own answer.

More questions