Headline: The Speculation Rules API is a JSON block (
<script type="speculationrules">) that tells Chromium-based browsers to prefetch or fully prerender a likely next page before the user clicks. In a Next.js App Router app it only helps hard navigations — plain anchors, links into another Next.js zone, links across root layouts — because<Link>soft navigations never load a new document. I scope the rules to those links, usemoderateeagerness, exclude every URL with side effects, and delay analytics until the prerendered page is activated.
I added speculation rules to a Next.js setup expecting every navigation to get faster. Client-side navigations did not change at all, the server started rendering pages nobody opened, and only the hard navigations improved. These are my notes on where the Speculation Rules API pays off in a Next.js app, how I wire it up, and what broke.
Key takeaways
-
The Speculation Rules API is a Chrome and Edge feature that prefetches the next document or prerenders it in a hidden tab, configured with a
<script type="speculationrules">block or aSpeculation-Rulesheader. -
Next.js
<Link>prefetching and speculation rules solve different problems:<Link>speeds up client-side navigations; speculation rules speed up only full document navigations. -
Document rules must be scoped to hard-navigation links, because a catch-all
/*rule also matches every<Link>anchor and triggers server renders the client-side router throws away. -
moderateeagerness is a safe default: Chrome speculates after a 200 ms hover or on pointerdown, and keeps at most 2 such speculations at a time. -
Prerendered pages run JavaScript before the user sees them, so page-view analytics must wait until
document.prerenderingis false, and side-effecting URLs must be excluded.
What is the Speculation Rules API?
The Speculation Rules API is a web platform API that lets a page declare which URLs the browser may load before a navigation happens. It has two actions. Prefetch downloads only the HTML of the next document — no subresources and no JavaScript execution. Prerender loads and renders the entire page in an invisible background tab, including subresources and scripts, and swaps it in when the user clicks.
Rules come in two forms. List rules name exact URLs in a urls array. Document rules match links in the current page with a where condition — href_matches for URL patterns and selector_matches for CSS selectors, combined with and, or and not. The eagerness field decides when Chrome acts:
| Eagerness | When Chrome speculates | Concurrent limit |
|---|---|---|
immediate |
As soon as the rules are observed | 50 prefetches, 10 prerenders |
eager |
Desktop: about 10 ms hover (Chrome 143+); mobile: soon after the link enters the viewport | 50 prefetches, 10 prerenders |
moderate |
Desktop: 200 ms hover or pointerdown; mobile: viewport heuristics | 2, oldest evicted first |
conservative |
pointerdown or touchstart | 2, oldest evicted first |
List rules default to immediate and document rules default to conservative. Browser support is the main constraint: Chrome and Edge ship the API, Safari has it behind a flag, and Firefox does not support it. Unsupported browsers ignore the rules entirely, which makes speculation rules a progressive enhancement that needs no fallback code.
Does Next.js <Link> prefetching make speculation rules redundant?
No — Next.js <Link> prefetching and the Speculation Rules API accelerate different kinds of navigation. A <Link> click inside the same root layout is a soft navigation: the Next.js App Router fetches a React Server Component (RSC) payload and updates the page with history.pushState, so the browser never requests a new document. A prerendered document cannot help that click. Speculation rules only help when the browser performs a full document navigation.
Next.js <Link> prefetch |
Speculation rules prefetch | Speculation rules prerender | |
|---|---|---|---|
| What is fetched | RSC payload for the route segment | HTML document only | Full page, subresources and JavaScript |
| Navigation it speeds up | Client-side (soft) navigation | Full document (hard) navigation | Full document (hard) navigation |
| Browser support | All browsers | Chromium-based | Chromium-based |
| Runs page JavaScript early | No | No | Yes |
In my Next.js projects, hard navigations come from four places:
- Plain
<a href>anchors inside HTML from a CMS or a markdown renderer, which the App Router does not intercept. - Links into a different Next.js application on the same domain through multi-zones, for example a marketing app at
/and a docs app at/docs. - Links between two different root layouts, which the App Router turns into a full page load.
- Links from a static landing page into the Next.js app.
The trap is the catch-all rule. A document rule with href_matches: "/*" matches every anchor on the page, and <Link> renders a real <a> element. With moderate eagerness, each hover prerenders a full document on the server, then the client-side router performs a soft navigation and discards it — one wasted server render per hover.
How do I add speculation rules to a Next.js App Router app?
The simplest way to add speculation rules in the Next.js App Router is an inline <script type="speculationrules"> element rendered from the root layout. I keep the rules in one module and scope them to the links that actually cause hard navigations:
// lib/speculation-rules.ts
export const speculationRules = {
prerender: [
{
// /docs is a separate Next.js zone: every click there is a hard navigation
where: {
and: [
{ href_matches: '/docs/*' },
{ not: { selector_matches: '[data-no-prerender]' } },
],
},
eagerness: 'moderate',
},
],
prefetch: [
{
// plain anchors rendered from CMS HTML opt in explicitly
where: { selector_matches: 'a[data-hard-nav]' },
eagerness: 'conservative',
},
],
};
// app/speculation-rules-script.tsx
import { headers } from 'next/headers';
import { speculationRules } from '@/lib/speculation-rules';
export async function SpeculationRulesScript() {
const nonce = (await headers()).get('x-nonce') ?? undefined;
return (
<script
type="speculationrules"
nonce={nonce}
dangerouslySetInnerHTML={{ __html: JSON.stringify(speculationRules) }}
/>
);
}
A Content Security Policy (CSP) blocks inline speculation rules unless script-src allows them through a nonce, a hash of the JSON, or the 'inline-speculation-rules' keyword, which permits speculation rules JSON without permitting arbitrary inline JavaScript. The nonce above comes from the same middleware that sets the CSP header; reading headers() makes the layout dynamic, which nonce-based pages already are.
For statically rendered pages I use the Speculation-Rules HTTP response header instead. The header points to a JSON file that the browser fetches separately, so the layout never needs a per-request nonce. The JSON must be served with the application/speculationrules+json content type, or the browser ignores it:
// app/speculationrules/route.ts
import { speculationRules } from '@/lib/speculation-rules';
export const dynamic = 'force-static';
export function GET() {
return new Response(JSON.stringify(speculationRules), {
headers: { 'Content-Type': 'application/speculationrules+json' },
});
}
// next.config.ts
const nextConfig = {
async headers() {
return [
{
source: '/:path*',
headers: [{ key: 'Speculation-Rules', value: '"/speculationrules"' }],
},
];
},
};
export default nextConfig;
What breaks when the browser prerenders a page?
A prerendered page executes its JavaScript before the user decides to visit it, so anything that assumes "loaded means viewed" becomes wrong. I check four areas before I enable prerender on a project.
Side-effecting GET URLs. Logout, one-click unsubscribe, magic-link sign-in and "mark as read" URLs must never be speculated, because a prefetch or prerender is a real GET request. I exclude them with not conditions or a data-no-prerender attribute.
Analytics. A page-view event that fires on load counts prerenders the user never saw. document.prerendering is true while the page is prerendering, and the prerenderingchange event fires when the user actually navigates to it. Some analytics libraries already handle this; my own page-view helper did not:
export function whenActivated(callback: () => void) {
if (document.prerendering) {
document.addEventListener('prerenderingchange', () => callback(), {
once: true,
});
} else {
callback();
}
}
whenActivated(() => trackPageView(location.pathname));
Server-side work. Speculative requests carry a Sec-Purpose request header — prefetch for prefetches and prefetch;prerender for prerenders. I read it in middleware to tag speculative requests in logs and metrics. The client supplies that header, so I never use it to bypass rate limits or authorization.
Cross-origin links. Chrome prerenders only same-origin URLs by default; a same-site subdomain such as app.example.com must opt in with the Supports-Loading-Mode: credentialed-prerender response header. Next.js multi-zones on one domain avoid that, because every zone shares one origin.
How do I check that speculation rules are working?
Chrome DevTools shows every speculation under Application › Background services › Speculative loads: parsed rule sets, prefetched and prerendered URLs, and the failure reason for each cancelled speculation. I check that panel after every rule change, because an invalid rule set fails silently.
In real-user monitoring, activationStart in the Navigation Timing entry is greater than zero when a page was prerendered and then activated. The web-vitals library reports navigationType: 'prerender' for those navigations and measures Largest Contentful Paint (LCP) from activation:
import { onLCP } from 'web-vitals';
onLCP(({ value, navigationType }) => {
// navigationType: 'navigate' | 'reload' | 'back-forward' | 'prerender' | ...
report({ metric: 'LCP', value, navigationType });
});
Cost matters as much as speed. I compare requests carrying Sec-Purpose: prefetch;prerender with activations; a large gap means the rules are too eager or too broad, so I move from moderate to conservative or narrow href_matches before changing anything else.
FAQ
Q: Do speculation rules work in Safari and Firefox?
A: Not by default. Chrome and Edge support the Speculation Rules API, Safari has it behind a feature flag, and Firefox does not support it. Unsupported browsers ignore the speculationrules script, so adding it never breaks them.
Q: Is prerender or prefetch the safer default?
A: Prefetch is safer because it downloads only the HTML document and runs no JavaScript. Prerender makes activation faster but executes the page early, so analytics and side-effect handling must be fixed first.
Q: Can speculation rules hurt performance?
A: Yes, when the rules are too broad. Eager rules on link-heavy pages waste bandwidth, server capacity and device memory, which is why Chrome caps concurrent speculations and why I start with moderate eagerness on a narrow set of URLs.
Originally published on devya.dev. Also on eng-ahmed.com. Built by Devya Solutions.
Top comments (0)