|
| 1 | +declare global { |
| 2 | + interface CloudflareEnv { |
| 3 | + NEXT_CACHE_WORKERS_KV?: KVNamespace; |
| 4 | + ASSETS?: Fetcher; |
| 5 | + } |
| 6 | +} |
| 7 | + |
| 8 | +export type CloudflareContext< |
| 9 | + CfProperties extends Record<string, unknown> = IncomingRequestCfProperties, |
| 10 | + Context = ExecutionContext, |
| 11 | +> = { |
| 12 | + /** |
| 13 | + * the worker's [bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/) |
| 14 | + */ |
| 15 | + env: CloudflareEnv; |
| 16 | + /** |
| 17 | + * the request's [cf properties](https://developers.cloudflare.com/workers/runtime-apis/request/#the-cf-property-requestinitcfproperties) |
| 18 | + */ |
| 19 | + cf: CfProperties | undefined; |
| 20 | + /** |
| 21 | + * the current [execution context](https://developers.cloudflare.com/workers/runtime-apis/context) |
| 22 | + */ |
| 23 | + ctx: Context; |
| 24 | +}; |
| 25 | + |
| 26 | +// Note: this symbol needs to be kept in sync with the one used in `src/cli/templates/worker.ts` |
| 27 | +const cloudflareContextSymbol = Symbol.for("__cloudflare-context__"); |
| 28 | + |
| 29 | +/** |
| 30 | + * Utility to get the current Cloudflare context |
| 31 | + * |
| 32 | + * @returns the cloudflare context |
| 33 | + */ |
| 34 | +export async function getCloudflareContext< |
| 35 | + CfProperties extends Record<string, unknown> = IncomingRequestCfProperties, |
| 36 | + Context = ExecutionContext, |
| 37 | +>(): Promise<CloudflareContext<CfProperties, Context>> { |
| 38 | + const global = globalThis as unknown as { |
| 39 | + [cloudflareContextSymbol]: CloudflareContext<CfProperties, Context> | undefined; |
| 40 | + }; |
| 41 | + |
| 42 | + const cloudflareContext = global[cloudflareContextSymbol]; |
| 43 | + |
| 44 | + if (!cloudflareContext) { |
| 45 | + // the cloudflare context is initialized by the worker and is always present in production/preview, |
| 46 | + // so, it not being present means that the application is running under `next dev` |
| 47 | + return getCloudflareContextInNextDev(); |
| 48 | + } |
| 49 | + |
| 50 | + return cloudflareContext; |
| 51 | +} |
| 52 | + |
| 53 | +const cloudflareContextInNextDevSymbol = Symbol.for("__next-dev/cloudflare-context__"); |
| 54 | + |
| 55 | +/** |
| 56 | + * Gets a local proxy version of the cloudflare context (created using `getPlatformProxy`) when |
| 57 | + * running in the standard next dev server (via `next dev`) |
| 58 | + * |
| 59 | + * @returns the local proxy version of the cloudflare context |
| 60 | + */ |
| 61 | +async function getCloudflareContextInNextDev< |
| 62 | + CfProperties extends Record<string, unknown> = IncomingRequestCfProperties, |
| 63 | + Context = ExecutionContext, |
| 64 | +>(): Promise<CloudflareContext<CfProperties, Context>> { |
| 65 | + const global = globalThis as unknown as { |
| 66 | + [cloudflareContextInNextDevSymbol]: CloudflareContext<CfProperties, Context> | undefined; |
| 67 | + }; |
| 68 | + |
| 69 | + if (!global[cloudflareContextInNextDevSymbol]) { |
| 70 | + try { |
| 71 | + const cloudflareContext = await getCloudflareContextFromWrangler<CfProperties, Context>(); |
| 72 | + global[cloudflareContextInNextDevSymbol] = cloudflareContext; |
| 73 | + } catch (e: unknown) { |
| 74 | + if (e instanceof Error && e.message.includes("A dynamic import callback was not specified")) { |
| 75 | + const getCloudflareContextFunctionName = getCloudflareContext.name; |
| 76 | + const enablingFunctionName = enableEdgeDevGetCloudflareContext.name; |
| 77 | + throw new Error( |
| 78 | + `\n\n\`${getCloudflareContextFunctionName}\` has been invoked during development inside the edge runtime ` + |
| 79 | + "this is not enabled, to enable such use of the function you need to import and call the " + |
| 80 | + `\`${enablingFunctionName}\` function inside your Next.js config file\n\n"` + |
| 81 | + "Example: \n ```\n // next.config.mjs\n\n" + |
| 82 | + ` import { ${enablingFunctionName} } from "@opennextjs/cloudflare";\n\n` + |
| 83 | + ` ${enablingFunctionName}();\n\n` + |
| 84 | + " /** @type {import('next').NextConfig} */\n" + |
| 85 | + " const nextConfig = {};\n" + |
| 86 | + " export default nextConfig;\n" + |
| 87 | + " ```\n" + |
| 88 | + "\n(note: currently middlewares in Next.js are always run using the edge runtime)\n\n" |
| 89 | + ); |
| 90 | + } else { |
| 91 | + throw e; |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + return global[cloudflareContextInNextDevSymbol]!; |
| 97 | +} |
| 98 | + |
| 99 | +type RuntimeContext = Record<string, unknown> & { |
| 100 | + process?: { env?: Record<string | symbol, unknown> }; |
| 101 | + [cloudflareContextInNextDevSymbol]?: { |
| 102 | + env: unknown; |
| 103 | + ctx: unknown; |
| 104 | + cf: unknown; |
| 105 | + }; |
| 106 | +}; |
| 107 | + |
| 108 | +/** |
| 109 | + * Enables `getCloudflareContext` to work, during development (via `next dev`), in the edge runtime |
| 110 | + * |
| 111 | + * Note: currently middlewares always run in the edge runtime |
| 112 | + * |
| 113 | + * Note: this function should only be called inside the Next.js config file |
| 114 | + */ |
| 115 | +export async function enableEdgeDevGetCloudflareContext() { |
| 116 | + const require = ( |
| 117 | + await import(/* webpackIgnore: true */ `${"__module".replaceAll("_", "")}`) |
| 118 | + ).default.createRequire(import.meta.url); |
| 119 | + |
| 120 | + // eslint-disable-next-line unicorn/prefer-node-protocol -- the `next dev` compiler doesn't accept the node prefix |
| 121 | + const vmModule = require("vm"); |
| 122 | + |
| 123 | + const originalRunInContext = vmModule.runInContext.bind(vmModule); |
| 124 | + |
| 125 | + const context = await getCloudflareContextFromWrangler(); |
| 126 | + |
| 127 | + vmModule.runInContext = (...args: [string, RuntimeContext, ...unknown[]]) => { |
| 128 | + const runtimeContext = args[1]; |
| 129 | + runtimeContext[cloudflareContextInNextDevSymbol] ??= context; |
| 130 | + return originalRunInContext(...args); |
| 131 | + }; |
| 132 | +} |
| 133 | + |
| 134 | +async function getCloudflareContextFromWrangler< |
| 135 | + CfProperties extends Record<string, unknown> = IncomingRequestCfProperties, |
| 136 | + Context = ExecutionContext, |
| 137 | +>(): Promise<CloudflareContext<CfProperties, Context>> { |
| 138 | + // Note: we never want wrangler to be bundled in the Next.js app, that's why the import below looks like it does |
| 139 | + const { getPlatformProxy } = await import(/* webpackIgnore: true */ `${"__wrangler".replaceAll("_", "")}`); |
| 140 | + const { env, cf, ctx } = await getPlatformProxy({ |
| 141 | + // This allows the selection of a wrangler environment while running in next dev mode |
| 142 | + environment: process.env.NEXT_DEV_WRANGLER_ENV, |
| 143 | + }); |
| 144 | + return { |
| 145 | + env, |
| 146 | + cf: cf as unknown as CfProperties, |
| 147 | + ctx: ctx as Context, |
| 148 | + }; |
| 149 | +} |
0 commit comments