🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

React Security: XSS, CSRF, and Safe Token Storage

React SecurityđŸŸĸ Free Lesson

What You'll Learn

  • 1Identify the three realistic cross-site scripting paths in a React codebase
  • 2Sanitise rich content and untrusted URLs before they reach the DOM
  • 3Pick a token storage and transmission strategy with a clear threat model
  • 4Write a content security policy that survives contact with your build pipeline

React escapes interpolation by default, which lulls teams into treating cross-site scripting as a solved problem. It is solved for the ordinary case: text placed in the tree is rendered as text, and the classic injection of markup through a data binding does not work. The realistic attacks live in the places where you deliberately opt out of that protection, in URLs the browser will happily execute, in the server's own templates, and in everything that happens after authentication — token storage, request forgery, and the third-party scripts you loaded to render a chart. Security in a React application is mostly a story about those five surfaces.

The three ways script still gets in

The first is the escape hatch itself. Rendering server-supplied rich text, a markdown export or a colleague's annotation through a raw HTML sink runs whatever was stored, and stored script runs for every viewer including admins. The second is untrusted URLs: a link whose href comes from user input can carry a script-bearing scheme, and an image source from a query string can do the same. The third is subtler and more common — a server-rendered page that reflects input into its own HTML before React ever hydrates, which means the payload executes during parse, before your sanitising component had a chance to run.

Treat each differently. Sanitise rich content at the sink with an allow-list, validate schemes on every URL you render, and audit the server's own output so hydration never begins with injected nodes already in the document.

import DOMPurify from 'dompurify';

const ALLOWED_TAGS = ['p', 'br', 'strong', 'em', 'ul', 'ol', 'li', 'blockquote', 'a', 'code', 'pre'];
const ALLOWED_ATTR = ['href', 'rel', 'target'];

function sanitizeRichText(html) {
  return DOMPurify.sanitize(html, {
    ALLOWED_TAGS,
    ALLOWED_ATTR,
    ADD_ATTR: ['target'],
  });
}

function safeHref(value) {
  try {
    const url = new URL(value, window.location.origin);
    if (url.protocol === 'http:' || url.protocol === 'https:') return url.href;
  } catch (error) {
    return null;
  }
  return null;
}

export function CommentBody({ html, link }) {
  const href = safeHref(link);

  return (
    <article>
      <div dangerouslySetInnerHTML={{ __html: sanitizeRichText(html) }} />
      {href && (
        <a href={href} rel="noopener noreferrer nofollow" target="_blank">
          Read the source
        </a>
      )}
    </article>
  );
}

Two details in that fragment carry weight. The allow-list is a list of what is permitted, never a list of what to block, because attackers will use the tags you forgot rather than the ones you removed. And the link is passed through a URL constructor restricted to http and https, which removes javascript, data and vbscript schemes without a hand-written string check that eventually misses an encoded variant. Adding rel with noopener is not strictly a script defence, but it closes the reverse-tabnabbing window that comes with target blank.

Sanitisation must also happen at write time on the server. Filtering only in the React layer means a direct API call stores the payload, and the next consumer — a mobile client, an email digest, an admin tool without your component — renders it unsanitised.

Cross-site request forgery and why it still exists

Forgery relies on the browser attaching credentials automatically. If your session is a cookie and a malicious page can cause a request to your origin, the request is authenticated whether the user intended it or not. Single-page applications moved much of the industry to bearer tokens in memory precisely because they are not attached automatically, but many teams use cookie sessions for their refresh flow and inherit the problem again.

The defences stack. SameSite cookies set to lax or strict remove most cross-site cases outright. Requiring a custom header on every mutating request is effective because a cross-origin page cannot set it without a preflight that fails. The classic synchroniser token works when the server issues a per-session value that the client must echo, and the double-submit pattern — a random value in a cookie that is not http-only plus the same value in a header — is the version that works without server-side session state.

import { useEffect, useState } from 'react';

function readCookie(name) {
  const match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
  return match ? decodeURIComponent(match[1]) : '';
}

export function useApiFetch() {
  const [csrfToken, setCsrfToken] = useState('');

  useEffect(() => {
    if (readCookie('csrf')) {
      setCsrfToken(readCookie('csrf'));
      return;
    }
    fetch('/api/session', { credentials: 'include' })
      .then((res) => res.json())
      .then((data) => setCsrfToken(data.csrfToken));
  }, []);

  return async function request(path, options) {
    const response = await fetch(path, {
      credentials: 'include',
      ...options,
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-Token': csrfToken,
        ...(options && options.headers ? options.headers : {}),
      },
    });

    if (response.status === 403) {
      throw Object.assign(new Error('Request rejected'), { code: 'FORBIDDEN' });
    }
    return response.json();
  };
}

