Skip to content
Tutorials Center
My learning

Topics

Lesson 92 of 132 ยท Testing and Quality

React Security: XSS, Tokens and Dependencies

Learn the security risks in React apps - cross-site scripting, dangerouslySetInnerHTML and sanitizing, unsafe URLs, token storage, CSRF, secrets in bundles and supply-chain attacks.

React is safer by default than many ways of building web pages, but it is not a security guarantee. Most real-world problems in React apps fall into a few families: untrusted text becoming executable markup (XSS), credentials stored where scripts can steal them, secrets shipped to every visitor, and malicious code arriving through an npm package. This lesson teaches each one, how it happens, and the habits that prevent it.

One rule sits under everything else. Code that runs in the browser belongs to the visitor. They can read your bundle, change any variable and call your API with any data. The browser side of an app can improve the user experience, but only the server can enforce rules. This is the same lesson as in authentication patterns, applied more widely.

The demos here use harmless sample strings and never run attacker code. Do not test attacks on sites you do not own.

Cross-site scripting (XSS)

In an XSS attack, an attacker gets their JavaScript to run inside your page, for example through a comment, a profile name or a URL parameter. That script runs with the visitor's privileges: it can read the page, send requests as the user and read anything JavaScript can reach, including tokens in localStorage.

React blocks the most common route automatically. When you render a value in JSX, React treats it as text, escaping it for you:

JSX
const comment = '<img src="x" onerror="stealCookies()">';

function Comment() {
  return <p>{comment}</p>; // shows the characters, runs nothing
}

The browser displays the literal text <img src="x" onerror="stealCookies()">. This is the biggest security feature React gives you, and you keep it by doing one thing: render user data as JSX children, not as HTML.

flowchart TD
  A["Untrusted data<br/>(comment, name, URL, API field)"] --> B{"How is it rendered?"}
  B -->|"JSX child {value}"| C["Escaped as text<br/>safe"]
  B -->|"href / src attribute"| D{"Protocol checked?"}
  D -->|yes| C
  D -->|no| E["javascript: URL<br/>risk"]
  B -->|"dangerouslySetInnerHTML"| F{"Sanitized with an<br/>allowlist?"}
  F -->|yes| C
  F -->|no| G["XSS risk"]

Safe by default: risk appears only when you opt out of escaping or put unchecked values in URL attributes.

dangerouslySetInnerHTML

Sometimes you do have HTML to show: a rich-text article from a CMS, or output from a Markdown converter. React gives you an escape hatch whose name is a warning:

JSX
<div dangerouslySetInnerHTML={{ __html: article.html }} />

The name is deliberate. Whatever string you pass is parsed as live HTML, so if it contains a <script> or an event handler such as onerror, it can run. The rules:

  1. Avoid it when plain JSX or a component (for example a Markdown library that outputs React elements) will do.
  2. If you must use it, sanitize first, on the server and/or just before rendering, using a maintained library such as DOMPurify. Do not write your own sanitizer for production: HTML parsing has many edge cases, and attackers collect them.
  3. Use an allowlist (only these tags and attributes are kept), never a blocklist (these bad tags are removed), because a blocklist always misses something.

The next demo is a teaching sketch of an allowlist sanitizer. It parses the string with DOMParser, which creates an inert document (nothing runs and no images load), keeps only a few tags, and drops every attribute except a checked href on links. The dirty input is shown only as text.

An allowlist sanitizer (teaching sketch)

Compare the two text boxes. The img, the script, both on... attributes, the javascript: link target and target="_blank" are gone, while the harmless formatting survived. A real sanitizer also handles tricks such as nested or malformed markup that browsers re-interpret ("mutation XSS"), which is why you should rely on DOMPurify rather than copying this sketch.

URLs are code too

Escaping text does not protect attributes that the browser treats as instructions. A link whose href begins with javascript: runs script when clicked:

JSX
// user.website comes from a profile form
<a href={user.website}>My site</a>

If an attacker sets the website to javascript:..., the visitor who clicks runs it. Recent React versions block javascript: URLs in href and similar attributes, but do not depend on one layer: validate the protocol with an allowlist before you render a user-supplied URL. The same applies to src on iframes and to redirect targets such as ?next=/orders (check that it is a path on your own site, as in authentication patterns).

Checking user-supplied links

Note that the mixed-case, space-prefixed javascript: string is caught because the URL parser normalizes it before you check the protocol. A hand-written test such as value.startsWith('javascript:') would miss it. Parse, then compare the protocol against an allowlist.

Other ways around the escaping

  • Setting ref.current.innerHTML = ... or using document.write skips React's protection just like dangerouslySetInnerHTML.
  • eval, new Function and setTimeout("string") turn strings into code.
  • Rendering on the server and embedding data as JSON in a script tag requires escaping <, as shown in SEO and metadata.
  • Markdown and rich-text libraries: prefer ones that output React elements or sanitize by default. Turning on "allow raw HTML" options without a sanitizer brings the problem back.
  • A Content Security Policy header (Content-Security-Policy) is a second line of defense: it tells the browser which script sources are allowed and can block inline scripts, limiting the damage of a missed bug.

Where to keep tokens

