Skip to content

Commit 87f4fb5

Browse files
authored
feat: configure kv binding name with env var (#83)
1 parent 8d18ca4 commit 87f4fb5

File tree

3 files changed

+19
-9
lines changed

3 files changed

+19
-9
lines changed

.changeset/yellow-cougars-explain.md

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"@opennextjs/cloudflare": minor
3+
---
4+
5+
feat: configure kv binding name with env var
6+
7+
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`.

packages/cloudflare/src/cli/build/patches/investigated/patch-cache.ts

+9-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,15 @@ import { build } from "esbuild";
33
import { join } from "node:path";
44

55
/**
6-
* Install the cloudflare KV cache handler
6+
* Sets up the OpenNext cache handler in a Next.js build.
7+
*
8+
* The cache handler used by Next.js is normally defined in the config file as a path. At runtime,
9+
* Next.js would then do a dynamic require on a transformed version of the path to retrieve the
10+
* cache handler and create a new instance of it.
11+
*
12+
* This is problematic in workerd due to the dynamic import of the file that is not known from
13+
* build-time. Therefore, we have to manually override the default way that the cache handler is
14+
* instantiated with a dynamic require that uses a string literal for the path.
715
*/
816
export async function patchCache(code: string, config: Config): Promise<string> {
917
console.log("# patchCache");

packages/cloudflare/src/cli/config.ts

+3-8
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,6 @@ import { readdirSync, statSync } from "node:fs";
33

44
const PACKAGE_NAME = "@opennextjs/cloudflare";
55

6-
// Make this user configurable
7-
const UserConfig = {
8-
cache: {
9-
bindingName: "NEXT_CACHE_WORKERS_KV",
10-
},
11-
};
12-
136
export type Config = {
147
// Timestamp for when the build was started
158
buildTimestamp: number;
@@ -63,6 +56,8 @@ export function getConfig(appDir: string, outputDir: string): Config {
6356
const internalPackage = path.join(nodeModules, ...PACKAGE_NAME.split("/"));
6457
const internalTemplates = path.join(internalPackage, "cli", "templates");
6558

59+
process.env.__OPENNEXT_KV_BINDING_NAME ??= "NEXT_CACHE_WORKERS_KV";
60+
6661
return {
6762
buildTimestamp: Date.now(),
6863

@@ -79,7 +74,7 @@ export function getConfig(appDir: string, outputDir: string): Config {
7974
},
8075

8176
cache: {
82-
kvBindingName: UserConfig.cache.bindingName,
77+
kvBindingName: process.env.__OPENNEXT_KV_BINDING_NAME,
8378
},
8479

8580
internalPackageName: PACKAGE_NAME,

0 commit comments

Comments
 (0)