Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
5 changes: 5 additions & 0 deletions .changeset/major-mails-shave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@opennextjs/cloudflare": patch
---

fix fetch inside `use cache` in ISR
41 changes: 41 additions & 0 deletions examples/e2e/experimental/e2e/use-cache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,45 @@ test.describe("Composable Cache", () => {
const fullyCachedText = await fullyCachedElt.textContent();
expect(fullyCachedText).toEqual(initialFullyCachedText);
});

test("cached fetch should work in ISR", async ({ page }) => {
await page.goto("/use-cache/fetch");

let dateElt = page.getByTestId("date");
await expect(dateElt).toBeVisible();

let initialDate = await dateElt.textContent();

let isrElt = page.getByTestId("isr");
await expect(isrElt).toBeVisible();
let initialIsrText = await isrElt.textContent();

// We have to force reload until ISR has triggered at least once, otherwise the test will be flakey

let isrText = initialIsrText;

while (isrText === initialIsrText) {
await page.reload();
isrElt = page.getByTestId("isr");
dateElt = page.getByTestId("date");
await expect(isrElt).toBeVisible();
isrText = await isrElt.textContent();
await expect(dateElt).toBeVisible();
initialDate = await dateElt.textContent();
await page.waitForTimeout(1000);
}
initialIsrText = isrText;

do {
await page.reload();
dateElt = page.getByTestId("date");
isrElt = page.getByTestId("isr");
await expect(dateElt).toBeVisible();
await expect(isrElt).toBeVisible();
isrText = await isrElt.textContent();
await page.waitForTimeout(1000);
} while (isrText === initialIsrText);
const fullyCachedText = await dateElt.textContent();
expect(fullyCachedText).toEqual(initialDate);
});
});
22 changes: 22 additions & 0 deletions examples/e2e/experimental/src/app/use-cache/fetch/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ISRComponent } from "@/components/cached";
import { Suspense } from "react";

async function getFromFetch() {
"use cache";
// This is a simple fetch to ensure that the cache is working with IO inside
const res = await fetch("https://opennext.js.org");
return res.headers.get("Date");
}

