|
| 1 | +import "server-only"; |
| 2 | + |
| 3 | +declare global { |
| 4 | + // eslint-disable-next-line @typescript-eslint/no-empty-interface |
| 5 | + interface CloudflareEnv {} |
| 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; |
| 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 | + * Throws an error if the context could not be retrieved |
| 33 | + * |
| 34 | + * @returns the cloudflare context |
| 35 | + */ |
| 36 | +export async function getCloudflareContext< |
| 37 | + CfProperties extends Record<string, unknown> = IncomingRequestCfProperties, |
| 38 | + Context = ExecutionContext, |
| 39 | +>(): Promise<CloudflareContext<CfProperties, Context>> { |
| 40 | + const cloudflareContext = ( |
| 41 | + globalThis as unknown as { |
| 42 | + [cloudflareContextSymbol]: CloudflareContext<CfProperties, Context> | undefined; |
| 43 | + } |
| 44 | + )[cloudflareContextSymbol]; |
| 45 | + |
| 46 | + if (!cloudflareContext) { |
| 47 | + // TODO: cloudflareContext should always be present in production/preview, if not it means that this |
| 48 | + // is running under `next dev`, in this case use `getPlatformProxy` to return local proxies |
| 49 | + throw new Error("Cloudflare context is not defined!"); |
| 50 | + } |
| 51 | + |
| 52 | + return cloudflareContext; |
| 53 | +} |
0 commit comments