Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/curvy-lions-prefetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@opennextjs/cloudflare": patch
---

fix: serve cached segment prefetches when Next.js prefetch inlining is enabled

Prevent Next.js 16.3 clients from repeatedly requesting the route tree when cache interception is enabled.
5 changes: 5 additions & 0 deletions examples/playground16/app/prefetch/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import Link from "next/link";

export default function PrefetchPage() {
return <Link href="/prefetch/target">Target</Link>;
}
3 changes: 3 additions & 0 deletions examples/playground16/app/prefetch/target/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function PrefetchTargetPage() {
return <p>Target page</p>;
}
43 changes: 43 additions & 0 deletions examples/playground16/e2e/prefetch.cloudflare.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { expect, test } from "@playwright/test";

test("cache interception serves segment prefetches without retrying indefinitely", async ({ page }) => {
const segmentPrefetches: string[] = [];
page.on("request", (request) => {
if (new URL(request.url()).pathname !== "/prefetch/target") {
return;
}

const segment = request.headers()["next-router-segment-prefetch"];
if (segment) {
segmentPrefetches.push(segment);
}
});

const routeTreeResponsePromise = page.waitForResponse((response) => {
const request = response.request();
return (
new URL(request.url()).pathname === "/prefetch/target" &&
request.headers()["next-router-segment-prefetch"] === "/_tree"
);
});

await page.goto("/prefetch");

const routeTreeResponse = await routeTreeResponsePromise;
expect(routeTreeResponse.status()).toBe(200);
expect(routeTreeResponse.headers()).toMatchObject({
"content-type": "text/x-component",
"x-nextjs-postponed": "2",
"x-nextjs-prerender": "1",
"x-opennext-cache": "HIT",
});

await expect.poll(() => segmentPrefetches.some((segment) => segment.endsWith("/__PAGE__"))).toBe(true);
await page.waitForLoadState("networkidle");

const settledPrefetchCount = segmentPrefetches.length;
await page.waitForTimeout(1_000);

expect(segmentPrefetches).toHaveLength(settledPrefetchCount);
expect(settledPrefetchCount).toBeLessThan(10);
});
1 change: 1 addition & 0 deletions examples/playground16/open-next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import d1NextTagCache from "@opennextjs/cloudflare/overrides/tag-cache/d1-next-t

export default {
...defineCloudflareConfig({
enableCacheInterception: true,
incrementalCache: r2IncrementalCache,
queue: doQueue,
tagCache: d1NextTagCache,
Expand Down
2 changes: 1 addition & 1 deletion examples/playground16/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"cf-typegen": "wrangler types --env-interface CloudflareEnv"
},
"dependencies": {
"next": "16.2.11",
"next": "16.3.1",
"react-dom": "^19.2.6",
"react": "^19.2.6",
"shiki": "^3.22.0"
Expand Down
4 changes: 4 additions & 0 deletions packages/cloudflare/src/cli/build/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { compileInit } from "./open-next/compile-init.js";
import { compileSkewProtection } from "./open-next/compile-skew-protection.js";
import { compileDurableObjects } from "./open-next/compileDurableObjects.js";
import { createServerBundle } from "./open-next/createServerBundle.js";
import { patchCacheInterceptor } from "./patches/ast/cache-interceptor.js";
import { useNodeMiddleware } from "./utils/middleware.js";
import { getVersion } from "./utils/version.js";

Expand Down Expand Up @@ -100,6 +101,9 @@ export async function build(

// Compile middleware
await createMiddleware(options, { forceOnlyBuildOnce: true });
if (config.dangerous?.enableCacheInterception === true) {
patchCacheInterceptor(options);
}

createStaticAssets(options, { useBasePath: true });

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { readFileSync } from "node:fs";

import mockFs from "mock-fs";
import { afterEach, describe, expect, test } from "vitest";

import { patchCacheInterceptor, patchCacheInterceptorSource } from "./cache-interceptor.js";

const cacheInterceptorSource = `
function getBodyForAppRouter(event, cachedValue) {
const segmentHeader = \`\${event.headers[NEXT_SEGMENT_PREFETCH_HEADER]}\`;
const isSegmentResponse =
Boolean(segmentHeader) &&
segmentHeader in (cachedValue.segmentData || {}) &&
!NextConfig.experimental?.prefetchInlining;
const body = isSegmentResponse
? cachedValue.segmentData[segmentHeader]
: cachedValue.rsc;
return { body };
}
`;

describe("patchCacheInterceptor", () => {
afterEach(() => mockFs.restore());

test("patches the generated middleware", () => {
const outputDir = "/app/.open-next";
const middlewarePath = `${outputDir}/middleware/handler.mjs`;
mockFs({ [middlewarePath]: cacheInterceptorSource });

patchCacheInterceptor({ outputDir });

expect(readFileSync(middlewarePath, "utf8")).not.toContain("!NextConfig.experimental?.prefetchInlining");
});

test("serves cached segment data when prefetch inlining is enabled", () => {
const patchedSource = patchCacheInterceptorSource(cacheInterceptorSource);

expect(patchedSource).toContain(
"Boolean(segmentHeader) && segmentHeader in (cachedValue.segmentData || {})"
);
expect(patchedSource).not.toContain("!NextConfig.experimental?.prefetchInlining");
});

test("fails when the upstream cache interceptor no longer matches", () => {
expect(() => patchCacheInterceptorSource("const isSegmentResponse = false;")).toThrow(
"Failed to patch the OpenNext cache interceptor"
);
});
});
29 changes: 29 additions & 0 deletions packages/cloudflare/src/cli/build/patches/ast/cache-interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { readFileSync, writeFileSync } from "node:fs";
import path from "node:path";

import type { BuildOptions } from "@opennextjs/aws/build/helper.js";
import { patchCode } from "@opennextjs/aws/build/patch/astCodePatcher.js";

const segmentPrefetchRule = `
rule:
pattern: Boolean($SEGMENT_HEADER) && $SEGMENT_HEADER in ($CACHED_VALUE.segmentData || {}) && !NextConfig.experimental?.prefetchInlining
fix: Boolean($SEGMENT_HEADER) && $SEGMENT_HEADER in ($CACHED_VALUE.segmentData || {})
`;

export function patchCacheInterceptorSource(source: string): string {
const patchedSource = patchCode(source, segmentPrefetchRule);
if (patchedSource === source) {
throw new Error("Failed to patch the OpenNext cache interceptor");
}
return patchedSource;
}

/**
* OpenNext AWS 4.1.0 treats prefetch inlining as if it eliminates segment responses, but Next.js
* still requests cached route-tree and bundle segments. A full RSC response makes Next.js retry indefinitely.
*/
export function patchCacheInterceptor(buildOpts: Pick<BuildOptions, "outputDir">): void {
const middlewarePath = path.join(buildOpts.outputDir, "middleware/handler.mjs");
const source = readFileSync(middlewarePath, "utf8");
writeFileSync(middlewarePath, patchCacheInterceptorSource(source));
}
Loading