demo · v138
CDN-rewrite at the Service Worker
Before 138, speculation-rule prefetches bypassed the Service Worker entirely — so SW-routed sites lost the prefetch optimisation, and any CDN-routing or auth-injection logic broke for speculative requests. 138 routes them through the SW so it can do exactly the same rewriting it does for real navigations.
Behind a flag in some channels. Enable
chrome://flags/#service-worker-speculation-rules-prefetch. The demo simulates the SW behaviour so the pipeline still illustrates without registering one.
speculation rule
awaiting prefetch…
→
Service Worker fetch handler
no event
→
actual outbound request
none
the SW handler
// In 138, prefetches from speculation rules generate a fetch event in the SW
// with request.mode === "navigate" and a Sec-Purpose: prefetch header.
self.addEventListener("fetch", (event) => {
const req = event.request;
const sp = req.headers.get("Sec-Purpose") || "";
// Auth header injection (couldn't do this for prefetch pre-138)
let r = req;
if (req.url.startsWith(self.location.origin + "/account/")) {
r = new Request(req, { headers: { ...req.headers, Authorization: "Bearer " + (await getToken()) } });
}
// CDN rewrite — route /products/* via the regional edge
const u = new URL(r.url);
if (u.pathname.startsWith("/products/")) {
u.host = "edge-eu.example.com";
r = new Request(u.toString(), r);
}
// Skip server-side analytics for speculative requests; log a counter instead
if (sp.includes("prefetch")) counter.add({ name: "speculative_prefetch" });
event.respondWith(fetch(r));
});