|
| 1 | +import type { Context, RunningCodeOptions } from "node:vm"; |
| 2 | + |
| 3 | +declare global { |
| 4 | + interface CloudflareEnv { |
| 5 | + NEXT_CACHE_WORKERS_KV?: KVNamespace; |
| 6 | + ASSETS?: Fetcher; |
| 7 | + } |
| 8 | +} |
| 9 | + |
| 10 | +export type CloudflareContext< |
| 11 | + CfProperties extends Record<string, unknown> = IncomingRequestCfProperties, |
| 12 | + Context = ExecutionContext, |
| 13 | +> = { |
| 14 | + /** |
| 15 | + * the worker's [bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/) |
| 16 | + */ |
| 17 | + env: CloudflareEnv; |
| 18 | + /** |
| 19 | + * the request's [cf properties](https://developers.cloudflare.com/workers/runtime-apis/request/#the-cf-property-requestinitcfproperties) |
| 20 | + */ |
| 21 | + cf: CfProperties | undefined; |
| 22 | + /** |
| 23 | + * the current [execution context](https://developers.cloudflare.com/workers/runtime-apis/context) |
| 24 | + */ |
| 25 | + ctx: Context; |
| 26 | +}; |
| 27 | + |
| 28 | +/** |
| 29 | + * Symbol used as an index in the global scope to set and retrieve the Cloudflare context |
| 30 | + * |
| 31 | + * This is used both in production (in the actual built worker) and in development (`next dev`) |
| 32 | + * |
| 33 | + * Note: this symbol needs to be kept in sync with the one used in `src/cli/templates/worker.ts` |
| 34 | + */ |
| 35 | +const cloudflareContextSymbol = Symbol.for("__cloudflare-context__"); |
| 36 | + |
| 37 | +/** |
| 38 | + * `globalThis` override for internal usage (simply the standard `globalThis`) enhanced with |
| 39 | + * a property indexed by the `cloudflareContextSymbol` |
| 40 | + */ |
| 41 | +type InternalGlobalThis< |
| 42 | + CfProperties extends Record<string, unknown> = IncomingRequestCfProperties, |
| 43 | + Context = ExecutionContext, |
| 44 | +> = typeof globalThis & { |
| 45 | + [cloudflareContextSymbol]: CloudflareContext<CfProperties, Context> | undefined; |
| 46 | +}; |
| 47 | + |
| 48 | +/** |
| 49 | + * Utility to get the current Cloudflare context |
| 50 | + * |
| 51 | + * @returns the cloudflare context |
| 52 | + */ |
| 53 | +export function getCloudflareContext< |
| 54 | + CfProperties extends Record<string, unknown> = IncomingRequestCfProperties, |
| 55 | + Context = ExecutionContext, |
| 56 | +>(): CloudflareContext<CfProperties, Context> { |
| 57 | + const global = globalThis as InternalGlobalThis<CfProperties, Context>; |
| 58 | + |
| 59 | + const cloudflareContext = global[cloudflareContextSymbol]; |
| 60 | + |
| 61 | + if (!cloudflareContext) { |
| 62 | + // the cloudflare context is initialized by the worker and is always present in production/preview |
| 63 | + // during local development (`next dev`) it might be missing only if the developers hasn't called |
| 64 | + // the `initOpenNextCloudflareForDev` function in their Next.js config file |
| 65 | + const getContextFunctionName = getCloudflareContext.name; |
| 66 | + const initFunctionName = initOpenNextCloudflareForDev.name; |
| 67 | + throw new Error( |
| 68 | + `\n\n\`${getContextFunctionName}\` has been called during development without having called` + |
| 69 | + ` the \`${initFunctionName}\` function inside the Next.js config file.\n\n` + |
| 70 | + `In order to use \`${getContextFunctionName}\` import and call ${initFunctionName} in the Next.js config file.\n\n` + |
| 71 | + "Example: \n ```\n // next.config.mjs\n\n" + |
| 72 | + ` import { ${initFunctionName} } from "@opennextjs/cloudflare";\n\n` + |
| 73 | + ` ${initFunctionName}();\n\n` + |
| 74 | + " /** @type {import('next').NextConfig} */\n" + |
| 75 | + " const nextConfig = {};\n" + |
| 76 | + " export default nextConfig;\n" + |
| 77 | + " ```\n" + |
| 78 | + "\n(note: currently middlewares in Next.js are always run using the edge runtime)\n\n" |
| 79 | + ); |
| 80 | + } |
| 81 | + |
| 82 | + return cloudflareContext; |
| 83 | +} |
| 84 | + |
| 85 | +/** |
| 86 | + * Performs some initial setup to integrate as best as possible the local Next.js dev server (run via `next dev`) |
| 87 | + * with the open-next Cloudflare adapter |
| 88 | + * |
| 89 | + * Note: this function should only be called inside the Next.js config file, and although async it doesn't need to be `await`ed |
| 90 | + */ |
| 91 | +export async function initOpenNextCloudflareForDev() { |
| 92 | + const context = await getCloudflareContextFromWrangler(); |
| 93 | + |
| 94 | + addCloudflareContextToNodejsGlobal(context); |
| 95 | + |
| 96 | + await monkeyPatchVmModuleEdgeContext(context); |
| 97 | +} |
| 98 | + |
| 99 | +/** |
| 100 | + * Adds the cloudflare context to the global scope in which the Next.js dev node.js process runs in, enabling |
| 101 | + * future calls to `getCloudflareContext` to retrieve and return such context |
| 102 | + * |
| 103 | + * @param cloudflareContext the cloudflare context to add to the node.sj global scope |
| 104 | + */ |
| 105 | +function addCloudflareContextToNodejsGlobal(cloudflareContext: CloudflareContext<CfProperties, Context>) { |
| 106 | + const global = globalThis as InternalGlobalThis<CfProperties, Context>; |
| 107 | + global[cloudflareContextSymbol] = cloudflareContext; |
| 108 | +} |
| 109 | + |
| 110 | +/** |
| 111 | + * Next.js uses the Node.js vm module's `runInContext()` function to evaluate edge functions |
| 112 | + * in a runtime context that tries to simulate as accurately as possible the actual production runtime |
| 113 | + * behavior, see: https://github.com/vercel/next.js/blob/9a1cd3/packages/next/src/server/web/sandbox/context.ts#L525-L527 |
| 114 | + * |
| 115 | + * This function monkey-patches the Node.js `vm` module to override the `runInContext()` function so that the |
| 116 | + * cloudflare context is added to the runtime context's global scope before edge functions are evaluated |
| 117 | + * |
| 118 | + * @param cloudflareContext the cloudflare context to patch onto the "edge" runtime context global scope |
| 119 | + */ |
| 120 | +async function monkeyPatchVmModuleEdgeContext(cloudflareContext: CloudflareContext<CfProperties, Context>) { |
| 121 | + const require = ( |
| 122 | + await import(/* webpackIgnore: true */ `${"__module".replaceAll("_", "")}`) |
| 123 | + ).default.createRequire(import.meta.url); |
| 124 | + |
| 125 | + // eslint-disable-next-line unicorn/prefer-node-protocol -- the `next dev` compiler doesn't accept the node prefix |
| 126 | + const vmModule = require("vm"); |
| 127 | + |
| 128 | + const originalRunInContext = vmModule.runInContext.bind(vmModule); |
| 129 | + |
| 130 | + vmModule.runInContext = ( |
| 131 | + code: string, |
| 132 | + contextifiedObject: Context, |
| 133 | + options?: RunningCodeOptions | string |
| 134 | + ) => { |
| 135 | + type RuntimeContext = Record<string, unknown> & { |
| 136 | + [cloudflareContextSymbol]?: CloudflareContext<CfProperties, Context>; |
| 137 | + }; |
| 138 | + const runtimeContext = contextifiedObject as RuntimeContext; |
| 139 | + runtimeContext[cloudflareContextSymbol] ??= cloudflareContext; |
| 140 | + return originalRunInContext(code, contextifiedObject, options); |
| 141 | + }; |
| 142 | +} |
| 143 | + |
| 144 | +/** |
| 145 | + * Gets a cloudflare context object from wrangler |
| 146 | + * |
| 147 | + * @returns the cloudflare context ready for use |
| 148 | + */ |
| 149 | +async function getCloudflareContextFromWrangler< |
| 150 | + CfProperties extends Record<string, unknown> = IncomingRequestCfProperties, |
| 151 | + Context = ExecutionContext, |
| 152 | +>(): Promise<CloudflareContext<CfProperties, Context>> { |
| 153 | + // Note: we never want wrangler to be bundled in the Next.js app, that's why the import below looks like it does |
| 154 | + const { getPlatformProxy } = await import(/* webpackIgnore: true */ `${"__wrangler".replaceAll("_", "")}`); |
| 155 | + const { env, cf, ctx } = await getPlatformProxy({ |
| 156 | + // This allows the selection of a wrangler environment while running in next dev mode |
| 157 | + environment: process.env.NEXT_DEV_WRANGLER_ENV, |
| 158 | + }); |
| 159 | + return { |
| 160 | + env, |
| 161 | + cf: cf as unknown as CfProperties, |
| 162 | + ctx: ctx as Context, |
| 163 | + }; |
| 164 | +} |
0 commit comments