跳转到主要内容

Security

React provides some XSS protection by default, but security is systemic: inputs, outputs, dependencies, and delivery all matter.

A useful mindset: assume every external string is untrusted, and design boundaries that make the safe path the default.

XSS basics in React

React reduces some XSS risk by escaping text by default, but you can still create vulnerabilities through HTML injection, URL injection, and unsafe third-party scripts.

  • `JSX` text nodes are escaped by default.
  • Danger zones are raw HTML injection and unsafe URL handling.

Raw HTML: treat as untrusted by default

The moment you render user-controlled HTML, you are in XSS territory. Only allow it if you can strictly sanitize and constrain features.

If you are building rich text, prefer a structured document model and render it yourself. “HTML strings” are a footgun.

  • Prefer a structured representation (`Markdown` subset, rich-text model) over “HTML string”.
  • If you must render HTML, sanitize with a trusted allowlist and remove dangerous attributes (`on*` handlers, `style`, `srcdoc`).

Safe URL handling (links, images)

`XSS` is not only HTML injection. URL-based attacks (`javascript:`, `data:`) can execute code when used in `href`/`src`.

A simple baseline is to allow only `http:`/`https:` (and optionally `mailto:`), and reject everything else.

TypeScript
export function safeUrl(input: string) {
  try {
    const url = new URL(input, 'https://example.com');
    const protocol = url.protocol.toLowerCase();
    if (protocol === 'http:' || protocol === 'https:' || protocol === 'mailto:') {
      return url.href;
    }
    return null;
  } catch {
    return null;
  }
}

Third-party scripts

Third-party scripts are a supply-chain risk. Every script you add expands your attack surface.

  • Treat third-party scripts as code execution with your origin privileges. Limit and review.
  • Prefer loading on demand and isolating where possible (subdomain, sandboxed iframe).

Deployment and CSP

`CSP` can mitigate classes of `XSS` by restricting script sources. Start in `report-only` mode and tighten gradually.

Treat CSP as a migration: observe, fix violations, and then enforce. The goal is not perfect CSP on day one, but a steady tightening loop.

Bash
Content-Security-Policy: default-src 'self'; script-src 'self'; object-src 'none'; base-uri 'self'; frame-ancestors 'none'

Dependency hygiene

Most real-world compromises are caused by dependency issues. Make upgrades and scans routine so you are not surprised during a crisis.

  • Pin and review major upgrades; keep an upgrade cadence to reduce risky jumps.
  • Automate vulnerability scanning in `CI` and treat high-severity issues as release blockers.

Production checklist

  • No raw HTML rendering without `sanitize` and an allowlist.
  • User-provided URLs are validated/allowlisted before use in `href`/`src`.
  • `CSP` is enabled (`report-only` first, then enforced).
  • Dependencies are scanned and upgrades are routine.

Further reading

Security - Guides - React Docs - React 文档