Skip to content

Commit

Permalink
feat: configure kv binding name with env var (#83)
Browse files Browse the repository at this point in the history
  • Loading branch information
james-elicx authored Oct 10, 2024
1 parent 8d18ca4 commit 87f4fb5
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 9 deletions.
7 changes: 7 additions & 0 deletions .changeset/yellow-cougars-explain.md
Original file line number Diff line number Diff line change
@@ -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`.
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> {
console.log("# patchCache");
Expand Down
11 changes: 3 additions & 8 deletions packages/cloudflare/src/cli/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(),

Expand All @@ -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,
Expand Down

0 comments on commit 87f4fb5

Please sign in to comment.