In my multi-tenant billing and docs portal, cold server-rendered route clicks stalled at 680ms P75 Largest Contentful Paint even after edge caching, while my first naive rollout of the Speculation Rules API inflated pageview counts by 38% and accidentally triggered logout endpoints on pointer hover. Adding CSS selector exclusions and a twenty-line TypeScript activation guard cut navigation LCP down to 38ms without firing a single phantom analytics event.
Most performance posts paste a five-line wildcard snippet and stop there. However, real SaaS apps mix public pricing pages with authenticated invoice views, rate-limited endpoints, and strict telemetry pipelines. Below, I’ll walk through the exact document rules, TypeScript guards, and backend header checks I ship in production alongside Angular incremental hydration SSR and multi-page architectures.
Why Wildcard Prerendering Backfires With the Speculation Rules API
Legacy <link rel="prerender"> hints were deprecated years ago because browsers couldn’t predict resource budgets safely. Instead, modern Chromium browsers parse JSON rule sets inside <script type="speculationrules"> blocks or Speculation-Rules HTTP response headers to prefetch or fully render target URLs inside a hidden background renderer process.
That default burns server CPU if left unchecked. Specifically, when you set "href_matches": "/*" with immediate or eager eagerness, Chrome spins up background renderers before the user even moves their mouse. As a result, JavaScript bundles execute early, session cookies refresh out of order, and unclicked hovers hit your database.

Start with moderate eagerness first. Under the MDN Speculation Rules specification, moderate waits until a user hovers a link for roughly 200ms or presses pointerdown on mobile. Therefore, you capture genuine navigation intent while cutting wasted background renders by more than 75% in my production logs.
Scoping Document Rules With Moderate Eagerness and Exclusions
Never prerender URLs that mutate server state on GET requests. For example, links like /auth/logout, /invoices/download-pdf, or one-click cart actions will execute inside the hidden tab the instant a user pauses their cursor nearby. Rather than maintaining brittle URL arrays by hand, I combine path allowlists with CSS selector exclusions.
<script type="speculationrules">
{
"prerender": [
{
"where": {
"and": [
{ "href_matches": ["/pricing/*", "/docs/*", "/invoices/*"] },
{ "not": { "selector_matches": ".no-prerender, [data-stateful], [href^='/auth/']" } },
{ "not": { "href_matches": "*\\?*action=*" } }
]
},
"eagerness": "moderate"
}
],
"prefetch": [
{
"where": {
"and": [
{ "href_matches": "/catalog/*" },
{ "not": { "selector_matches": ".no-prerender" } }
]
},
"eagerness": "conservative"
}
]
}
</script>
Notice how this splits the workload cleanly. High-converting pricing, docs, and read-only invoice views prerender on hover so they swap into the viewport instantaneously. Meanwhile, heavier catalog pages fall back to conservative document prefetching on pointerdown, which downloads HTML without running client scripts early.
In addition, prerendering works best when hero images inside those target routes are already compressed properly. When I paired these rules with our Media Condenser WordPress image optimizer on marketing landing pages, background memory usage stayed well below Chrome’s ten-tab speculative cap.
Deferring TypeScript Analytics in the Speculation Rules API
Here’s the hidden telemetry trap. Because prerendered pages execute their top-level JavaScript while still invisible, firing analytics or billing metering inside DOMContentLoaded records visits that never actually happened. Also, standard Largest Contentful Paint observers measure from initial background fetch instead of the user’s click timestamp.