The credentials option deserves attention: including cookies on every request is what makes the session work and what makes forgery possible, so it should be paired with origin checks on the server for state-changing routes rather than used casually. Verify the Origin or Referer header on the server for anything that mutates state, and treat a mismatch as a rejection rather than a log line.

Where tokens should live

There is no universally correct answer, only a trade-off you should make knowingly. A cookie marked http-only and secure cannot be read by script, which removes an entire class of exfiltration, at the cost of requiring csrf defences. A token in memory survives only until the page reloads, which is why refresh flows exist. Local storage is readable by any script on the origin, so one injected third-party tag drains the session — and third-party tags are precisely what marketing and analytics add.

LocationReadable by scriptSurvives reloadCSRF riskPractical verdict
http-only cookieNoYesYes, needs tokens and origin checksBest default for sessions
In-memory variableYes, same originNoNoAccess tokens for the tab lifetime
Session storageYes, same originPer tabNoTab-scoped flows and wizards
Local storageYes, same originYesNoAvoid for credentials; fine for prefs
IndexedDB with a key held elsewherePartiallyYesNoLarge offline payloads, not secrets

Whatever you choose, the server must rotate and expire. Short-lived access tokens with a refresh that is itself protected keep the blast radius of a stolen credential to minutes rather than months, and a revocation list on the server is what turns a stolen token into a temporary inconvenience.

A content security policy that does not break the build

A policy is a browser-enforced constraint on where script, style, images and connections may come from. Written tightly it converts a successful injection into a non-event, because injected markup cannot load the attacker's script. Written loosely — with unsafe inline and unsafe eval everywhere — it documents an intention without enforcing anything.

Start by observing what your build actually emits. Report-only mode on staging tells you which inline scripts your framework needs, whether your analytics tag is the only reason unsafe inline is present, and which font or image origins you forgot. Then lock it down: script sources restricted to your origin plus any audited vendor, connections limited to your API and telemetry endpoints, and frame ancestors set so your pages cannot be embedded where clickjacking lives.

DirectiveTypical valueWhat it stops
default-srcselfAnything not explicitly allowed
script-srcself plus hashed vendor originsInjected script tags and inline payloads
style-srcself plus unsafe-hashed inlineStyle-based data exfiltration
img-srcself plus data and your CDNBeaconing to an attacker server
connect-srcself plus API and telemetry originsExfiltration through fetch
frame-ancestorsnone or selfClickjacking through embedding

Prefer nonces or hashes over unsafe inline wherever the framework allows it, and keep report-uri or report-to active so a future regression is visible in telemetry instead of silent until someone reports a broken widget.

Secrets do not belong in the bundle

Anything shipped to the browser is public, including variables with an environment prefix that looks official. The client cannot hold a secret: not an API key for a paid service, not the private half of a signing pair, not a master encryption key. The correct shape is a narrow server-side endpoint that does the privileged thing with scoped permissions, and a client that holds only a public identifier.

The same reasoning covers server-rendered configuration and feature flags that gate billing. If a value changes what the user is allowed to do rather than merely how the interface looks, the enforcement belongs on the server, with the client using it only to decide what to render. Auditing for this means grepping the built output for known key patterns after every release, because the leak is invisible in source review when it lives in a dependency's default configuration.

Testing the frontend as an attacker would

Automated scanning catches the shallow issues: missing headers, raw HTML sinks, and dependency advisories. The deeper checks are manual and cheap. Paste a script payload into every field that stores text and see where it reappears, including in exports and emails. Open the network panel and replay a mutating request from a foreign origin. Read the built bundle for anything that looks like a credential. Turn the content policy report-only on and fix what it complains about. Each of those takes under an hour and finds more than a generic scanner will.

Common Mistakes

Sanitising only in the React layer while the API stores raw markup

Fix: Sanitise on write as well as on render so every consumer receives clean content

Rendering user-supplied links without validating the scheme

Fix: Parse with a URL constructor and allow only http and https

Keeping long-lived credentials in local storage because it is convenient

Fix: Use an http-only cookie or a short-lived in-memory token with rotation

Allowing unsafe inline scripts to silence a noisy policy

Fix: Use nonces or hashes and move inline logic into bundled files

Best Practices

  • Keep a narrow allow-list for any rich content and default-deny everything else
  • Require a custom header or synchroniser token plus an origin check on mutations
  • Expire and rotate tokens on the server regardless of where the client keeps them
  • Run a report-only content policy on staging and fix every violation before shipping
  • Scan built artifacts for credentials on release so a leaked key is found by you first

Key Takeaways

  • React escapes by default, so the real risks are raw HTML sinks, unsafe URLs and server-side reflection
  • Sanitisation belongs at write time as well as at render time
  • Forgery defences are layered: same-site cookies, custom headers and origin checks
  • Local storage is readable by any script on the origin, which is why injected tags steal sessions
  • A tight content security policy turns a successful injection into a blocked request
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement