JS Guide
HomeQuestionsTopicsCompaniesResources
BookmarksSearch

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeTopicsreactSecurity
PrevNext
react
advanced
12 min read

Security

csp
csrf
dompurify
httponly-cookies
sanitization
security
xss

JSX auto-escapes values to prevent XSS by default, but dangerouslySetInnerHTML, href='javascript:', and localStorage token storage are common vulnerability vectors that require explicit mitigation.

Key Points

1JSX Auto-Escaping

All values in {} are escaped before rendering — prevents the most common XSS attacks by treating user input as text, not HTML.

2XSS Bypass Vectors

dangerouslySetInnerHTML bypasses escaping (sanitize with DOMPurify), href='javascript:' executes code, and compromised npm packages run with full access.

3Token Storage

localStorage is vulnerable to XSS (any script can read it). httpOnly + Secure + SameSite cookies prevent JavaScript access to tokens.

4CSRF Prevention

React doesn't prevent CSRF — use server-generated tokens in custom headers and SameSite cookie attributes.

5Content Security Policy

CSP headers restrict script sources, blocking inline scripts and third-party injection — the strongest browser-level XSS defense.

What You'll Learn

  • Explain React's built-in XSS protection and its limitations
  • Know the security tradeoffs between localStorage and httpOnly cookies for tokens
  • Implement defense strategies for XSS, CSRF, and dependency vulnerabilities

Deep Dive

React provides built-in XSS protection through JSX auto-escaping, but a secure React application requires understanding additional attack vectors and defense strategies.

React's Built-in XSS Protection

JSX escapes all values embedded in curly braces before rendering to the DOM. If a user enters <script>alert('xss')</script> and you render {userInput}, React treats it as text, not HTML. This prevents the most common XSS attack vector — injecting malicious scripts through user input.

XSS Vectors That Bypass Protection

dangerouslySetInnerHTML: This prop deliberately bypasses escaping to render raw HTML. If the HTML comes from user input or untrusted sources, it must be sanitized first. Use DOMPurify: <div dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(userHTML) }} />.

href and src attributes: React does not sanitize URL attributes. <a href={userInput}> can execute JavaScript if the user provides javascript:alert('xss'). Validate URLs: ensure they start with https:// or /, and never use user input directly in href or src without validation.

Third-party dependencies: NPM packages can contain malicious code. A compromised dependency runs with full access to your app. Regularly audit with npm audit, use Snyk or Dependabot, and minimize dependencies.

CSRF (Cross-Site Request Forgery)

React doesn't prevent CSRF — it's a UI library, not a security framework. CSRF attacks trick authenticated users into making unwanted requests. Defense:

  • Server generates a CSRF token and includes it in the page
  • Client sends the token in a custom header (X-CSRF-Token) with every mutation request
  • Server validates the token before processing the request
  • SameSite cookie attribute (SameSite=Strict or Lax) prevents cookies from being sent on cross-site requests

Authentication Token Storage

localStorage is accessible to any JavaScript running on the page — a single XSS vulnerability lets an attacker steal tokens. More secure approach:

  • httpOnly cookies: Set HttpOnly flag so JavaScript cannot access the cookie. Set Secure to require HTTPS. Set SameSite=Strict to prevent CSRF.
  • Short-lived access tokens: Use short expiration with refresh token rotation to limit damage if a token is compromised.

Content Security Policy (CSP)

CSP HTTP headers restrict which scripts can run on the page. Content-Security-Policy: script-src 'self' only allows scripts from your own domain, blocking inline scripts and third-party injection. Requires nonce or hash attributes for legitimate inline scripts. CSP is the strongest browser-level defense against XSS.

Additional Best Practices

  • Validate and sanitize all input server-side (never trust client validation alone)
  • Use TypeScript to catch type errors that could lead to security issues
  • Avoid eval() and new Function() — they execute arbitrary strings as code
  • Keep React and all dependencies updated — security patches are released regularly
  • Implement rate limiting and input length restrictions on forms

Key Interview Distinction

React auto-escapes JSX values (built-in XSS protection) but dangerouslySetInnerHTML, URL attributes, and third-party deps are still vectors. Use httpOnly cookies over localStorage for auth tokens. CSP headers are the strongest client-side defense. React is a UI library — CSRF, authentication, and server-side validation are not its responsibility.

Fun Fact

React intentionally named the prop 'dangerouslySetInnerHTML' to be scary and verbose — the React team wanted developers to think twice before using it. The __html key inside the object is another speed bump: it forces you to write { __html: ... } instead of just passing a string, making accidental unsafe rendering harder.

Continue Learning

Forms

intermediate

Practice What You Learned

What security vulnerabilities should you address in React applications and how do you prevent them?
senior
security
Key vulnerabilities include XSS (mitigated by React's auto-escaping, but watch dangerouslySetInnerHTML and URL injection), CSRF (use tokens in API requests, SameSite cookies), and insecure storage (avoid localStorage for sensitive data, prefer httpOnly cookies).
Previous
Routing
Next
State
PrevNext