diff --git a/.changeset/yellow-cougars-explain.md b/.changeset/yellow-cougars-explain.md new file mode 100644 index 00000000..030a2ef9 --- /dev/null +++ b/.changeset/yellow-cougars-explain.md @@ -0,0 +1,7 @@ +--- +"@opennextjs/cloudflare": minor +--- + +feat: configure kv binding name with env var + +The Workers KV binding used in the Next.js cache handler can be given a custom name with the `__OPENNEXT_KV_BINDING_NAME` environment variable at build-time, instead of defaulting to `NEXT_CACHE_WORKERS_KV`. diff --git a/packages/cloudflare/src/cli/build/patches/investigated/patch-cache.ts b/packages/cloudflare/src/cli/build/patches/investigated/patch-cache.ts index 1f5145d9..daba3704 100644 --- a/packages/cloudflare/src/cli/build/patches/investigated/patch-cache.ts +++ b/packages/cloudflare/src/cli/build/patches/investigated/patch-cache.ts @@ -3,7 +3,15 @@ import { build } from "esbuild"; import { join } from "node:path"; /** - * Install the cloudflare KV cache handler + * Sets up the OpenNext cache handler in a Next.js build. + * + * The cache handler used by Next.js is normally defined in the config file as a path. At runtime, + * Next.js would then do a dynamic require on a transformed version of the path to retrieve the + * cache handler and create a new instance of it. + * + * This is problematic in workerd due to the dynamic import of the file that is not known from + * build-time. Therefore, we have to manually override the default way that the cache handler is + * instantiated with a dynamic require that uses a string literal for the path. */ export async function patchCache(code: string, config: Config): Promise { console.log("# patchCache"); diff --git a/packages/cloudflare/src/cli/config.ts b/packages/cloudflare/src/cli/config.ts index b79d356d..238a74d8 100644 --- a/packages/cloudflare/src/cli/config.ts +++ b/packages/cloudflare/src/cli/config.ts @@ -3,13 +3,6 @@ import { readdirSync, statSync } from "node:fs"; const PACKAGE_NAME = "@opennextjs/cloudflare"; -// Make this user configurable -const UserConfig = { - cache: { - bindingName: "NEXT_CACHE_WORKERS_KV", - }, -}; - export type Config = { // Timestamp for when the build was started buildTimestamp: number; @@ -63,6 +56,8 @@ export function getConfig(appDir: string, outputDir: string): Config { const internalPackage = path.join(nodeModules, ...PACKAGE_NAME.split("/")); const internalTemplates = path.join(internalPackage, "cli", "templates"); + process.env.__OPENNEXT_KV_BINDING_NAME ??= "NEXT_CACHE_WORKERS_KV"; + return { buildTimestamp: Date.now(), @@ -79,7 +74,7 @@ export function getConfig(appDir: string, outputDir: string): Config { }, cache: { - kvBindingName: UserConfig.cache.bindingName, + kvBindingName: process.env.__OPENNEXT_KV_BINDING_NAME, }, internalPackageName: PACKAGE_NAME,