export default async function Page() {
const date = await getFromFetch();
return (
<div>
<h1>Cache</h1>
<p data-testid="date">{date}</p>
<Suspense fallback={<p>Loading...</p>}>
<ISRComponent />
</Suspense>
</div>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import type { Plugin } from "esbuild";

import { getOpenNextConfig } from "../../../api/config.js";
import { patchResRevalidate } from "../patches/plugins/res-revalidate.js";
import { patchUseCacheIO } from "../patches/plugins/use-cache.js";
import { normalizePath } from "../utils/index.js";
import { copyWorkerdPackages } from "../utils/workerd.js";

Expand Down Expand Up @@ -216,6 +217,7 @@ async function generateBundle(
patchBackgroundRevalidation,
// Cloudflare specific patches
patchResRevalidate,
patchUseCacheIO,
...additionalCodePatches,
]);

Expand Down
159 changes: 159 additions & 0 deletions packages/cloudflare/src/cli/build/patches/plugins/use-cache.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
import { patchCode } from "@opennextjs/aws/build/patch/astCodePatcher.js";
import { expect, test } from "vitest";

import { rule } from "./use-cache.js";

const codeToPatch = `"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
bindSnapshot: null,
createAsyncLocalStorage: null,
createSnapshot: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
bindSnapshot: function() {
return bindSnapshot;
},
createAsyncLocalStorage: function() {
return createAsyncLocalStorage;
},
createSnapshot: function() {
return createSnapshot;
}
});
const sharedAsyncLocalStorageNotAvailableError = Object.defineProperty(new Error('Invariant: AsyncLocalStorage accessed in runtime where it is not available'), "__NEXT_ERROR_CODE", {
value: "E504",
enumerable: false,
configurable: true
});
class FakeAsyncLocalStorage {
disable() {
throw sharedAsyncLocalStorageNotAvailableError;
}
getStore() {
// This fake implementation of AsyncLocalStorage always returns \`undefined\`.
return undefined;
}
run() {
throw sharedAsyncLocalStorageNotAvailableError;
}
exit() {
throw sharedAsyncLocalStorageNotAvailableError;
}
enterWith() {
throw sharedAsyncLocalStorageNotAvailableError;
}
static bind(fn) {
return fn;
}
}
const maybeGlobalAsyncLocalStorage = typeof globalThis !== 'undefined' && globalThis.AsyncLocalStorage;
function createAsyncLocalStorage() {
if (maybeGlobalAsyncLocalStorage) {
return new maybeGlobalAsyncLocalStorage();
}
return new FakeAsyncLocalStorage();
}
function bindSnapshot(fn) {
if (maybeGlobalAsyncLocalStorage) {
return maybeGlobalAsyncLocalStorage.bind(fn);
}
return FakeAsyncLocalStorage.bind(fn);
}
function createSnapshot() {
if (maybeGlobalAsyncLocalStorage) {
return maybeGlobalAsyncLocalStorage.snapshot();
}
return function(fn, ...args) {
return fn(...args);
};
}

//# sourceMappingURL=async-local-storage.js.map
`;

test("patch the createSnapshot function", () => {
const patchedCode = patchCode(codeToPatch, rule);
expect(patchedCode).toMatchInlineSnapshot(`""use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
0 && (module.exports = {
bindSnapshot: null,
createAsyncLocalStorage: null,
createSnapshot: null
});
function _export(target, all) {
for(var name in all)Object.defineProperty(target, name, {
enumerable: true,
get: all[name]
});
}
_export(exports, {
bindSnapshot: function() {
return bindSnapshot;
},
createAsyncLocalStorage: function() {
return createAsyncLocalStorage;
},
createSnapshot: function() {
return createSnapshot;
}
});
const sharedAsyncLocalStorageNotAvailableError = Object.defineProperty(new Error('Invariant: AsyncLocalStorage accessed in runtime where it is not available'), "__NEXT_ERROR_CODE", {
value: "E504",
enumerable: false,
configurable: true
});
class FakeAsyncLocalStorage {
disable() {
throw sharedAsyncLocalStorageNotAvailableError;
}
getStore() {
// This fake implementation of AsyncLocalStorage always returns \`undefined\`.
return undefined;
}
run() {
throw sharedAsyncLocalStorageNotAvailableError;
}
exit() {
throw sharedAsyncLocalStorageNotAvailableError;
}
enterWith() {
throw sharedAsyncLocalStorageNotAvailableError;
}
static bind(fn) {
return fn;
}
}
const maybeGlobalAsyncLocalStorage = typeof globalThis !== 'undefined' && globalThis.AsyncLocalStorage;
function createAsyncLocalStorage() {
if (maybeGlobalAsyncLocalStorage) {
return new maybeGlobalAsyncLocalStorage();
}
return new FakeAsyncLocalStorage();
}
function bindSnapshot(fn) {
if (maybeGlobalAsyncLocalStorage) {
return maybeGlobalAsyncLocalStorage.bind(fn);
}
return FakeAsyncLocalStorage.bind(fn);
}
function createSnapshot() {
// Ignored snapshot
return function(fn, ...args) {
return fn(...args);
};
}

//# sourceMappingURL=async-local-storage.js.map
"`);
});
39 changes: 39 additions & 0 deletions packages/cloudflare/src/cli/build/patches/plugins/use-cache.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* This patch will replace the createSnapshot function in the
* server/app-render/async-local-storage.js file to an empty string.
* This is necessary because the createSnapshot function is causing I/O issues for
* ISR/SSG revalidation in Cloudflare Workers.
* TODO: Find a better fix for this issue.
*/
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please add more details from the PR discussion:

https://github.com/vercel/next.js/blob/62de494f/packages/next/src/server/app-render/async-local-storage.ts#L55-L65

This is because by default it will use AsyncLocalStorage.snapshot() and it will bind everything to the initial request context. The downsides is that use cache function will have access to the full request ALS context from next (i.e. cookies, headers ...)

import { patchCode } from "@opennextjs/aws/build/patch/astCodePatcher.js";
import type { CodePatcher } from "@opennextjs/aws/build/patch/codePatcher.js";
import { getCrossPlatformPathRegex } from "@opennextjs/aws/utils/regex.js";

export const rule = `
rule:
kind: if_statement
inside:
kind: function_declaration
stopBy: end
has:
kind: identifier
pattern: createSnapshot
fix:
'// Ignored snapshot'
`;

export const patchUseCacheIO: CodePatcher = {
name: "patch-use-cache",
patches: [
{
versions: ">=15.3.1",
field: {
pathFilter: getCrossPlatformPathRegex(String.raw`server/app-render/async-local-storage\.js$`, {
escape: false,
}),
contentFilter: /createSnapshot/,
patchCode: async ({ code }) => patchCode(code, rule),
},
},
],
};