React › Security in React (XSS & dangerouslySetInnerHTML)

Why should you avoid storing sensitive information, like an authentication token, directly in your React app's regular JavaScript state or a global variable?

Intermediate

Answer

Data kept only in memory disappears the moment the page reloads, but more importantly, any sensitive token accessible to your app's JavaScript can potentially be read by malicious code if your app is ever vulnerable to a cross site scripting attack. Storing sensitive tokens in a properly configured cookie that JavaScript cannot access at all offers stronger protection.
// Less secure, readable by any JavaScript running on the page, including malicious code
localStorage.setItem('authToken', token);

// More secure, the browser sends this cookie automatically, but JavaScript cannot read its value
// (this cookie must be set by the server with the HttpOnly flag)
Real-world example A banking app avoids storing its authentication token in a place JavaScript can read, choosing instead to rely on a secure cookie set by the server, reducing the damage a successful cross site scripting attack could cause.

Common follow-ups: What does the HttpOnly flag on a cookie actually prevent JavaScript from doing?;What other common security practices should a React app follow alongside this one?