Where you store a sign-in credential decides what an XSS bug can steal.

Storage JavaScript can read it Sent automatically Main risk
localStorage / sessionStorage yes no Any XSS or compromised dependency can copy the token
Memory (a JS variable) yes, but only while the page lives no Lost on refresh; still readable by an XSS bug while running
HttpOnly cookie no yes CSRF (see below)

For an app that talks to its own backend, an HttpOnly, Secure, SameSite cookie is usually the best default, because injected scripts cannot read it. If you need bearer tokens, keep the short-lived access token in memory and the refresh token in an HttpOnly cookie. Whatever you choose, an XSS bug can still use the session while the page is open; storage choice limits theft, it does not replace fixing XSS.

Because cookies are attached automatically, another website can make the visitor's browser send a request to yours, for example by submitting a hidden form to POST /transfer. This is cross-site request forgery. Defenses, ideally combined:

  • Set SameSite=Lax or Strict on session cookies so they are not sent on most cross-site requests.
  • Use anti-CSRF tokens or check the Origin header on state-changing requests; frameworks and auth libraries usually do this, so use theirs and read their docs.
  • Never change data in response to a GET request.

APIs that use an Authorization header (not cookies) are not exposed to CSRF in the same way, but they carry the token-storage risk above.

Secrets do not belong in the bundle

Everything bundled into your client code is public. Environment variables with a VITE_ prefix in Vite, or NEXT_PUBLIC_ in Next.js, are copied into the bundle on purpose (see Vite, bundling and environment setup). A payment secret key, a database URL or an admin API key in those variables is published to the world. Public keys (a map key restricted by domain, an analytics ID) are fine.

With server components the same idea applies in a new form: props you pass to a Client Component are serialized and sent to the browser, so do not pass a whole user record that includes a password hash or an internal note. Pass the fields the UI needs. Frameworks offer helpers (for example the server-only package) that fail the build if server-only code is imported into client code. See server components.

Dependencies and the supply chain

A typical React app has hundreds or thousands of transitive packages, and each is code that runs with your page's privileges. Attackers publish look-alike package names (typosquatting), take over abandoned packages, or slip malicious code into a new version. Habits that reduce the risk:

  • Commit your lockfile and install with npm ci in CI, so builds use exactly the versions you reviewed.
  • Run npm audit (or your registry's scanner) regularly and enable automated update pull requests with Dependabot or Renovate, so patches arrive quickly and in small steps.
  • Think before adding a package. Check its download count, maintainers, last release and size; a ten-line helper is often better written yourself.
  • Consider npm install --ignore-scripts or reviewing install scripts, because packages can run code during installation.
  • Load third-party scripts from a CDN only with Subresource Integrity (integrity="sha384-...") and a pinned version, and keep them to a minimum. Tag managers and chat widgets have full access to your page.
  • Never put publishing tokens in code. Use your CI system's secret store.

Defense checklist

  1. Render untrusted data as JSX text; avoid dangerouslySetInnerHTML, and sanitize with DOMPurify when you cannot.
  2. Allowlist URL protocols for user-supplied links and redirects.
  3. Prefer HttpOnly SameSite cookies for sessions; guard against CSRF.
  4. Keep secrets on the server; treat every client variable as public.
  5. Add a Content Security Policy and security headers at the server or CDN.
  6. Lock, audit and minimize dependencies.
  7. Enforce permissions on the server for every request.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A user's display name contains <script>alert(1)</script>. You render it with <p>{user.name}</p>. What happens?

    Values in JSX children are escaped as text, which is React's main protection against XSS. The risk starts when you opt out, for example with dangerouslySetInnerHTML.
  2. 2. Which approach is the right way to sanitize HTML before using dangerouslySetInnerHTML?

    HTML has many tricky edge cases, so use a maintained library, and prefer allowlists over blocklists. Data from a database can still contain attacker-written HTML.
  3. 3. Why is localStorage a risky place for a long-lived access token?

    localStorage is readable by all JavaScript on your origin. An HttpOnly cookie cannot be read by scripts, which limits what an XSS bug can steal.
  4. 4. Which environment variable is safe to hold a payment provider's SECRET key in a Vite app?

    Variables exposed to client code are copied into the bundle that every visitor downloads. Minifying does not hide values. Secrets must live on a server.
  5. 5. How should you protect an app from a malicious new version of an npm package?

    A lockfile plus npm ci makes builds reproducible, so changes are reviewed instead of arriving silently. Auditing and careful selection reduce the exposure further.

Summary

  • React escapes JSX text by default; XSS appears when you bypass that with dangerouslySetInnerHTML, innerHTML or eval.
  • Sanitize any HTML you must render with a maintained library and an allowlist, and validate URL protocols for user-supplied href, src and redirects.
  • Store sessions in HttpOnly, Secure, SameSite cookies when you can; guard cookie-based requests against CSRF.
  • Everything in the client bundle is public, including VITE_ and NEXT_PUBLIC_ variables. Keep secrets on the server and send only needed fields to Client Components.
  • Treat dependencies as code you run: lock versions, audit, review additions and limit third-party scripts.
  • Add a Content Security Policy as a backstop and enforce every permission on the server.

Next: TypeScript and React