Part 1 · Cross-site scripting: what React escapes and what it does not
What cross-site scripting is
A residents' association forum lets neighbours post comments, so every comment is input from a stranger. This chapter covers how React treats that input, how to add browser-level defences, and how to ship the result safely.
Cross-site scripting (XSS) means an attacker gets their own JavaScript to run inside your page. The browser cannot tell it from your code, so it runs with your page's permissions: it can read what the user sees, call your API with the user's cookies and change the page. On a forum the usual route is a stored attack. The attacker posts a comment that contains markup, the server saves it, and every neighbour who opens the thread loads it.
The defence has two halves. Output handling decides how each piece of data enters the page, so that data stays data. Browser policies, covered in the next lesson, limit the damage when that handling fails. The OWASP cross-site scripting prevention cheat sheet puts most of the weight on the first half. It says frameworks help by escaping what they render, and that the usual way to lose the protection is an escape hatch such as dangerouslySetInnerHTML without sanitising.
The lab forum has three seeded comments. The second carries an image whose onerror handler adds one to window.__xss, a counter that stands in for an attacker's script. The third is a link whose address starts with javascript:.
The HTML stored for comments 2 and 3 in the seed data. Long lines are wrapped to fit.
What React does for you
React turns a string in braces into a text node. The browser never parses that string as HTML, so markup in a comment shows up as visible characters. The forum's first mode does only that.
tsx
if (mode === 'text') return <p>{comment.html}</p>
The text branch of the comment body.
text
text mode, Kabir: <h2>Kabir</h2><p><img src="x" onerror="window.__xss
= (window.__xss || 0) + 1">Great news</p>
img elements in the page: 0
Output of a real run in jsdom. The page has no img elements at all. Long lines are wrapped to fit.
The angle brackets came out as < and >, which is how the DOM serialises literal characters. Nothing was parsed as an element, so no handler exists to run. This is the default, and it needs no effort from you.
The escape hatch
Sometimes a product needs real markup: bold text, a short list, a link. React's answer is dangerouslySetInnerHTML, which takes an object with an __html key. The react.dev page for it says to use it only with trusted and sanitised data, and warns that markup from a source you do not fully trust makes an XSS hole easy to create.
Real run in jsdom: the markup became real elements. Long lines are wrapped to fit.
jsdom does not load images or run handlers here, so a real browser has to show whether the code runs. The lab built the forum with Vite and opened it in Chrome 157, once per mode. After the page loaded, the run clicked the Parking map link when it existed.
Mode
window.__xss after load and one click
img elements
text
0
0
unsafe
2
1
sanitised
0
1
In the unsafe mode the counter reached 2: one from the image's failed load and one from the click on the link. Sanitising fixes this. Sanitising means parsing the HTML and removing everything that is not on a list of safe tags and attributes. OWASP recommends DOMPurify for this and adds that you must patch it regularly. The lab used DOMPurify 3.4.17.
sanitised, Meera: <h2>Meera</h2><div><p>The lift repair is done. Thanks
to the <b>committee</b>.</p></div>
sanitised, Kabir: <h2>Kabir</h2><div><img src="x">Great news</div>
sanitised, Anita: <h2>Anita</h2><div><a>Parking map</a></div>
Real run in jsdom with the same three comments. Long lines are wrapped to fit.
The ordinary comment kept its bold text. The image lost its handler but is still an image, and the link lost its address. In Chrome the counter stayed at 0.
Here is the same story as a sequence.
Animated sceneOne comment, three routes into the page0:16
Watch for the same comment taking three routes into the page
Read it as steps
A comment with an onerror payload reaches the page as text, as raw HTML, or sanitised
The three routes differ in one decision: whether the string is handed to the HTML parser as it is. Text never is. The unsafe route always is. The sanitised route is only safe because the parser sees cleaned HTML.
Addresses need their own check
Attributes that take a URL are a second route. A link whose address begins with javascript: runs code when followed. The React 19 upgrade guide lists, among its breaking changes, an error for javascript: URLs in src and href, and OWASP's cheat sheet says React 19 blocks them but that this does not replace validation specific to your application. The lab tried seven addresses.
"https://example.com/lift" -> https://example.com/lift | safeHref:
https://example.com/lift
"/parking" -> /parking | safeHref:
https://forum.example.com/parking
"javascript:alert(1)" -> javascript:throw new Error('React has
blocked a javascript: URL as a security precaution.') | safeHref:
undefined
" JavaScript:alert(1)" -> javascript:throw new Error('React has
blocked a javascript: URL as a security precaution.') | safeHref:
undefined
"java\tscript:alert(1)" -> javascript:throw new Error('React has
blocked a javascript: URL as a security precaution.') | safeHref:
undefined
"data:text/html,hello" -> data:text/html,hello | safeHref:
undefined
"vbscript:msgbox(1)" -> vbscript:msgbox(1) | safeHref:
undefined
Real run in jsdom: what React put in the href, then what safeHref returned. Long lines are wrapped to fit.
React replaced the three javascript: variants, including one with leading spaces, mixed case and a tab inside the word. It left data: and vbscript: alone. The replacement is itself a javascript: URL that throws that message when followed; the lab did not click it. The helper above allows only http: and https:, which is the allow-list of http and https URLs that OWASP's cheat sheet recommends, and it reads the address with the same URL parser the browser uses, so spaces and mixed case do not hide the scheme.
A comment contains <img src=x onerror=...>. Why is it harmless when rendered as {comment.html}?
React inserts the string as a text node, so the browser never parses it as markup. In the run the angle brackets were escaped and the page had no img elements.
What did sanitising change in the run, and what did it keep?
DOMPurify removed the onerror handler and the javascript: address, and kept the image, the link text and the bold tag in the ordinary comment.
React 19 blocks javascript: URLs. Why still validate addresses yourself?
React rewrote only javascript: addresses. In the run data: and vbscript: addresses passed through unchanged, and OWASP says the React change does not replace application-specific validation.
Part 2 · Content Security Policy and Trusted Types
A second layer in the response header
Sanitising fails when a rule is missed or a library has a bug. A Content Security Policy (CSP) limits the damage in that case. It is a set of rules the server sends in the Content-Security-Policy response header, and the browser enforces them for that page. MDN describes its main use as controlling which resources, especially JavaScript, a page may load, as a defence against XSS. OWASP calls it an additional layer, not the primary defence, and MDN says that setting a CSP is not an alternative to sanitising input: do both.
A policy is a list of directives separated by semicolons. default-src is the fallback for resource types without their own directive, and script-src controls JavaScript. MDN states that when a policy has either of them, inline JavaScript will not run unless extra measures allow it. That covers inline <script> blocks, inline event handlers such as onerror="..." and javascript: URLs.
The response header the lab server sent with the page. Long lines are wrapped to fit.
A Vite production build fits this policy because it writes the page's scripts as separate files. The built index.html has one external module script and one modulepreload link, and no inline script.
dist/index.html after vite build, head only. Long lines are wrapped to fit.
What the policy blocked
The lab served the same build with and without the header and loaded it in Chrome 157. A listener for the securitypolicyviolation event recorded each report.
Mode and policy
__xss
Violation reports
unsafe, no policy
2
none
unsafe, script-src 'self'
0
script-src-attr, script-src-elem
sanitised, script-src 'self'
0
script-src-attr
Chrome printed two console messages for the unsafe page. The first was "Executing inline event handler violates the following Content Security Policy directive 'script-src 'self''", for the image. The second was "Running the JavaScript URL violates the following Content Security Policy directive 'script-src 'self''", for the click on the link. The counter stayed at 0.
The last row needs a careful reading. The sanitised page also produced one report, although its final DOM held no handler and the counter was 0. A separate probe page found the cause. The probe sent the same script-src 'self' policy, loaded DOMPurify as a plain script and logged every securitypolicyviolation event with its source file and line.
text
DOMParser.parseFromString(html) -> script-src-attr, probe.js line 8
createHTMLDocument + body.innerHTML -> script-src-attr, probe.js line 9
template.innerHTML = html -> script-src-attr, probe.js line
10
DOMPurify.sanitize(html) -> script-src-attr, purify.js line
1844
DOMPurify.sanitize('<b>hi</b>') -> no report
Chrome 157, probe page with script-src 'self'. One report per parse of markup that contains onerror; none for markup without a handler. Long lines are wrapped to fit.
Line 1844 of the DOMPurify file is its call to new DOMParser().parseFromString. Chrome reported a violation when the parser read an onerror attribute into a detached, inert document, before DOMPurify removed it, so the report came from the sanitiser's own parsing step and no code ran. This is behaviour observed in Chrome 157 on this machine, and the lab did not find it written down in the CSP documents. The practical lesson stands: a violation report is a signal to look at, and by itself it does not prove that an attacker's code ran. A page that sanitises markup with handlers in it can send some noise to its report endpoint.
MDN also describes the Content-Security-Policy-Report-Only header, which reports violations without enforcing the policy. That is the safe way to roll out a new policy on a live site. Pages that need inline <script> blocks can use nonces or hashes instead of 'unsafe-inline', and Vite's html.cspNonce option is a placeholder for the nonce in the tags it generates. MDN is clear that nonces and hashes do not unblock inline event handlers or javascript: URLs: they have to be refactored away, for example into addEventListener calls. So the onerror payload in this chapter stays blocked under a nonce policy too. The chapter did not run nonces, hashes or Report-Only.
Trusted Types: making the dangerous call explicit
A CSP controls where scripts may come from. Trusted Types adds a different rule, for the calls that turn strings into code or markup, such as innerHTML. MDN says the API makes sure input passes through a transformation function you define before it reaches such a call. You turn the rule on with the directive require-trusted-types-for 'script', and after that a plain string given to innerHTML throws a TypeError. The API does not sanitise anything itself: you write a policy, a named set of functions that return trusted values.
React uses innerHTML for dangerouslySetInnerHTML, so this is exactly where it bites. The lab added the directive to the policy and loaded the unsafe mode.
text
This document requires 'TrustedHTML' assignment. The action has been
blocked.
Failed to set the 'innerHTML' property on 'Element': This document
requires 'TrustedHTML' assignment.
Chrome 157 console and page error, unsafe mode with Trusted Types required. Long lines are wrapped to fit.
The forum rendered no articles at all: React threw while setting the HTML and the page showed an uncaught error. The fix is to build the value through a policy that sanitises.
The policy is created once and its createHTML runs DOMPurify.
The React 19.3 release post says why this now works: React used to turn every value into a string before giving it to DOM calls, which would turn a trusted value back into a plain string, and it now passes these values through unchanged so the browser can check them. In the lab, dangerouslySetInnerHTML={{ __html: trusted }} with the policy's output rendered all three comments with the directive on and the counter at 0. That run also logged the one script-src-attr report from DOMPurify's parsing step described above. MDN lists Trusted Types as Baseline 2026, newly available: it says the feature has worked across the latest devices and browser versions since February 2026, and may not work in older ones.
The directive also changes how you read errors. Every string-to-HTML call in your code and in your dependencies now has to go through a policy, so enabling it on a large app is a project. Trusted Types is a good fit for new code and for the few places that really need dangerouslySetInnerHTML.
What does script-src 'self' do to an inline onerror attribute?
Chrome refused to run it. The run reported a script-src-attr violation and the counter stayed at 0.
What happened when the unsafe mode ran with require-trusted-types-for 'script'?
React could not assign a plain string to innerHTML, Chrome threw a TypeError about TrustedHTML, and no comments rendered.
Does Trusted Types sanitise the markup for you?
No. MDN says the API supplies no policy of its own. The lab's policy called DOMPurify inside createHTML.
Part 3 · Cookies, tokens and CSRF
Where to keep a session
After sign-in, the browser must prove who it is on every request. The two usual carriers are a cookie, which the browser attaches itself, and a token in a header, which your code attaches. Where the value lives decides what an XSS bug can steal. OWASP's HTML5 security cheat sheet says not to store session identifiers in local storage, because that data is always accessible to JavaScript, and suggests cookies, noting that the HttpOnly flag can mitigate the risk.
The lab's forum server set three cookies at sign-in and a Chrome 157 page read them back.
Real run. document.cookie in the page, then what the browser stored.
Script on the page saw only theme. The two session cookies are HttpOnly, which MDN says forbids JavaScript from reading the cookie through document.cookie. MDN adds that such a cookie is still sent with requests made from JavaScript, such as fetch(), and that this mitigates XSS attacks and does not remove them. An XSS bug can still make requests that carry those cookies, so HttpOnly limits what is stolen, not what an attacker can do while the page is open. That is why the previous lessons come first.
The other flags are simple to state. MDN says Secure sends the cookie only over HTTPS, with an exception for localhost, which is why the lab's Secure cookie worked over plain HTTP. SameSite takes Strict, Lax or None, and None requires Secure. MDN adds that a cookie with a __Host- name prefix must be Secure, set from a secure page, have no Domain and have the path /. The lab did not run the prefix.
Cross-site request forgery
Cross-site request forgery (CSRF) is the attack that cookies invite. Because the browser attaches cookies by itself, a page on another site can make the browser send a request to the forum, and the forum sees the user's session. The attacker never reads the cookie; the browser sends it for them.
The lab served the forum on http://localhost:56121 and an attacker page on http://127.0.0.1:56122. Chrome sent Sec-Fetch-Site: cross-site for requests between them, so they count as different sites. The attacker page is one auto-submitting form.
The user was signed in to the forum in the same browser. The lab pointed the form at three endpoints in turn.
text
attack on /comment-lax -> no session cookie
attack on /comment-none -> posted "buy my flat" as meera
attack on /comment-protected -> bad origin
real form on /comment-protected -> posted "from the real form" as meera
Real run in Chrome 157.
text
/comment-lax: cookies seen [session_none, theme], Origin
http://127.0.0.1:56122, Sec-Fetch-Site cross-site
/comment-none: cookies seen [session_none, theme], Origin
http://127.0.0.1:56122, Sec-Fetch-Site cross-site
/comment-protected: cookies seen [session_none, theme], Origin
http://127.0.0.1:56122, Sec-Fetch-Site cross-site
/comment-protected: cookies seen [session_lax, session_none, theme],
Origin http://localhost:56121, Sec-Fetch-Site same-origin
What the server saw on each request. Long lines are wrapped to fit.
Each endpoint checks one cookie. The SameSite=Lax cookie was not sent on the cross-site form post, so that endpoint refused the request. The SameSite=None cookie was sent, and the forged comment was accepted. The third endpoint accepted nothing from the attacker page because it checks two more things.
Defences that do not depend on one flag
The third endpoint is the shape OWASP's CSRF cheat sheet recommends: do not rely on the cookie alone. It lists synchroniser tokens, signed double-submit cookies, custom request headers for AJAX and API endpoints, and verifying the Origin header, falling back to the Referer when Origin is missing and rejecting the request if neither can be trusted. It also says SameSite does not replace a proper CSRF defence in most deployments, and that GET requests must never change state, because Lax cookies still travel on top-level GET navigations.
js
if (url.pathname === '/comment-protected') {
if (req.headers.origin !== victimOrigin)
return res.writeHead(403).end('bad origin')
if (body.get('csrf') !== csrfToken)
return res.writeHead(403).end('bad token')
}
Server check for the protected endpoint.
The attacker's request carried the wrong Origin, so it stopped at the first line. The real form, sent from the forum's own origin with the hidden token field, passed both. The server also saw the theme cookie on the cross-site post, even though it has no SameSite attribute. That needs an explanation, because Chrome treats a cookie without SameSite as Lax, and Lax cookies are not sent on a cross-site POST.
The cookie without SameSite
The explanation is a documented exception. MDN says some browsers use Lax as the default, and that when Lax is applied as a default a more permissive version is used: the cookie is also sent on POST requests if it was set no more than two minutes earlier. Chrome's SameSite FAQ calls this a temporary exception for top-level cross-site POST requests, made for single sign-on flows, and OWASP's CSRF cheat sheet describes the same window. The theme cookie had been set seconds before the attack. A second lab run tested the window directly.
text
0s POST /post-fresh: cookies [theme], Sec-Fetch-Site cross-site
0s GET /get-fresh: cookies [session_lax, theme], Sec-Fetch-Site
cross-site
131s POST /post-late: cookies [none], Sec-Fetch-Site cross-site
131s GET /get-late: cookies [session_lax, theme], Sec-Fetch-Site
cross-site
Real run in Chrome 157.0.8103.80. A forum page sets session_lax (SameSite=Lax) and theme (no SameSite), then an attacker page submits a form to the forum, now and after 130 seconds. Favicon requests are left out. Long lines are wrapped to fit.
The cookie without SameSite travelled on the fresh POST and not on the one after two minutes, so the exception was active in this Chrome version. The explicit Lax cookie never travelled on a POST, but it did travel on both top-level GET navigations, which is why a GET that changes state is open to forgery. Treat the two-minute window as a browser detail that may be removed: Chrome's FAQ calls it temporary and gives no date. The habit that does not depend on it is to set SameSite explicitly on every cookie.
Why could document.cookie not show the session cookies?
They had the HttpOnly flag, so the page's script could not read them. The run showed only theme.
Which of the three forged requests succeeded, and why?
Only the one aimed at /comment-none. That endpoint depended on a SameSite=None cookie, which Chrome sent from the other site, and it checked nothing else.
What stopped the forged post to /comment-protected?
The server compared the Origin header with its own origin and the attacker's value did not match.
Part 4 · Supply chain: lockfiles, audits and release age
Your app is mostly other people's code
A Vite and React project of a few hundred lines still installs hundreds of packages. This lab's node_modules held 214 packages after one install. Code from any of them can run on your machine during the build, and some packages run an install script during npm install itself. A supply chain attack targets that trust: a compromised maintainer account or a malicious new version reaches every project that installs it.
Three habits cover most of what a small team can do: install exactly what you reviewed, check what you installed against known advisories, and avoid versions that are brand new. Each habit maps to a command that the lab ran.
Install what you reviewed
package-lock.json records the exact version of every package, including those you never named, and an integrity hash of each tarball. npm ci is the command meant for automated environments. The npm documentation says it removes node_modules, needs an existing lockfile, never writes to the lockfile, and exits with an error if the lockfile does not match package.json. The lab changed one character of the stored hash for DOMPurify and ran npm ci.
text
npm warn tarball tarball data for dompurify@... seems to be corrupted.
Trying again.
npm warn tarball tarball data for dompurify@... seems to be corrupted.
Trying again.
npm error code EINTEGRITY
npm error sha512-B/pAlYVHQ58k... integrity checksum failed when using
sha512: wanted sha512-B/pAlYVHQ58k... but got sha512-B/pSlYVHQ58k...
Real run. The first lines of npm's error, shortened; the command exited with 1. Long lines are wrapped to fit.
npm downloaded the tarball, computed its hash, compared it with the lockfile, retried twice and then refused to install. Commit the lockfile, and use npm ci in the build pipeline so nobody's local resolution reaches production.
Check what you installed
npm audit sends a description of your dependencies to the registry and prints the known advisories. The lab used a separate project with lodash pinned to an old version, 4.17.20, so there would be something to find. The JSON report was saved with npm audit --json, and a short script summarised it.
js
import { readFileSync } from'node:fs'const report = JSON.parse(readFileSync('audit.json', 'utf8'))
const counts = report.metadata.vulnerabilities
console.log('counts:', JSON.stringify(counts))
for (const [name, v] of Object.entries(report.vulnerabilities)) {
console.log(`${name}: ${v.severity}, affected ${v.range}`)
for (const via of v.via.filter((x) => typeof x === 'object')) {
console.log(` ${via.severity} ${via.title}`)
}
}
summarise.mjs reads audit.json.
text
counts: {"info":0,"low":0,"moderate":0,"high":1,"critical":0,"total":1}
lodash: high, affected <=4.17.23
high Command Injection in lodash
moderate Regular Expression Denial of Service (ReDoS) in lodash
high lodash vulnerable to Code Injection via `_.template` imports key
names
moderate Lodash has Prototype Pollution Vulnerability in `_.unset`,
`_.omit`, and `_.pullAt` functions
Real run. Advisories change over time, so a rerun may differ. Long lines are wrapped to fit.
One package carried four advisories, and the package's severity is the highest of them. The npm documentation says the --audit-level option sets the minimum severity that makes the command exit with a non-zero code, and that it does not filter the report. The lab confirmed it: with --audit-level=high the exit code was 1, and with --audit-level=critical it was 0, while the report was the same. Plain npm audit --json also exited 1, because with no level set any advisory counts. That is how a pipeline can fail on high and above without drowning in low-severity noise.
The forum project itself reported found 0 vulnerabilities. A clean audit does not prove safety: it lists published advisories only. npm audit signatures is a separate check, and on the audit project it printed 1 package has a verified registry signature.
Avoid versions that are brand new
A version published a few minutes ago has had the least time for anyone to notice a problem with it. The npm configuration option min-release-age makes npm install only versions that have been available for more than the given number of days. The lab installed dompurify with the option off and then at 14 days.
With the option on, npm skipped the newest release and chose the newest one older than two weeks. This course's own labs use a two-week rule for that reason. The npm docs also describe ignore-scripts, which stops npm running scripts from package.json; the lab used it on the audit and lockfile experiments because those installs needed no scripts.
Reading an advisory is part of the job. Note which versions are affected, whether you call the vulnerable function, and what the fixed version is. The server components chapter made the same point about framework advisories: read the advisory and the framework's release notes, and do not infer your exposure from the lockfile alone.
What does npm ci do when a tarball's hash differs from the lockfile?
It retries, then stops with EINTEGRITY and refuses to install that tarball. In the run the exit code was 1.
Does --audit-level=critical hide high-severity advisories from the report?
No. It only changes the exit code. The run printed the same report and exited 0, while --audit-level=high exited 1.
What does min-release-age=14 change?
npm installs only versions released more than 14 days ago. The run picked 3.4.17 instead of the newer 3.5.0.
Part 5 · Core Web Vitals and performance budgets
Three numbers users feel
A forum that is slow to show its first comment, or that freezes when a neighbour taps Filter, feels broken before anyone reads a word. Core Web Vitals are three measurements that describe this from the user's side, and web.dev gives a threshold for each that counts as good.
Metric
What it measures
Good
Largest Contentful Paint (LCP)
how long until the largest content is painted
2.5 seconds or less
Interaction to Next Paint (INP)
how long the page takes to respond to taps, clicks and key presses
200 milliseconds or less
Cumulative Layout Shift (CLS)
how much visible content jumps around
0.1 or less
web.dev recommends judging each at the 75th percentile of page loads, split by mobile and desktop. INP became a stable Core Web Vital in 2024, replacing First Input Delay. Its page also marks INP above 200 and up to 500 milliseconds as needing improvement, and above 500 as poor.
Two details matter for how you read numbers. They are field metrics: they come from real visits and are judged across many of them, not from one load on your machine. And INP covers a whole interaction, from input to the next paint, so a slow click handler, a slow render or a slow paint all count.
Measuring in the browser
A performance budget is a limit you set on something measurable so that regressions fail loudly. web.dev's budgets article groups the metrics you can budget into three kinds: quantity-based metrics such as script size, milestone timings such as the load event or time to interactive, and rule-based scores such as those Lighthouse calculates. It advises focusing on asset sizes in the early phases of a project and tracking timings as soon as possible after that.
The browser reports these metrics through PerformanceObserver. MDN documents event entries, which carry the fields startTime, processingStart, processingEnd, duration and interactionId. By default only events lasting 104 ms or more are reported, and the durationThreshold option lowers that to a minimum of 16 ms. The lab page below registers three observers and exposes what they saw.
js
new PerformanceObserver((list) => {
for (const e of list.getEntries()) {
if (e.interactionId) {
window.__vitals.events.push({
type: e.name,
duration: e.duration,
delay: e.processingStart - e.startTime,
handler: e.processingEnd - e.processingStart,
})
}
}
}).observe({
type: 'event',
durationThreshold: 16,
buffered: true,
})
The event observer. The LCP and layout-shift observers follow the same shape.
The page also has two buttons. Like runs a 5 ms handler and Filter comments busy-waits for 260 ms, and 300 ms after load a banner is inserted above the intro text. Chrome 157 clicked each button once.
Real run in headless Chrome. One load, on this machine; numbers vary.
Reading the numbers
The Like click does not appear: at 5 ms it fell below the 16 ms threshold. The Filter interaction took 264 ms, almost all of it in the click handler, which is above the 200 ms line and would count as needing improvement. LCP and layout shift were comfortably inside their limits in this single load.
web.dev splits an interaction's latency into three parts: the input delay before handlers start, the processing time of the handlers, and the presentation delay until the next frame is painted. The event entry exposes all three. Here the first was under a millisecond, the second was 260 ms by design, and the third was the small remainder. A page where the first part dominates has a busy main thread, a page where the second dominates has a slow handler, and a page where the third dominates is rendering or painting too much.
Read this as a lab measurement and no more. The field metric is a percentile over real visits, and the lab saw three events on one fast machine. Five more loads of the same page, one after another, gave a feel for the spread.
text
LCP (ms): 240, 584, 408, 312, 488
layout shift: 0.0084 in four loads, none in one
Filter interaction: 264, 264, 272, 264, 264 ms, handler 260 ms each
time
Five more real loads on this machine, headless Chrome 157, one click on Filter each. Long lines are wrapped to fit.
The handler time is fixed by the page's busy loop, so the interaction barely moves. LCP ranged from 240 to 584 ms across six loads including the first, and the layout shift appeared in five of the six. A single number would have hidden that. For a real site the number to act on is the field percentile, not a lab run. The useful part is the method: when INP is bad, the event entry splits the time into input delay, handler time and the rest, which tells you which to attack first. The rendering chapter covers the tools for a slow render.
Why did the Like click not appear in the run's output?
Its duration was below the 16 ms durationThreshold that the observer was registered with.
In the run, where did the 264 ms of the Filter interaction go?
Almost all of it was the click handler, 260 ms, with under a millisecond of input delay.
Part 6 · Bundle budgets in CI
Budgets that fail the build
A timing budget needs a browser and a network. A bundle budget is cheaper: a limit on how many bytes of JavaScript the page downloads, checked from the build output on every change. The lab forum is built with Vite 8. Its configuration splits React into its own chunk, so the framework, which rarely changes, keeps the same file name between releases.
The app code is 3.73 kB. React and React DOM are 218.72 kB, or 68.24 kB compressed. DOMPurify has its own chunk because the app loads it with a dynamic import() only when a mode needs it, so it is not part of the first load. The index page references only the first and third files, with modulepreload for React.
The budget is a small JSON file next to a script. Each chunk has a limit, and the total of the chunks the page loads at start has a limit. The two limits catch different slips. A per-chunk limit notices one chunk growing, for example a heavy import landing in the app code. The total notices many small increases that no single chunk limit would flag, and it is the number closest to what a visitor downloads before the page works.
The script reads the built index.html to find which scripts load at start, reads the budget file, compresses each file with gzip from node:zlib, and compares the sizes with the budget. It exits with code 1 when anything is over.
js
let failed = falselet total = 0for (const file of readdirSync(join(dist, 'assets')).sort()) {
const size = kb(
gzipSync(readFileSync(join(dist, 'assets', file))).length,
)
const limit =
budget.chunkGzipKB[file.split('-')[0].replace('.es', '')]
const initial = atStart.includes(file)
if (initial) total += size
const over = size > limit
failed ||= over
console.log(
file,
`${size} kB`,
initial ? 'initial' : 'lazy',
`limit ${limit}`,
over ? 'OVER' : '',
)
}
const over = total > budget.initialGzipKB
failed ||= over
const line = `initial JavaScript: ${total.toFixed(2)} kB`
console.log(line, `budget ${budget.initialGzipKB}`, over ? 'OVER' : '')
process.exit(failed ? 1 : 0)
The core of check-budget.mjs, after it reads index.html and budget.json.
Real run on the build above, gzip sizes. Exit code 0.
The script's numbers differ a little from Vite's report: 67.5 against 68.24 for the React chunk. The lab did not find the reason. A compressor and its level change the answer too: the same React chunk is 67,504 bytes with Node's default gzip, 67,360 with level 9 and 58,060 with Node's default brotli. Pick one compressor, say which in the budget file or a comment, and budget against the numbers of the tool that enforces the budget. Do not mix them with another tool's report.
A regression it would catch
A common slip is turning a lazy import into a static one. The lab built a copy of the app where main.tsx imports DOMPurify at the top, so it ships in the first load.
text
index-paxwltMc.js 12.22 kB initial limit 10 OVER
react-BMPqjrqc.js 67.5 kB initial limit 70
initial JavaScript: 79.72 kB budget 75 OVER
Real run on the copy. Exit code 1.
The app chunk grew from 1.71 kB to 12.22 kB and the first load from 69.21 kB to 79.72 kB, so two checks failed. Notice that the React chunk kept its name, react-BMPqjrqc.js, because its contents did not change.
The two limits fail independently. The next run lowers only the total to 69 kB and leaves every chunk limit alone. No chunk is over, and the build still fails because of the sum.
The check: fails (the build stops and the change is looked at)
Read it as steps
The first load is 69.21 kB gzip against a 75 kB budget, and a static DOMPurify import breaks it
Set a budget from a measurement, not a guess. web.dev gives defaults for when you have nothing else: under 170 KB of compressed, minified critical-path resources and a time to interactive under 5 seconds on a 3G network, and it says budgets should differ by page type. Start slightly above today's number, then tighten it as the app improves. A budget that never fails is not doing its job, and one that fails every day gets ignored.
Why does the budget script read index.html?
To find which chunks load at the start. Only those count toward the initial JavaScript total, and the lazy DOMPurify chunk does not.
What caused the failure in the regression run?
A static import of DOMPurify moved its code into the app chunk, which grew to 12.22 kB and pushed the first load to 79.72 kB, over the 75 kB budget.
Why does the React chunk keep the same file name in both builds?
Its contents did not change, and the file name changed only for the app chunk, whose contents did.
Part 7 · Delivery: environment, caching, flags, errors and rollbacks
Build-time variables are public
A Vite build replaces import.meta.env values with their literal text. The Vite documentation says variables prefixed with VITE_ are exposed in the client-side source after bundling, that other variables are not, and that VITE_ variables must not hold secrets. The lab built a tiny page that reads one of each.
text
VITE_API_URL=https://api.example.com DB_PASSWORD=hunter2 vite build
Build command. Both variables are set in the shell.
text
https://api.example.com found in 1 file
hunter2 found in 0 files
grep over the built JavaScript.
The prefixed value is in the bundle, readable by anyone who opens the file. The other variable was never copied in: the bundle holds no trace of it. The practical rule is that anything the browser needs is public by definition, and anything secret belongs on a server that the app calls.
Caching hashed files
Vite puts a hash of the content in each asset's file name. MDN calls this cache busting: a file's URL changes when the file changes, so you can tell caches to keep it for a very long time, and add immutable to avoid revalidation. The page you load first, index.html, is the one that points to the current names, so it must not be cached for long. MDN's example for a hashed file is Cache-Control: public, max-age=31536000, immutable. The page that names the files cannot be cached that hard, so the lab server sent no-cache for index.html and the one-year header for the assets.
Real run against the lab server. Long lines are wrapped to fit.
no-cache does not mean do not cache: MDN says it lets caches store the response but requires them to revalidate it before reuse. The lab then built a second release with one extra seeded comment and compared the files.
Only the app chunk got a new name. A returning visitor downloads one small file and reuses the React and DOMPurify chunks from cache. The same fact makes rollbacks cheap: if release A's files are still on the server, pointing index.html back at them restores A without rebuilding.
Flags, errors and rollbacks
A feature flag is a value that turns a feature on or off without a new build. A flag read at build time is public and needs a rebuild to change; a flag fetched at runtime from a small JSON file or a service changes in seconds, and gives you a way to switch off a broken feature without a rollback. Keep flags few and short-lived, and delete the code path once a feature is settled.
Errors you cannot see are errors you cannot fix. React 19 gives createRoot two reporting options in addition to onRecoverableError: onCaughtError for errors an error boundary caught and onUncaughtError for errors nothing caught. The react.dev page says each is called with the error and an errorInfo object that holds the componentStack. The lab rendered a broken component twice, once inside a boundary and once with none.
text
page shows: Something went wrong.
page shows: ""
caught: broken inside a boundary | Broken <- Boundary
uncaught: broken with no boundary | Broken
Real run in jsdom. The root had both options; names come from componentStack.
The boundary kept a fallback on the page and still reported, and the uncaught error left an empty page and reported as well. Send both to your logging service with the release name, so you know which build produced an error, and your rollback decision rests on data.
A release routine for the forum then reads as a short list: build with npm ci, fail on the budget and on npm audit --audit-level=high, upload the hashed assets before the HTML, watch the error reports and the vitals, and keep the previous assets available so that going back is a change of one file.
Why is a VITE_ variable unsuitable for a secret?
Vite copies its value into the bundle. The run found the API address in the built file, readable by anyone.
Which headers did the lab give index.html and the hashed assets, and why different?
no-cache for the page and a one-year max-age with immutable for assets. The assets' names change when their contents do, and the page must always be revalidated to find the current names.
What is the difference between onCaughtError and onUncaughtError?
onCaughtError runs for errors an error boundary handled, and onUncaughtError for errors no boundary caught. The run called each once.