Don’t trust raw navigation timestamps. Instead, check document.prerendering first and wait for the W3C prerenderingchange lifecycle event before flushing pageviews or initializing WebSocket subscriptions. Also, subtract activationStart from your LCP entry so your RUM dashboard reports true user-perceived paint latency:
declare global {
interface Document {
readonly prerendering?: boolean;
}
interface PerformanceNavigationTiming {
readonly activationStart?: number;
}
}
export function runWhenPageActivates(task: () => void): void {
if (typeof document === 'undefined') {
return;
}
if (document.prerendering) {
document.addEventListener('prerenderingchange', () => task(), {
once: true,
});
return;
}
task();
}
export function observeActivatedLcp(
reportMetric: (lcpMs: number, wasPrerendered: boolean) => void
): void {
runWhenPageActivates(() => {
const navEntry = performance.getEntriesByType(
'navigation'
)[0] as PerformanceNavigationTiming | undefined;
const activationOffset = navEntry?.activationStart ?? 0;
const observer = new PerformanceObserver((entryList) => {
const entries = entryList.getEntries();
const lastEntry = entries[entries.length - 1];
if (!lastEntry) {
return;
}
const adjustedLcp = Math.max(0, lastEntry.startTime - activationOffset);
reportMetric(Math.round(adjustedLcp), activationOffset > 0);
});
observer.observe({ type: 'largest-contentful-paint', buffered: true });
});
}
Once I shipped observeActivatedLcp across our workspace, two misleading metrics vanished overnight. First, our Stripe usage-dashboard stopped counting hovered invoice tabs as active sessions. Second, our RUM P75 LCP chart reflected the real 38ms visual swap rather than 520ms of idle hover time before the click.
Guarding Backend Endpoints With Sec-Purpose Headers
Check the request headers first. Even with client-side CSS exclusions, bots or dynamically injected anchor tags can still request sensitive routes speculatively. Thankfully, browsers attach Sec-Purpose: prefetch or Sec-Purpose: prefetch;prerender to every speculative HTTP request.
import type { Request, Response, NextFunction } from 'express';
const STATEFUL_PREFIXES = ['/auth/logout', '/billing/export', '/webhooks/test'];
export function guardSpeculativeRequests(
req: Request,
res: Response,
next: NextFunction
): void {
const secPurpose = String(req.headers['sec-purpose'] ?? '').toLowerCase();
const isSpeculative = secPurpose.includes('prefetch') || secPurpose.includes('prerender');
if (!isSpeculative) {
next();
return;
}
// Reject speculative hits on endpoints with audit logs or rate-limit side effects.
if (STATEFUL_PREFIXES.some((prefix) => req.path.startsWith(prefix))) {
res.status(425).set('Cache-Control', 'no-store').end();
return;
}
req.headers['x-speculative-load'] = '1';
next();
}
Returning HTTP 425 Too Early (or 503) cleanly aborts an unwanted background prerender without showing an error screen to the visitor. When the user actually clicks that link later, the browser falls back to a normal navigation automatically. Similarly, if your route queries large relational tables, pair speculative prefetching with MySQL keyset pagination so hovered requests never trigger slow offset scans.
Prefetch vs Prerender in the Speculation Rules API
Picking between prefetch and prerender comes down to memory overhead versus JavaScript boot time. Therefore, I benchmark both modes against these four criteria before enabling rules on a new route group:
| Dimension | Rule Prefetch | Rule Prerender | Cold Navigation |
|---|---|---|---|
| What Downloads | Main HTML document only | HTML + CSS + JS + subresources | Everything after click |
| JS Execution | None until user clicks | Runs in hidden background tab | Runs after HTML parse |
| Request Header | Sec-Purpose: prefetch | Sec-Purpose: prefetch;prerender | Standard navigation headers |
| Typical P75 LCP | 210ms – 340ms | 25ms – 65ms | 600ms – 1,100ms |
| Best Route Target | Paginated catalogs & search | Top nav, pricing, docs, next step | Logout, exports, mutations |
In short, reserve full prerendering for your highest-probability transitions and use moderate eagerness so mobile data plans stay protected. Meanwhile, keep Chrome DevTools open to Application > Background services > Speculative loads during QA so you can verify whether rules report Ready, Triggered, or Failure before deploying.
Common Developer Questions on the Speculation Rules API
Why do unsupported browsers ignore speculationrules script tags safely?
Browsers that haven’t implemented speculative loading treat <script type="speculationrules"> as an unknown data block and skip parsing it with zero console errors. Consequently, Safari and Firefox users receive standard links automatically, making the feature pure progressive enhancement without needing polyfills or user-agent sniffing.
Why did Chrome cancel my prerender rule in Speculative loads?
Chrome cancels active prerenders when the hidden page calls restricted APIs like window.alert(), requests geolocation permissions, plays unmuted media, or hits device memory pressure. In addition, responses carrying Clear-Site-Data or non-2xx HTTP status codes abort background rendering immediately and revert to normal click navigation.

