Introduction
Page load performance has always been a critical factor in user experience and SEO rankings. The Speculation Rules API represents a fundamental shift in how browsers handle page navigations, allowing developers to predict and prepare for user journeys before they even click. This declarative browser feature lets you specify which pages users are likely to visit next, enabling browsers to prefetch or prerender those pages in the background.
For Next.js developers building performance-critical applications, understanding and implementing this API can mean the difference between instant page loads and perceptible delays. Unlike traditional resource hints like <link rel="prefetch">, which only download HTML content, speculation rules can trigger full page prerendering--essentially loading and rendering pages in invisible background tabs that activate instantly when navigated to.
The Speculation Rules API works through JSON-based configuration embedded in your pages. This configuration tells the browser which URLs to target, what loading technique to use, and how aggressively to pursue speculation. The browser then monitors user behavior--mouse movements, scrolling patterns, touch interactions--and decides when to trigger the actual prefetch or prerender based on the heuristics you've defined.
For Next.js applications specifically, this means you can now leverage browser-native prerendering without relying on framework-specific solutions or custom JavaScript implementations. The API integrates seamlessly with the browser's existing navigation infrastructure, ensuring that prerendered pages behave exactly like traditionally loaded pages.
Prefetch Mode
When a URL is prefetched, the browser downloads only the HTML document and stores it in a per-document in-memory cache. The browser does not execute JavaScript, load external resources like images or stylesheets, or render the page in any way. This lightweight approach uses minimal bandwidth while still significantly reducing Time to First Byte (TTFB) when the user actually clicks the link.
Prefetch is ideal for scenarios where you want performance improvements without the resource overhead of full prerendering. It's particularly useful for pages with significant JavaScript dependencies, pages that would trigger analytics events you don't want to fire prematurely, or situations where you need to conserve bandwidth and processing power. The trade-off is smaller performance gains compared to prerendering, but with substantially lower risk of resource waste if the user doesn't navigate to the prefetched page.
The prefetched content is stored in a per-document in-memory cache that persists only while the referring page remains open. Navigation to a prefetched page consumes this cache; navigating away from the current page discards any unused prefetched content.
Prerender Mode
Prerendering goes far beyond prefetching by fully loading and rendering the target page in an invisible background tab. This includes downloading all subresources--images, stylesheets, scripts--executing JavaScript, and performing any data fetches initiated by scripts. When the user navigates to a prerendered page, the browser activates the prerendered tab instead of performing a traditional navigation, resulting in near-instant page display.
The performance benefits of prerendering can be dramatic. Shopify's implementation achieved average improvements of 130ms on desktop and 180ms on mobile across all loading metrics including Largest Contentful Paint (LCP) and First Contentful Paint (FCP). For user experience, this often translates to pages feeling instant--users see content immediately upon navigation, with no perceptible loading period.
However, prerendering carries significant resource implications. Prerendering a page consumes roughly the same resources as rendering an iframe. If users don't navigate to prerendered pages, these resources are wasted. Prerendering is best reserved for high-confidence navigation predictions such as prerendering the next article in a blog series, preparing product detail pages when users view product listings, or prerendering checkout pages when users add items to their cart.
Script-Based Implementation
The most common implementation method uses inline <script> elements with the speculationrules type. This approach embeds your speculation rules directly in the page's HTML, making them immediately available when the page loads. The script contains a JSON object that defines your speculation configuration.
This method is straightforward to implement and works reliably across all scenarios. However, if you need to dynamically update your speculation rules based on user behavior or other runtime conditions, you'll need to use JavaScript to manipulate the rules after page load. The browser will process any changes to speculation rule scripts and update its speculation behavior accordingly.
For Content Security Policy (CSP) environments, you may need to allow inline speculation rules by adding 'inline-speculation-rules' to your script-src directive, or by using a nonce or hash source for the script.
1<script type="speculationrules">2{3 "prefetch": [4 {5 "where": {6 "href_matches": ["/products/**", "/blog/**"]7 },8 "eagerness": "moderate"9 }10 ]11}12</script>URL List Rules
For more targeted speculation, you can specify exact URLs using the urls property. This approach gives you precise control over which pages get speculatively loaded, making it ideal for specific high-priority pages like checkout flows or popular product pages. URL list rules are straightforward to implement and provide predictable behavior, but they require you to explicitly enumerate every URL you want to target.
Document rules, on the other hand, use the where property with conditions like href_matches for URL pattern matching and selector_matches for CSS selector matching. This allows you to target categories of URLs without listing each one individually.
1<script type="speculationrules">2{3 "prerender": [4 {5 "urls": [6 "/products/best-selling-item",7 "/checkout",8 "/thank-you"9 ],10 "eagerness": "eager"11 }12 ]13}14</script>HTTP Header Implementation
Alternatively, speculation rules can be delivered through the Speculation-Rules HTTP header. This method keeps your HTML documents clean and separates configuration from content. It's particularly useful for caching strategies since the header can be cached independently or configured at the CDN level.
The referenced JSON file must be served with the application/speculationrules+json MIME type and contain valid speculation rules JSON. This method is particularly useful for platform-level implementations where you want to apply the same rules across many pages without modifying each page's HTML.
Shopify implemented their platform-wide speculation rules using this approach, setting the header on all storefront pages to point to a centralized rules file. This allows them to update speculation behavior for all stores by modifying a single configuration file.
1Speculation-Rules: [{"prefetch": [{"where": {"href_matches": ["/api/**"]}, "eagerness": "conservative"}]}]The eagerness setting controls how aggressively the browser pursues speculation based on user behavior signals. This is one of the most important configuration options, as it directly impacts the trade-off between performance benefits and resource usage. Choosing the right eagerness level is crucial for balancing performance gains with resource consumption.
Shopify's platform-wide implementation uses conservative eagerness, triggering prefetch on mousedown/touchdown events to maximize the benefit while minimizing wasted resources. For many Next.js applications, moderate or conservative eagerness provides the best balance of performance and efficiency.
Immediate
Speculation begins as soon as the rule is parsed. Use sparingly for critical landing pages where user navigation is certain.
Eager
Triggers when links enter viewport or cursor moves toward links. Good for visible navigation with clear user intent.
Moderate
Triggers on hover, approximately 200ms before click. Best balance of performance and resource usage.
Conservative
Only speculates on click (mousedown/touchdown). Minimal resource usage but still provides measurable benefits.
Next.js has built-in prefetching for <Link> components, which makes it an excellent complement to the Speculation Rules API. While Next.js prefetches JSON data for linked pages, the Speculation Rules API can prefetch or prerender entire HTML documents, creating a powerful combination. This browser-native approach works alongside Next.js performance optimizations to deliver near-instant navigation experiences.
For optimal results, consider using speculation rules to prefetch pages that Next.js doesn't prefetch by default, such as pages loaded via client-side navigation or dynamically generated routes. Implementation in Next.js is straightforward--simply add the speculationrules script to your root layout or individual page layouts. For App Router applications, add the script to your root layout component.
The Speculation Rules API operates at the browser level, independent of Next.js's own prefetching mechanisms, which means you can use both approaches together for maximum performance benefit. However, be mindful of potential redundancy--if you're already aggressively prefetching pages with Next.js's <Link prefetch> behavior, you might choose a less aggressive speculation strategy to avoid duplicate work.
1// app/layout.tsx2import type { Metadata } from 'next'3 4export const metadata: Metadata = {5 title: 'My Next.js App',6 description: 'Optimized with Speculation Rules API',7}8 9export default function RootLayout({10 children,11}: {12 children: React.ReactNode13}) {14 return (15 <html lang="en">16 <head>17 <script18 type="speculationrules"19 dangerouslySetInnerHTML={{20 __html: JSON.stringify({21 prerender: [22 {23 where: {24 href_matches: ['/products/**', '/checkout']25 },26 eagerness: 'eager'27 }28 ]29 })30 }}31 />32 </head>33 <body>{children}</body>34 </html>35 )36}Do
- Use moderate eagerness for broad rule sets to balance performance and resource usage
- Prerender only high-traffic, stable pages where navigation is highly likely
- Combine with real user monitoring (RUM) to measure actual performance impact
- Clear speculation cache when deploying content updates using
Clear-Site-Dataheader - Test with Chrome DevTools Performance panel to verify speculation behavior
Strategic page targeting requires understanding your user's typical navigation patterns. For Next.js applications, common high-value speculation targets include product or listing pages that users frequently navigate to from category pages.
Don't
- Prerender authenticated or personalized pages, which can expose private content
- Use immediate eagerness for large rule sets that could waste significant resources
- Speculate on external links where you can't control the destination content
- Ignore Clear-Site-Data header when deploying content updates
- Overlook viewport rules for mobile users with different navigation patterns
Pages that should generally be excluded from speculation include authentication pages, pages with form submissions, real-time or frequently changing content, and pages that trigger side effects on load.
Near-Instant Navigation
Prerendered pages load in under 100ms, creating app-like fluidity that users expect from modern web applications.
Browser-Native
No external libraries required. Built-in browser intelligence handles resource management efficiently.
Progressive Enhancement
Gracefully degrades in unsupported browsers without causing JavaScript errors.
Standards-Based
Official web standard with [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/Speculation_Rules_API) and broad Chromium support.
The Speculation Rules API is currently supported in Chromium-based browsers including Chrome, Edge, and Opera. Firefox and Safari have announced implementations but may not yet have full support.
For production deployments, implement feature detection and provide graceful degradation for unsupported browsers. The good news is that speculation rules are designed as a progressive enhancement--when not supported, browsers simply ignore them and users navigate normally. This means you can implement speculation rules without providing explicit fallbacks for older browsers.
When measuring the impact of speculation rules, filter your analysis to include only supported browsers. Shopify's measurements specifically analyzed same-site navigations using Chromium-based browsers to ensure accurate results.
Sources
- MDN Web Docs - Speculation Rules API - Official browser API documentation with comprehensive technical details
- Chrome Developer Docs - Implementing Speculation Rules - Google's official implementation guide with best practices
- Shopify Performance Blog - Speculation Rules at Shopify - Production implementation with measurable results showing 130-180ms improvements
- Telerik Blog - Boost Speed with Speculation Rules API - Practical code examples and real-world demonstrations