React security: tracing untrusted data through your components
Text a component renders is only one of the ways data reaches a React page.
Raw HTML, link addresses, style values, refs, third-party scripts, browser storage and build variables each take another route. This guide shows what happens at each one, according to React's documentation, MDN, OWASP, the build tools' documentation and a lab run on React 18.3.1, and gives you a worksheet to trace every flow in your own components.
In this guide
React untrusted-data trace worksheet with sanitisation fixtures
A worksheet with one flow record for each place in your components where outside data reaches HTML, a URL, a style, a script, a ref, browser storage or a build variable, with what React's documentation, MDN, OWASP and the build tools' documentation say about each and what to record. A fixtures lab follows, with three files and outputs copied in from a real run on React 18.3.1.
react.txt
Introduction17 lines
Part A. The worksheet106 lines
Part B. The fixtures lab421 lines
Part C. What the lab does not show4 lines
Whole template556 lines
REACT UNTRUSTED-DATA TRACE WORKSHEET AND SANITISATION FIXTURES
ILLUSTRATION AND TEMPLATE. Part A is a blank worksheet to copy into a ticket or a spreadsheet: one flow record for each place in your components where data your team did not write reaches HTML, a URL, a style, a script, a DOM node through a ref, browser storage or a build variable. Part B is a fixtures lab that renders invented components with react-dom/server and prints what React wrote, with every output copied in from a real run. Part C says what the lab does not show. Every component, host name, input and token in Part B is invented.
Part A only reads. The person filling it in is the application's owner, or a developer working for them, and the code and systems it covers are theirs. You read source files, build configuration and the HTML your own application serves, and you write down what you find. No step changes a setting, rotates or reveals a secret, or sends traffic to a service you do not own. Record the names of variables, storage keys and cookies, never their values, and never paste a real token into the worksheet, a ticket or the lab.
HOW TO FILL IT
- Use one copy per application. For a large application, use one copy per area, such as the customer portal or the staff screens.
- Build the list of lines to trace first. Part B's list-flows.mjs prints the lines in your source that match the code names in section 0, or you can search your code for the same names. Markdown and rich-text renderers, tag manager snippets, libraries handed a DOM node and define entries need a search of their own.
- Fill one flow record for each line. An answer you do not have is written as "unknown" and logged as a finding to resolve.
- "React's documentation says", "React's reference for version 19.3 says" and "Source" name the page behind a statement, as read on 14 November 2026. Lines marked "This page's advice" or "This page's reading" are this guide's own suggestions; React, the build tools and the browser vendors did not write them.
- Log every finding on its own line at the end, naming the person who can make the change as its owner.
Application:
react-dom version in the deployed build (from the lockfile of the deployed commit, not the range in package.json):
Build tool and its version:
Completed by (name and role): Date:
PART A. THE WORKSHEET
SECTION 0. WHAT TO SEARCH FOR
0.1 HTML: dangerouslySetInnerHTML, .innerHTML, .outerHTML, insertAdjacentHTML, document.write, and any Markdown or rich-text renderer.
0.2 URL: href, src, action and formAction props given a value from data, and assignments to window.location or to an element's src.
0.3 Style: style props given a value from data.
0.4 Script: script elements in JSX, document.createElement('script') in effects, and tag manager snippets.
0.5 Ref: useRef, ref props and callback refs, and anything that hands a DOM node to another library.
0.6 Storage: localStorage, sessionStorage and document.cookie.
0.7 Build variable: import.meta.env, process.env and your build tool's define setting.
This page's advice: a search finds the obvious lines only. Props passed with spread syntax, wrapper components that pass href or style through, and libraries that write to the DOM themselves need reading, not searching.
THE FLOW RECORD (one per line traced)
R.1 Component, file and line:
R.2 Flow: HTML, URL, style, script, ref, storage or build variable.
R.3 Where the data enters: a prop from a parent, an API response, the page address or its fragment, a form field, a CMS or Markdown field, browser storage, a message from another window, a build-time variable, or a third-party script.
R.4 Who can write that data: only your own code, any signed-in user, a staff role, anyone who can send a link, or a third party.
R.5 The React API it reaches: a text child, dangerouslySetInnerHTML, a URL prop, the style prop, a script element, a DOM call through a ref, or a storage call in an effect or handler.
R.6 What the documentation says about it: copy the line for that API from sections 1 to 7.
R.7 The control in place, if any: none, a URL allow-list, a sanitiser (name and version), a conversion to a number, a list of public fields, or something else. Write what the control is, not a verdict on it.
R.8 Evidence: the code line with any literal secret redacted, a fixture result, or an excerpt of the served HTML with values redacted.
R.9 Decision and owner.
SECTION 1. HTML FLOWS
1.1 A value placed as a child, as in <p>{review.body}</p>.
React's documentation says: the children prop takes a React node, such as an element, a string or a number, and specifies the content inside the component.
Source: React DOM reference, Common components.
Fixture: Part B step 2. react-dom/server 18.3.1 wrote the marker as text, with its angle brackets and quotes turned into entities.
Record: nothing further unless the same value also reaches one of the flows below.
1.2 A string passed to dangerouslySetInnerHTML.
React's documentation says: it overrides the innerHTML property of the DOM node; if the HTML inside is not trusted, for example if it is based on user data, you risk introducing an XSS vulnerability; use it only with trusted and sanitised data; create the {__html} object as close as possible to where the HTML is generated, and creating it inline is not recommended; and children and dangerouslySetInnerHTML cannot be passed at the same time.
Source: React DOM reference, Common components.
Fixture: Part B step 2. On react-dom/server 18.3.1, the same marker went into the HTML as an element.
Record: where the HTML string is produced (a Markdown renderer, a CMS field, an API response, a rich-text editor); whether a sanitiser runs, with its name and version; whether anything changes the string after the sanitiser has run; and whether the {__html} object is built where the HTML is made or passed down through props.
Source for the third check: the DOMPurify README warns that modifying HTML after sanitising it might void the effects of sanitisation.
1.3 An object from an API response rendered as a child.
React's changelog says, in its 0.14.0 entry (October 7, 2015): including untrusted objects as React children previously could result in an XSS vulnerability; this should be avoided by validating input at the application layer and never passing untrusted objects around the application code; and React tags elements with an ES2015 Symbol, in browsers that support it, so that it never considers untrusted JSON to be a valid element. Its 18.0.0 entry (March 29, 2022) says React now depends on modern browser features including Symbol, and lists "Assume Symbols are always available."
Source: React changelog.
Fixture: Part B step 2. react-dom/server 18.3.1 refused an object parsed from JSON in the shape of an element with an error.
Record: any child whose value is a parsed object rather than a string or number, and any code that builds elements from data, such as createElement called with an element type taken from a response.
1.4 Markdown rendered by a React component.
Source: the react-markdown README describes the library as safe by default, with no dangerouslySetInnerHTML, says it typically escapes HTML or ignores it with the skipHtml option, shows the rehype-raw plugin for a trusted environment where you trust the Markdown, and says that overwriting urlTransform to something insecure opens you up to XSS vectors and that the plugins and components you use may be insecure.
Record: the renderer and its version, every plugin that lets raw HTML through, any urlTransform override, and any custom component that uses dangerouslySetInnerHTML itself.
SECTION 2. URL FLOWS (href, src, action, formAction)
2.1 What React does depends on the version in the deployed build.
React's changelog says: 16.9.0 (August 8, 2019), under React DOM, deprecates javascript: URLs as a common attack surface; 19.0.0 (December 5, 2024), under React DOM, replaces javascript URLs with functions that throw errors.
Source: React changelog.
Fixture: Part B steps 3 and 4. On react-dom/server 18.3.1 the development build printed a warning that a future version of React will block javascript: URLs, then wrote the value into href unchanged. It printed that warning once, for the first such URL, and not for the two variants after it. The production build wrote the same HTML and printed no warning. A data: URL went into href as given on both builds.
Source: OWASP Cross Site Scripting Prevention Cheat Sheet: React 19 blocks javascript: URLs in src and href, but this does not replace application-specific URL validation.
Record: the react-dom version in the deployed build, and each URL prop fed from data, with where its value comes from (R.3).
2.2 A check that does not depend on the React version.
Source: MDN, URL() constructor: it throws a TypeError if the URL, or the base and URL together, are not a valid URL, and a relative reference needs a base. MDN, URL: protocol property: the protocol includes the final colon.
This page's advice: parse each address with the URL constructor, using the application's own origin as the base; allow only the protocols you intend, such as http: and https: for ordinary links; and use a fixed fallback for anything else. A prefix check on the raw string is not a substitute: in Part B step 3 it missed an upper-case scheme with a leading space and a scheme with a tab inside it, and the URL parser read both as javascript:.
Record: the control on each URL prop, and whether the destination can be another site. The open redirects guide covers that second question.
2.3 What a javascript: URL does.
Source: MDN, javascript: URLs: they execute JavaScript when the browser attempts to navigate, and can be used anywhere a URL is a navigation target, including the href of an a element, the src of an iframe and window.location.
SECTION 3. STYLE FLOWS
3.1 React's documentation says: style takes an object with CSS styles, with property names written in camelCase; values can be strings or numbers, and React appends px to a number unless the property is unitless; React recommends style only for dynamic styles, and plain CSS classes through className otherwise.
Source: React DOM reference, Common components.
Fixture: Part B step 5. react-dom/server 18.3.1 wrote a value that carried a second declaration into the style attribute as given, turned quotes and angle brackets in a value into entities, and threw an error when style was a string.
This page's advice: convert a value from data to the type it should be, such as a number clamped to a range or one of a fixed list of values, before it reaches the style object, and keep property names fixed in code. The XSS guide covers CSS contexts outside React.
Record: each style value from data, the property it sets and the conversion applied to it.
SECTION 4. SCRIPT FLOWS AND THIRD-PARTY SCRIPTS
4.1 A script element rendered by a component.
React's reference for version 19.3 says: the script component takes either children, the source code of an inline script, or src, the URL of an external script; its props include integrity (a cryptographic hash of the script, to verify its authenticity), nonce (a cryptographic nonce to allow the resource when using a strict Content Security Policy) and crossOrigin; React can move a script that has src and async={true} to the document head and de-duplicate scripts with the same src, and with that treatment it ignores changes to props after the script has been rendered.
Sources: React DOM reference, script; the React v19 release post of December 05, 2024, which describes this async script support as part of React 19.
Fixture: Part B step 6. react-dom/server 18.3.1 wrote each script element with the attributes it was given and no others, and its development build gave a javascript: src the same warning as an href.
4.2 A script created in an effect, or loaded through a tag manager.
Source: OWASP Third Party JavaScript Management Cheat Sheet: when third-party code executes, the third party is granted the exact same privileges that were granted to the user; there is usually no guarantee that code hosted at the third party will remain the same as seen by the developers and testers; and the content a tag manager returns can be changed by host site employees through the tag manager's own interface. The typical defences it lists include in-house script mirroring, Subresource Integrity and secure transmission of the third-party code.
Source: MDN, Web Storage API: third-party code added to a site with a script element runs in the browsing context of the embedder, and from the browser's perspective there is no difference between first-party and third-party code when a script tag is used.
Source: MDN, Subresource Integrity: the browser loads the resource only if its hash matches a value in the integrity attribute, and a cross-origin request that uses it must use CORS, so the crossorigin attribute must be included.
4.3 Record, one line per script: its URL or "inline"; the vendor and the person in your business who owns it; whether the src is fixed in code or comes from data or a CMS; whether it loads through a tag manager, and who can change that container; integrity yes or no; nonce yes or no; and what it can reach on your origin, such as storage keys, cookies without HttpOnly and the pages that show personal data.
Part B step 6 lists every script tag in an HTML string with its integrity and nonce. For your own site, save the HTML of each kind of page your application serves and read its script tags the same way.
SECTION 5. REFS AND DIRECT DOM ACCESS
5.1 React's documentation says: React puts the DOM node into the ref's current property; refs are an escape hatch, to be used only when you have to "step outside React", such as managing focus or scroll position or calling browser APIs React does not expose; modifying the DOM directly can risk conflicting with the changes React is making, and you should avoid changing DOM nodes managed by React.
Source: React, Manipulating the DOM with Refs.
Source: MDN, Element: innerHTML property: setting innerHTML parses the value as HTML.
This page's reading: once code holds a DOM node, a write to innerHTML, insertAdjacentHTML, an attribute or src goes to the browser directly, and React's handling of children and props takes no part in it. Trace each such write as a sink of its own; the map in the XSS guide pairs each sink it lists with a replacement.
Record: each ref whose node is written to, the property or method used, the value written and where it comes from, and any library that receives a DOM node from your component, such as an editor, a map, a chart or a chat widget, with its version.
SECTION 6. BROWSER STORAGE AND COOKIES
6.1 Source: MDN, Window: localStorage property: localStorage gives access to a Storage object for the document's origin, its data is saved across browser sessions and has no expiration time, and sessionStorage data is cleared when the page session ends. MDN, Web Storage API: all documents with the same origin have access to the same localStorage area.
6.2 Source: OWASP HTML5 Security Cheat Sheet: a single cross-site scripting flaw can be used to steal all the data in these objects, so sensitive information should not be stored in local storage; a single cross-site scripting flaw can also be used to load malicious data into them, so the objects in them should not be considered trusted; do not store session identifiers in local storage, because the data is always accessible by JavaScript, and cookies can mitigate this risk with the HttpOnly flag.
6.3 Source: MDN, Set-Cookie header: HttpOnly forbids JavaScript from accessing the cookie, for example through document.cookie, and a cookie with HttpOnly is still sent with requests JavaScript starts, such as fetch().
6.4 Record, one line per key or cookie: its name (never its value), what it holds, which component writes it, which components read it back and which flow in sections 1 to 3 the value then reaches, and whether it is cleared at sign-out. As this page's advice, a session token in localStorage or sessionStorage, or in a cookie without HttpOnly, goes on the findings log for a decision. The JWT guide covers where a token should live, and the cookie security guide covers the attributes of the cookie that carries it.
6.5 This page's advice: treat a value read back from storage as untrusted input, and trace it through sections 1 to 3 again.
SECTION 7. TOKENS AND BUILD VARIABLES IN CLIENT CODE
7.1 Vite. Source: Vite, Env Variables and Modes: variables prefixed with VITE_ are exposed in client-side source code after bundling, should not contain sensitive information such as API keys, and have their values bundled into the source code at build time. Source: Vite, Shared Options: envPrefix defaults to VITE_, and variables starting with it are exposed to client source code through import.meta.env; envPrefix should not be set to an empty string, which would expose every env variable, and Vite throws an error when it detects one; an unprefixed variable can be exposed with define, whose entries are statically replaced during the build.
7.2 Next.js. Source: Next.js environment variables guide: a variable prefixed with NEXT_PUBLIC_ is inlined into the JavaScript bundle delivered to the browser at build time. The Next.js guide in this library covers the rest of that framework.
7.3 Another build tool: read that tool's own documentation for its rule, and record the page and the date you read it.
7.4 Values a server writes into the page, such as a start-up config object in a data attribute or a script element.
Fixture: Part B step 7. A whole config object written into a data attribute put the invented admin token into the HTML. A copy holding only the fields picked as public did not.
7.5 Record, one line per variable or config field: its name (never its value), the prefix, define entry or server code that sends it to the browser, what it grants and to whom, and whether its provider designed it for browser use. Also record the envPrefix value and every define entry that reads process.env. As this page's advice, a key that grants more than its provider designed for browser use goes on the findings log; the secrets exposure guide covers a key that has already shipped.
SECTION 8. PAGE-LEVEL CONTROLS TO NOTE
8.1 Content Security Policy. Source: MDN, Content Security Policy guide: setting a CSP is not an alternative to sanitising input, and the recommended practice for controlling script loading as a mitigation against XSS is nonce- or hash-based fetch directives, which MDN calls a strict CSP. Record whether your pages send a Content-Security-Policy header, and whether the script elements your components render carry its nonce (section 4).
8.2 Trusted Types. React's reference for version 19.3 says: if your site enforces Trusted Types, pass a TrustedHTML value created by your security policy as __html; React passes the value to the browser without converting it to a string, allowing the browser to validate it; and your policy must still ensure that any input used to create the value is trusted and sanitised. React's changelog lists "Enable Trusted Types API integration" among the notable changes in 19.3.0 (September 9, 2026).
Source: MDN, Trusted Types API: the API does not supply a policy or any transformation functions itself. On 14 November 2026 MDN labelled it Baseline 2026, newly available, and said it might not work in older devices or browsers.
Record: whether a policy sets require-trusted-types-for, the react-dom version, and the policy that creates TrustedHTML values.
FINDINGS LOG
One line per finding:
ID | Section | Component and line | Finding | Evidence | Owner | Decision | Review by | Closed (date and evidence)
PART B. THE FIXTURES LAB
WHAT IT IS
An illustration. fixtures.mjs renders small invented components to HTML strings with renderToString from react-dom/server, which React's documentation describes as rendering a React tree to an HTML string, and prints what React wrote for five kinds of flow: HTML, links, style, scripts and tokens. list-flows.mjs reads source files and lists the lines that match the code names in section 0. sample-app/src/components.jsx is an invented file for list-flows.mjs to read; it is never compiled or run. No browser runs at any point, and nothing is sent anywhere.
WHAT IT NEEDS
Node.js, with the react and react-dom packages installed where the files sit, such as a copy of your own project. The lab downloads nothing. fixtures.mjs imports react and react-dom/server, list-flows.mjs imports only node:fs and node:path, and components.jsx is never run. The outputs below were recorded on Node.js v26.0.0 with react 18.3.1 and react-dom 18.3.1 on macOS, the versions installed where it ran. They describe that run on those versions, not a version to move to. No other React version was run. React's changelog records the javascript: URL change in 19.0.0, which is why section 2.1 asks for the version in your own deployed build.
WHAT IT DOES NOT USE
DOMPurify. Its README says that running it on the server requires a DOM to be present and recommends keeping jsdom up to date. This lab installs no DOM package, so it does not show a sanitiser at work; section 1.2 records yours instead.
HOW THE OUTPUT WAS CAPTURED
A shell script ran the steps below in order and wrote each command, its combined output and its exit code to separate files; another script then pasted those files into this page. No line of output showed a local folder path, so nothing was cut. Neither script belongs to the lab itself. In steps 3 and 4, the href rendered for the fifth input contains a tab character, because that input contains one.
SET-UP
Use a folder where react and react-dom are installed, such as a copy of your own project. Save the three files below into it under the names shown, the third inside a sample-app/src folder, then run the steps under RUN IT from that folder.
==== File 1 of 3: fixtures.mjs ====
// fixtures.mjs: renders small invented React components to HTML strings with
// react-dom/server and prints what React wrote. Run one fixture at a time:
// node fixtures.mjs html
// node fixtures.mjs links
// node fixtures.mjs style
// node fixtures.mjs scripts
// node fixtures.mjs tokens
// Illustration only. Every input, host name and token is invented, nothing is
// sent anywhere, and no browser runs: the output is the HTML string a server
// would send. If an input ever became live markup in a browser, its markers
// would at most add an i element with a data-lab-marker attribute or set the
// page title to lab-marker; the other inputs name only invented hosts.
import { createElement as h, version as reactVersion } from 'react'
import { renderToString, version as serverVersion } from 'react-dom/server'
const HTML_MARKER = '<i data-lab-marker="html">marker</i>'
const TITLE_SCRIPT = 'void(document.title="lab-marker")'
const APP_ORIGIN = 'https://shop.lab-invented.test'
function show(label, buildElement) {
try {
console.log(label + ':')
console.log(' ' + renderToString(buildElement()))
} catch (error) {
console.log(' threw: ' + error.message.split('\n')[0])
}
}
// HTML flow: the same text as a child and through dangerouslySetInnerHTML,
// then an object parsed from JSON that copies the shape of a React element.
function runHtmlFixture() {
const reviewFromApi = HTML_MARKER
show('Text child', () => h('p', null, reviewFromApi))
show('dangerouslySetInnerHTML', () => h('p', { dangerouslySetInnerHTML: { __html: reviewFromApi } }))
const lookAlike = JSON.parse('{"$$typeof":"react.element","type":"i","props":{"data-lab-marker":"json"}}')
show('Object parsed from JSON, passed as a child', () => h('p', null, lookAlike))
}
// URL flow: each link input rendered into href as given, then through an
// allow-list built on the URL parser. A naive prefix check is shown beside it.
const LINK_INPUTS = [
'https://shop.lab-invented.test/orders/42',
'/orders/42',
'javascript:' + TITLE_SCRIPT,
' JavaScript:' + TITLE_SCRIPT,
'java\tscript:' + TITLE_SCRIPT,
'data:text/html,' + HTML_MARKER,
]
const ALLOWED_PROTOCOLS = ['https:', 'http:']
function readProtocol(input) {
try {
return new URL(input, APP_ORIGIN).protocol
} catch {
return '(not a URL)'
}
}
function toAllowedHref(input) {
const protocol = readProtocol(input)
if (!ALLOWED_PROTOCOLS.includes(protocol)) return '#'
return new URL(input, APP_ORIGIN).href
}
function runLinksFixture() {
for (const input of LINK_INPUTS) {
console.log('Input ' + JSON.stringify(input))
console.log(' starts with "javascript:": ' + input.startsWith('javascript:'))
console.log(' protocol read by the URL parser: ' + readProtocol(input))
console.log(' href as given: ' + renderToString(h('a', { href: input }, 'Website')))
console.log(' href after the allow-list: ' + renderToString(h('a', { href: toAllowedHref(input) }, 'Website')))
}
}
// Style flow: values from input placed in a style object, and a style string.
function toPercent(input) {
const number = Number(input)
if (!Number.isFinite(number)) return '0%'
return Math.min(100, Math.max(0, Math.round(number))) + '%'
}
function runStyleFixture() {
show('Fixed value', () => h('div', { style: { width: '40%' } }))
show('Value carrying a second declaration', () =>
h('div', { style: { width: '40%; background-image: url(https://tracker.lab-invented.test/pixel.gif)' } }))
show('Value carrying quotes and angle brackets', () =>
h('div', { style: { width: '"><i data-lab-marker="style">' } }))
show('Input converted to a number and clamped', () => h('div', { style: { width: toPercent('250') } }))
show('A string instead of an object', () => h('div', { style: 'width: 40%' }))
}
// Third-party scripts: script elements whose src comes from data, one with
// integrity and crossOrigin, and an inline script with a nonce. Then a list
// of every script tag in the HTML.
function readAttribute(tag, name) {
const match = tag.match(new RegExp(' ' + name + '="([^"]*)"'))
return match ? match[1] : null
}
function listScriptTags(html) {
const lines = []
for (const tag of html.match(/<script[^>]*>/g) || []) {
const source = readAttribute(tag, 'src') || '(inline)'
const hasIntegrity = readAttribute(tag, 'integrity') !== null
const hasNonce = readAttribute(tag, 'nonce') !== null
lines.push(' ' + source + ' | integrity: ' + (hasIntegrity ? 'yes' : 'no') + ' | nonce: ' + (hasNonce ? 'yes' : 'no'))
}
return lines
}
function runScriptsFixture() {
const widgetSourceFromCms = 'https://widgets.lab-invented.test/chat.js'
const page = h('div', null,
h('script', { src: widgetSourceFromCms, async: true }),
h('script', { src: 'https://cdn.lab-invented.test/maps.js', integrity: 'sha384-lab-invented-hash', crossOrigin: 'anonymous' }),
h('script', { src: 'javascript:' + TITLE_SCRIPT }),
h('script', { nonce: 'lab-invented-nonce', dangerouslySetInnerHTML: { __html: 'window.labWidgetId = "lab-widget"' } }),
)
const html = renderToString(page)
console.log('HTML:')
console.log(' ' + html)
console.log('Script tags found in the HTML:')
for (const line of listScriptTags(html)) console.log(line)
}
// Tokens: a start-up config written into the page as a data attribute, once
// whole and once with only the fields picked as public.
const SERVER_CONFIG = {
apiBase: '/api',
mapsPublicKey: 'lab-invented-public-maps-key',
adminApiToken: 'lab-invented-admin-token-not-a-secret',
}
const PUBLIC_CONFIG_FIELDS = ['apiBase', 'mapsPublicKey']
function pickPublicConfig(config) {
const publicConfig = {}
for (const field of PUBLIC_CONFIG_FIELDS) publicConfig[field] = config[field]
return publicConfig
}
function renderShell(config) {
return renderToString(h('div', { id: 'root', 'data-config': JSON.stringify(config) }))
}
function runTokensFixture() {
const shells = [
['Whole config', renderShell(SERVER_CONFIG)],
['Public fields only', renderShell(pickPublicConfig(SERVER_CONFIG))],
]
for (const [label, html] of shells) {
console.log(label + ':')
console.log(' ' + html)
console.log(' admin token present in the HTML: ' + html.includes(SERVER_CONFIG.adminApiToken))
}
}
const FIXTURES = {
html: runHtmlFixture,
links: runLinksFixture,
style: runStyleFixture,
scripts: runScriptsFixture,
tokens: runTokensFixture,
}
const fixtureName = process.argv[2]
if (!FIXTURES[fixtureName]) {
console.error('usage: node fixtures.mjs html|links|style|scripts|tokens')
process.exit(1)
}
console.log('react ' + reactVersion + ', react-dom/server ' + serverVersion + ', NODE_ENV ' + (process.env.NODE_ENV || 'not set'))
FIXTURES[fixtureName]()
==== File 2 of 3: list-flows.mjs ====
// list-flows.mjs: lists the lines in your component files where untrusted data
// can reach HTML, a URL, a style, a script, a ref or browser storage, so you can
// start the trace worksheet from a list instead of from memory. It reads files
// and prints lines; it changes nothing and runs nothing it reads.
// node list-flows.mjs path/to/src
// A match is a place to look, not a finding. A line it misses is not cleared.
import fs from 'node:fs'
import path from 'node:path'
const FLOW_PATTERNS = [
{ flow: 'HTML', pattern: /dangerouslySetInnerHTML|\.innerHTML\b|\.outerHTML\b|insertAdjacentHTML|document\.write/ },
{ flow: 'URL', pattern: /\b(?:href|src|action|formAction)=\{|\.src\s*=|location\.href\s*=|window\.location\s*=/ },
{ flow: 'Style', pattern: /\bstyle=\{/ },
{ flow: 'Script', pattern: /<script\b|createElement\(['"]script['"]\)/ },
{ flow: 'Ref', pattern: /\bref=\{|\buseRef\(/ },
{ flow: 'Storage', pattern: /\blocalStorage\b|\bsessionStorage\b|document\.cookie/ },
{ flow: 'Build variable', pattern: /import\.meta\.env\.|process\.env\./ },
]
const SOURCE_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx', '.mjs']
const SKIPPED_FOLDERS = ['node_modules', 'dist', 'build', '.git']
function listSourceFiles(target) {
if (fs.statSync(target).isFile()) return [target]
const files = []
for (const entry of fs.readdirSync(target, { withFileTypes: true })) {
if (SKIPPED_FOLDERS.includes(entry.name)) continue
const fullPath = path.join(target, entry.name)
if (entry.isDirectory()) files.push(...listSourceFiles(fullPath))
else if (SOURCE_EXTENSIONS.includes(path.extname(entry.name))) files.push(fullPath)
}
return files
}
function listFlowsInFile(filePath) {
const found = []
const lines = fs.readFileSync(filePath, 'utf8').split('\n')
lines.forEach((line, index) => {
for (const { flow, pattern } of FLOW_PATTERNS) {
if (pattern.test(line)) found.push(flow.padEnd(15) + filePath + ':' + (index + 1) + ' ' + line.trim())
}
})
return found
}
const target = process.argv[2]
if (!target) {
console.error('usage: node list-flows.mjs path/to/src')
process.exit(1)
}
let total = 0
for (const filePath of listSourceFiles(target)) {
for (const line of listFlowsInFile(filePath)) {
console.log(line)
total += 1
}
}
console.log(total + ' line(s) to trace')
==== File 3 of 3: sample-app/src/components.jsx ====
// components.jsx: invented components for list-flows.mjs to read.
// This file is never compiled or run.
import { useEffect, useRef } from 'react'
export function ReviewBody({ review }) {
return <div className="review" dangerouslySetInnerHTML={{ __html: review.bodyHtml }} />
}
export function CustomerLink({ customer }) {
return <a href={customer.website}>{customer.displayName}</a>
}
export function ProgressBar({ percent }) {
return <div className="bar" style={{ width: percent + '%' }} />
}
export function ChatWidget({ widgetUrl }) {
const box = useRef(null)
useEffect(() => {
const script = document.createElement('script')
script.src = widgetUrl
box.current.appendChild(script)
}, [widgetUrl])
return <div ref={box} />
}
export function rememberSession(token) {
localStorage.setItem('sessionToken', token)
}
export const mapsKey = import.meta.env.VITE_MAPS_KEY
RUN IT, WITH WHAT EACH STEP PRINTED
STEP 1: node --version
v26.0.0
(exit code 0)
STEP 2: node fixtures.mjs html
react 18.3.1, react-dom/server 18.3.1, NODE_ENV not set
Text child:
<p><i data-lab-marker="html">marker</i></p>
dangerouslySetInnerHTML:
<p><i data-lab-marker="html">marker</i></p>
Object parsed from JSON, passed as a child:
threw: Objects are not valid as a React child (found: object with keys {$$typeof, type, props}). If you meant to render a collection of children, use an array instead.
(exit code 0)
STEP 3: node fixtures.mjs links
react 18.3.1, react-dom/server 18.3.1, NODE_ENV not set
Input "https://shop.lab-invented.test/orders/42"
starts with "javascript:": false
protocol read by the URL parser: https:
href as given: <a href="https://shop.lab-invented.test/orders/42">Website</a>
href after the allow-list: <a href="https://shop.lab-invented.test/orders/42">Website</a>
Input "/orders/42"
starts with "javascript:": false
protocol read by the URL parser: https:
href as given: <a href="/orders/42">Website</a>
href after the allow-list: <a href="https://shop.lab-invented.test/orders/42">Website</a>
Input "javascript:void(document.title=\"lab-marker\")"
starts with "javascript:": true
protocol read by the URL parser: javascript:
Warning: A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed "javascript:void(document.title=\"lab-marker\")".
at a
href as given: <a href="javascript:void(document.title="lab-marker")">Website</a>
href after the allow-list: <a href="#">Website</a>
Input " JavaScript:void(document.title=\"lab-marker\")"
starts with "javascript:": false
protocol read by the URL parser: javascript:
href as given: <a href=" JavaScript:void(document.title="lab-marker")">Website</a>
href after the allow-list: <a href="#">Website</a>
Input "java\tscript:void(document.title=\"lab-marker\")"
starts with "javascript:": false
protocol read by the URL parser: javascript:
href as given: <a href="java script:void(document.title="lab-marker")">Website</a>
href after the allow-list: <a href="#">Website</a>
Input "data:text/html,<i data-lab-marker=\"html\">marker</i>"
starts with "javascript:": false
protocol read by the URL parser: data:
href as given: <a href="data:text/html,<i data-lab-marker="html">marker</i>">Website</a>
href after the allow-list: <a href="#">Website</a>
(exit code 0)
STEP 4: NODE_ENV=production node fixtures.mjs links
react 18.3.1, react-dom/server 18.3.1, NODE_ENV production
Input "https://shop.lab-invented.test/orders/42"
starts with "javascript:": false
protocol read by the URL parser: https:
href as given: <a href="https://shop.lab-invented.test/orders/42">Website</a>
href after the allow-list: <a href="https://shop.lab-invented.test/orders/42">Website</a>
Input "/orders/42"
starts with "javascript:": false
protocol read by the URL parser: https:
href as given: <a href="/orders/42">Website</a>
href after the allow-list: <a href="https://shop.lab-invented.test/orders/42">Website</a>
Input "javascript:void(document.title=\"lab-marker\")"
starts with "javascript:": true
protocol read by the URL parser: javascript:
href as given: <a href="javascript:void(document.title="lab-marker")">Website</a>
href after the allow-list: <a href="#">Website</a>
Input " JavaScript:void(document.title=\"lab-marker\")"
starts with "javascript:": false
protocol read by the URL parser: javascript:
href as given: <a href=" JavaScript:void(document.title="lab-marker")">Website</a>
href after the allow-list: <a href="#">Website</a>
Input "java\tscript:void(document.title=\"lab-marker\")"
starts with "javascript:": false
protocol read by the URL parser: javascript:
href as given: <a href="java script:void(document.title="lab-marker")">Website</a>
href after the allow-list: <a href="#">Website</a>
Input "data:text/html,<i data-lab-marker=\"html\">marker</i>"
starts with "javascript:": false
protocol read by the URL parser: data:
href as given: <a href="data:text/html,<i data-lab-marker="html">marker</i>">Website</a>
href after the allow-list: <a href="#">Website</a>
(exit code 0)
STEP 5: node fixtures.mjs style
react 18.3.1, react-dom/server 18.3.1, NODE_ENV not set
Fixed value:
<div style="width:40%"></div>
Value carrying a second declaration:
<div style="width:40%; background-image: url(https://tracker.lab-invented.test/pixel.gif)"></div>
Value carrying quotes and angle brackets:
<div style="width:"><i data-lab-marker="style">"></div>
Input converted to a number and clamped:
<div style="width:100%"></div>
A string instead of an object:
threw: The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.
(exit code 0)
STEP 6: node fixtures.mjs scripts
react 18.3.1, react-dom/server 18.3.1, NODE_ENV not set
Warning: A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed "javascript:void(document.title=\"lab-marker\")".
at script
at div
HTML:
<div><script src="https://widgets.lab-invented.test/chat.js" async=""></script><script src="https://cdn.lab-invented.test/maps.js" integrity="sha384-lab-invented-hash" crossorigin="anonymous"></script><script src="javascript:void(document.title="lab-marker")"></script><script nonce="lab-invented-nonce">window.labWidgetId = "lab-widget"</script></div>
Script tags found in the HTML:
https://widgets.lab-invented.test/chat.js | integrity: no | nonce: no
https://cdn.lab-invented.test/maps.js | integrity: yes | nonce: no
javascript:void(document.title="lab-marker") | integrity: no | nonce: no
(inline) | integrity: no | nonce: yes
(exit code 0)
STEP 7: node fixtures.mjs tokens
react 18.3.1, react-dom/server 18.3.1, NODE_ENV not set
Whole config:
<div id="root" data-config="{"apiBase":"/api","mapsPublicKey":"lab-invented-public-maps-key","adminApiToken":"lab-invented-admin-token-not-a-secret"}"></div>
admin token present in the HTML: true
Public fields only:
<div id="root" data-config="{"apiBase":"/api","mapsPublicKey":"lab-invented-public-maps-key"}"></div>
admin token present in the HTML: false
(exit code 0)
STEP 8: node list-flows.mjs sample-app/src
HTML sample-app/src/components.jsx:6 return <div className="review" dangerouslySetInnerHTML={{ __html: review.bodyHtml }} />
URL sample-app/src/components.jsx:10 return <a href={customer.website}>{customer.displayName}</a>
Style sample-app/src/components.jsx:14 return <div className="bar" style={{ width: percent + '%' }} />
Ref sample-app/src/components.jsx:18 const box = useRef(null)
Script sample-app/src/components.jsx:20 const script = document.createElement('script')
URL sample-app/src/components.jsx:21 script.src = widgetUrl
Ref sample-app/src/components.jsx:24 return <div ref={box} />
Storage sample-app/src/components.jsx:28 localStorage.setItem('sessionToken', token)
Build variable sample-app/src/components.jsx:31 export const mapsKey = import.meta.env.VITE_MAPS_KEY
9 line(s) to trace
(exit code 0)
WHAT THE LAB SHOWED
- Step 2: the marker as a text child came out as entities. The same string through dangerouslySetInnerHTML came out as an element. An object parsed from JSON in the shape of an element was refused with an error.
- Steps 3 and 4: React 18.3.1 wrote a javascript: URL, an upper-case variant with a leading space, a variant with a tab inside the scheme and a data: URL into href unchanged. The development build warned once; the production build did not warn. The allow-list built on the URL parser replaced all four with #, kept the https address, and resolved the relative path against the invented origin.
- Step 5: a style value carried a second declaration into the HTML. Quotes and angle brackets inside a value became entities. A string in place of the style object threw an error, and the clamped number wrote 100%.
- Step 6: each script element came out with exactly the attributes it was given, and the list shows which ones carry integrity or a nonce.
- Step 7: the whole config object put the invented admin token into the HTML; the copy with only the public fields did not.
- Step 8: list-flows.mjs listed nine lines in the invented component file, covering all seven of its flow types.
PART C. WHAT THE LAB DOES NOT SHOW
- A browser. Every result is the HTML string react-dom/server returned. What a browser does with that HTML, what client-side rendering does with the same values, and anything an effect or a ref does at run time are not exercised.
- React 19 or later. Only 18.3.1 was installed where the lab ran. React's changelog describes the javascript: URL change in 19.0.0 and the Trusted Types integration in 19.3.0.
- A sanitiser, browser storage, cookies, a Content Security Policy or Trusted Types.
- Every way data reaches a sink. list-flows.mjs matches one line at a time against fixed patterns, so it misses spread props, wrapper components, expressions split across lines and libraries that write to the DOM themselves.React security: what React handles and what your components decide
React is the layer that turns your components into the page a visitor's browser shows.
React's guide to refs puts the arrangement this way: React automatically updates the DOM to match your render output, so your components won't often need to manipulate it. React security comes down to where that arrangement holds and where your own code steps around it, which is why this guide works component by component rather than from a list of attacks.
Start with what holds. In the lab on this page, react-dom/server 18.3.1 wrote a string placed as a child into the HTML as text: the angle brackets and quotes of the HTML element inside it came out as entities. Raw HTML goes in through a prop with its own name, dangerouslySetInnerHTML.
React's reference says that building the {__html} object close to where the HTML is generated ensures that all raw HTML in your code is explicitly marked as such, and that only variables you expect to contain HTML are passed to it.
The doors are the places where a component hands React, or the browser, something other than text: an HTML string, an address for href or src, a CSS value, a script element, a DOM node reached through a ref, a value kept in browser storage, or a build variable compiled into the JavaScript.
Each one behaves differently, and for links the behaviour changed between React versions. The trace worksheet on this page records each kind of flow in your own components, with what React's documentation says about it or, for browser storage and build variables, what MDN, OWASP, Vite and Next.js say.
This guide covers client-side React. Next.js routing, server components and framework advisories have their own guide, whose advisory ledger covers React security vulnerabilities in React Server Components as they reached Next.js, and hosting on Vercel has another.
Cross-site scripting as a whole, with its encoding contexts and browser checks, sits in the XSS guide; this page deals with React XSS at the component level, where untrusted data travels inside React components.
dangerouslySetInnerHTML: where an HTML string enters a component
React's reference for version 19.3 describes dangerouslySetInnerHTML as taking an object of the form {__html} with a raw HTML string or a TrustedHTML value inside, and overriding the innerHTML property of the DOM node.
It says that if the HTML inside is not trusted, for example if it is based on user data, you risk introducing an XSS vulnerability, and to use the prop only with trusted and sanitised data. In the lab on react-dom/server 18.3.1, the same string that came out as text when passed as a child came out as an element in the HTML when passed this way.
The component-level question is where the {__html} object gets built. The reference says to create it as close as possible to where the HTML is generated, and that creating it inline in the JSX is not recommended. On this page's reading, an HTML string that travels down several components as an ordinary prop, under a name such as bodyHtml, has lost that marking by the time it reaches the sink, and a reviewer reading the last component cannot tell where it came from. The worksheet asks where each HTML string is produced and where its {__html} object is created.
Where HTML has to render, a sanitiser does the filtering, and the order of steps matters. DOMPurify's README warns that modifying HTML after sanitising it might void the effects of sanitisation, and asks that any library the sanitised markup is passed to does not change the HTML on its own.
It also says that on the server DOMPurify needs a DOM to be present, and recommends keeping jsdom up to date.
This page's advice is to sanitise last, after any Markdown or template step, at the point where the {__html} object is created, and to record the sanitiser and its version.
Markdown is one source of HTML strings in React apps. The react-markdown README describes that library as safe by default, with no dangerouslySetInnerHTML, and says it typically escapes HTML or ignores it with the skipHtml option.
It shows the rehype-raw plugin for a trusted environment where you trust the Markdown, and warns that overriding urlTransform with something insecure opens you up to XSS vectors and that the plugins and components you use may be insecure.
For each renderer, the worksheet records its version, any plugin that lets raw HTML through, any urlTransform override and any custom component that sets HTML itself.
One more HTML flow is easy to miss: an object from an API response rendered as a child. React's changelog entry for 0.14.0, dated 7 October 2015, says including untrusted objects as children previously could result in an XSS vulnerability, and that React tags elements with an ES2015 Symbol, in browsers that support it, so that it never considers untrusted JSON to be a valid element.
Its 18.0.0 entry, dated 29 March 2022, says React now depends on modern browser features including Symbol.
In the lab, react-dom/server 18.3.1 refused an object parsed from JSON in the shape of an element with an error. On this page's reading, the Symbol tag stops an object parsed from JSON passing as an element, in the browsers those entries describe, and it does not apply to code that builds elements from data, such as calling createElement with an element type taken from a response. That code is a flow to trace on its own.
Links and javascript: URLs: what React does depends on the version
MDN explains that javascript: URLs execute JavaScript when the browser attempts to navigate, and can be used anywhere a URL is a navigation target, including a link's href, an iframe's src and window.location.
So every href or src that comes from data, such as a customer's website field, a link inside CMS content or a return address from the query string, is a place where the scheme matters.
React's changelog marks where this changed. Its 16.9.0 entry, dated 8 August 2019, lists under React DOM the deprecation of javascript: URLs as a common attack surface. Its 19.0.0 entry, dated 5 December 2024, has "Javascript URLs are replaced with functions that throw errors" under React DOM.
The lab ran React 18.3.1, a release that falls between those entries. Its development build printed a warning that a future version of React will block javascript: URLs, then wrote the value into href unchanged, and printed that warning for the first such URL only.
Its production build wrote the same HTML with no warning at all. A data: URL went through on both builds.
On this page's reading, the production build in the lab gave no sign that a javascript: link had reached the page, so the version that matters is the one in the deployed build, read from the lockfile of the commit that was deployed rather than the range in package.json.
OWASP's XSS Prevention Cheat Sheet says React 19 blocks javascript: URLs in src and href, but that this does not replace application-specific URL validation.
The check that does not depend on the version is a URL parser with an allow-list. MDN's URL() reference says the constructor throws a TypeError for an address that is not valid, and that a relative reference needs a base. MDN's page on the URL protocol property says it holds the scheme with its final colon.
In the lab, a prefix check on the raw string missed an upper-case scheme with a leading space and a scheme with a tab inside it, while the URL parser read both as javascript:.
This page's advice is to parse each address with your own origin as the base, allow only the schemes you intend, and fall back to a fixed value. Where the destination can be another site, the open redirects guide covers what to check next.
Style props: what react-dom/server 18.3.1 wrote for a value carrying two declarations
React's reference says the style prop takes an object of CSS styles with camelCase property names, that values can be strings or numbers, and that React appends px to a number unless the property is unitless.
It recommends style only for dynamic styles whose values are not known ahead of time, and plain CSS classes through className otherwise.
The lab shows what react-dom/server 18.3.1 did with values from outside. A width value that carried a semicolon and a background-image declaration was written into the style attribute as given, so the attribute held two declarations. Quotes and angle brackets inside a value became entities, so the value stayed inside its attribute.
A string passed in place of the object threw an error saying the prop expects a mapping from style properties to values. On this page's reading of that output, react-dom/server 18.3.1 kept a style value inside its attribute but did not check that it was a single CSS value. The lab shows server output only; client rendering of the same value was not tested.
This page's advice is to convert a style value from data to the type it ought to be before it reaches the object: a number clamped to a range, as the lab's toPercent function does when it turns 250 into 100%, or one entry from a fixed list.
Keep property names in code, and never build a style object's keys from data. CSS contexts outside React are covered in the XSS guide.
Refs and effects: where code steps outside React
React's guide to refs explains that when React creates the DOM node for an element with a ref, it puts the node into the ref's current property.
It calls refs an escape hatch, for when you have to "step outside React", such as managing focus, scroll position, or calling browser APIs that React does not expose. It says modifying the DOM directly can risk conflicting with the changes React is making, and to avoid changing DOM nodes managed by React, while noting that doing so requires caution rather than being ruled out: a part of the DOM React has no reason to update, such as a div that is always empty in the JSX, can be changed safely.
That guidance is about keeping React working; the security point is this page's own. Once code holds a DOM node, a write to its innerHTML, an attribute or a src goes straight to the browser, and React's handling of children and props takes no part in it.
MDN notes that setting innerHTML parses the value as HTML. A ref is therefore a place where an HTML, URL or script flow can start again outside React, and each write through one is traced as its own sink.
Libraries count too. Trace a rich-text editor, map, chart or chat widget that receives a DOM node from your component, and an effect that creates a script element or saves to storage, as flows of their own. The lab's list-flows.mjs lists useRef calls, ref props, script elements and storage calls alongside the props it searches for, and the worksheet records which library receives each node and at what version.
Third-party scripts run with your page's privileges
MDN's Web Storage API overview explains that third-party code added to a site with a script element runs in the browsing context of the embedder, and that from the browser's perspective there is no difference between first-party and third-party code when a script tag is used.
OWASP's Third Party JavaScript Management Cheat Sheet puts it in terms of privileges: when the code executes, the third party is granted the exact same privileges that were granted to the user. It adds that there is usually no guarantee the code hosted by the third party will remain the same as the code developers and testers saw, and that the content a tag manager returns can be changed by staff at the host site through the tag manager's interface.
React's reference for the script component, written for version 19.3, lists integrity, a cryptographic hash of the script to verify its authenticity, and nonce, a cryptographic nonce to allow the resource under a strict Content Security Policy, among the props it supports. It says React can move a script with src and async={true} into the document head and de-duplicate scripts with the same src, and that it then ignores changes to props after the script has been rendered.
The React 19 release post presents that async script support as part of React 19.
In the lab, React 18.3.1 wrote each script element with exactly the attributes it was given, including a src taken from data, and its development build gave a javascript: src the same warning as an href.
MDN's Subresource Integrity page says the browser loads a resource only when its hash matches a value in the integrity attribute, and that a cross-origin request using it must include the crossorigin attribute. OWASP lists in-house script mirroring and Subresource Integrity among the typical defences, and notes that with Subresource Integrity in place you can sometimes end up with secure but not working third-party code when the vendor decides to update it.
This page's reading is that a fixed hash suits a script whose content you control or mirror; for a script the vendor changes on its own schedule, the worksheet records who owns the vendor relationship and who can change the tag manager.
Tokens in client-side code: build variables, start-up config and browser storage
Anything a build tool compiles into the JavaScript reaches every browser that loads it.
Vite's documentation says variables prefixed with VITE_ are exposed in client-side source code after bundling, that their values are bundled into the source at build time, and that they should not contain sensitive information such as API keys. Its shared options page gives VITE_ as the default for envPrefix, says envPrefix should not be set to an empty string because that would expose every environment variable, and says Vite throws an error when it detects one; it also notes that an unprefixed variable can be exposed through define.
Next.js has its own prefix, NEXT_PUBLIC_: its documentation says the values of variables with that prefix are inlined at build time into the JavaScript bundle delivered to the browser.
The Next.js guide covers that framework. For any other tool, the worksheet asks for the tool's own documentation page and the date you read it.
A server can hand tokens to the page without any build variable. The lab writes a start-up config object into a data attribute twice: the whole object put an invented admin token into the HTML, and a copy holding only the fields picked as public did not.
This page's advice is to build that object from a short list of named public fields, never by passing a server-side settings object through.
Browser storage is the third route. MDN's localStorage reference says it gives access to a Storage object for the document's origin, with data saved across browser sessions and no expiration time, and its Web Storage API overview says every document with the same origin has access to the same localStorage area.
OWASP's HTML5 Security Cheat Sheet says a single cross-site scripting flaw can be used to steal all the data in these objects, so sensitive information should not be stored in local storage. It adds that one such flaw can also be used to load malicious data into them, so their contents should not be considered trusted, and it says not to store session identifiers in local storage, because the data is always accessible by JavaScript.
MDN's Set-Cookie reference says the HttpOnly attribute forbids JavaScript from accessing a cookie, while the cookie is still sent with requests JavaScript starts, such as fetch().
The JWT guide covers where a token should live, and the cookie security guide the attributes of the cookie that carries it; this page's advice is to trace any value your components read back from storage as untrusted input.
Trusted Types and Content Security Policy in a React app
React's reference for version 19.3 says that a site enforcing Trusted Types should pass a TrustedHTML value created by its security policy as __html, that React passes the value to the browser without converting it to a string so the browser can validate it, and that the policy must still ensure any input used to create the value is trusted and sanitised.
React's changelog lists "Enable Trusted Types API integration" among the notable changes in version 19.3.0, dated 9 September 2026. On MDN's Trusted Types page, the API does not itself supply a policy or any transformation functions: the developer defines their own.
When that MDN page was read on 14 November 2026, it labelled the API Baseline 2026, newly available, and said it might not work in older devices or browsers.
A Content Security Policy works at page level. MDN's CSP guide says setting a policy is not an alternative to sanitising input, and describes nonce- or hash-based fetch directives, which it calls a strict CSP, as the recommended practice for controlling script loading against XSS.
React's 19.3 reference for the script component lists a nonce prop for that case. This page treats both as backstops: the worksheet notes them in its last section, after the flows that need fixing in code.
React security checklist for your developers
These React security best practices are this page's own advice, drawn from the documentation cited above.
They are the questions the worksheet asks, turned into habits.
- Render values from outside as children or ordinary props. Use dangerouslySetInnerHTML only where HTML must render, and build its {__html} object where that HTML is sanitised.
- Sanitise HTML last, after any Markdown or template step, and change nothing afterwards. Record the sanitiser and its version.
- Pass every href, src, action and formAction that comes from data through a URL-parser allow-list, whatever the React version.
- Convert style values from data to numbers or fixed choices before they reach the style object, and keep property names in code.
- Treat each write through a ref, and each DOM node handed to a library, as a sink to trace.
- Keep a register of third-party scripts with an owner, the source of each src, integrity, nonce and who can change the tag manager.
- Keep session identifiers out of localStorage and sessionStorage where you have the choice, and trace values read back from storage as untrusted.
- Give the browser prefix only to values whose provider designed them for browsers, and record envPrefix and every define entry.
- Record the react-dom version in the deployed build, and read React's changelog before relying on behaviour that changed between versions.
How to use the trace worksheet and the fixtures
The worksheet is built around one record per flow, so that a reviewer can see where each value enters, who can write it, which React API it reaches and what control sits in between.
Fill it from your source code and from the HTML your application serves. Every step reads and records; a change that a finding calls for is made later, as its own planned change.
- Run list-flows.mjs from the lab against your source folder, or search for the names in section 0. Each line it prints is a place to look, and a line it misses is not cleared.
- Fill one flow record for each line, copying the line from sections 1 to 7 that gives what the documentation says about that API.
- Run the fixtures in a copy of your own project to see what your react-dom version prints. They are illustrations rather than maintained tools.
- For third-party scripts, save the HTML of each kind of page your application serves and list its script tags, as step 6 of the lab does.
- Record names of variables, storage keys and cookies only. A value never goes into the worksheet, and a real token never goes into the lab.
- Give every finding an owner who can make the change, and revisit the worksheet when react-dom changes version or a new third-party script arrives.
What a review of your own components cannot show
A completed worksheet records the flows you found, at the React version and on the day you recorded.
It cannot show what a browser does with your pages at run time, what code a third-party script will serve tomorrow, or a flow the search did not find, such as a value passed through spread props or written to the DOM by a library. The lab adds server-rendered strings on React 18.3.1 only: no browser, no client-side rendering and no React 19.
It also says nothing about the server. React decides what a page shows; whether the API behind it returns another customer's data, or accepts a change it should refuse, is decided by server code, which a review of components does not read. That question belongs to a test of the running application and its API.
Where a Clever Ops review fits
This guide is informational, and nothing on it describes a test of React itself.
The worksheet and the fixtures are for your own team to keep and rerun.
Active testing of your own React application sits within a scoped web application penetration test. Clever Ops tests custom web applications and their APIs, such as applications built on Next.js, React or Node, in a signed-in test that covers what each role can see and change, and read-only code access to named areas can be added to confirm how a control is enforced.
A secure code review reads the source with read-only access to your repository, under a written scope that names what is read.
The website security check reads the page source and JavaScript a visitor receives for keys and secrets (WSTG v4.2, WSTG-INFO-05), and reviews a site's Content Security Policy against the OWASP Content Security Policy Cheat Sheet.
Where Clever Ops built or hosts the React application, the same work is called a security review, not an independent test, and the report names who built it and who hosts it.
Frequently asked questions
It depends on the version. React's changelog lists the deprecation of javascript: URLs in 16.9.0, and for 19.0.0 lists that they are replaced with functions that throw errors. In this page's lab, react-dom/server 18.3.1 printed a warning in its development build and still wrote the link into the HTML, and its production build wrote it with no warning. OWASP's XSS Prevention Cheat Sheet says React 19's blocking does not replace application-specific URL validation. This page's advice is to check the scheme in your own code on every version.
React's reference says to use it only with trusted and sanitised data, and to create the {__html} object as close as possible to where the HTML is generated; it does not recommend creating the object inline. DOMPurify's README warns that modifying HTML after sanitising it might void the effects of sanitisation, and says that on the server DOMPurify needs a DOM to be present, recommending that jsdom be kept up to date. Record where each HTML string comes from and which sanitiser and version handle it.
No. Vite's guide to env variables says variables prefixed with VITE_ are exposed in client-side source code after bundling, that their values are bundled in at build time, and that they should not contain sensitive information such as API keys. Vite's shared options page says envPrefix defaults to VITE_, and that Vite throws an error if envPrefix is set to an empty string, which would expose every variable.
Local storage is where OWASP's HTML5 Security Cheat Sheet advises against keeping session identifiers: it says data there is always accessible by JavaScript, and that a single cross-site scripting flaw can be used to steal all of it. MDN describes localStorage data as kept across browser sessions with no expiration time. For cookies, MDN's Set-Cookie reference says HttpOnly forbids JavaScript from accessing the cookie, which still goes out with requests JavaScript starts, such as fetch(). The JWT guide compares the options.
A ref hands your code the DOM node React created, and React's documentation calls refs an escape hatch for when you have to "step outside React". On this page's reading, writes made through it, such as setting innerHTML, go to the browser directly. MDN notes that setting innerHTML parses the value as HTML. Trace each write through a ref as its own sink.
React's reference for version 19.3 says that a site enforcing Trusted Types should pass a TrustedHTML value created by its security policy as __html, that React passes it to the browser without converting it to a string so the browser can validate it, and that the policy must still make sure any input used to create it is trusted and sanitised. React's changelog lists "Enable Trusted Types API integration" among the notable changes in 19.3.0, dated 9 September 2026. On 14 November 2026, MDN labelled the Trusted Types API Baseline 2026, newly available, and said it might not work in older devices or browsers.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.