Skip to content

Commit

Permalink
add "async mode" to getCloudflareContext
Browse files Browse the repository at this point in the history
add a new option to `getCloudflareContext` that makes it run in "async mode", the difference being that the returned value is a
promise of the Cloudflare context instead of the context itself

The main of this is that it allows the function to also run during SSG (since the missing context can be created on demand).
  • Loading branch information
dario-piotrowicz committed Feb 12, 2025
1 parent 5a3555e commit 0d74780
Show file tree
Hide file tree
Showing 19 changed files with 528 additions and 41 deletions.
10 changes: 10 additions & 0 deletions .changeset/tough-tables-talk.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
"@opennextjs/cloudflare": patch
---

add "async mode" to `getCloudflareContext`

add a new option to `getCloudflareContext` that makes it run in "async mode", the difference being that the returned value is a
promise of the Cloudflare context instead of the context itself

The main of this is that it allows the function to also run during SSG (since the missing context can be created on demand).
1 change: 1 addition & 0 deletions examples/common/apps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const apps = [
"middleware",
"vercel-blog-starter",
"vercel-commerce",
"ssg-app",
// e2e
"app-pages-router",
"app-router",
Expand Down
1 change: 1 addition & 0 deletions examples/ssg-app/.dev.vars
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
MY_SECRET = "psst... this is a secret!"
47 changes: 47 additions & 0 deletions examples/ssg-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*

# env files (can opt-in for committing if needed)
.env*

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts

# playwright
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/
Binary file added examples/ssg-app/app/favicon.ico
Binary file not shown.
14 changes: 14 additions & 0 deletions examples/ssg-app/app/globals.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
html,
body {
max-width: 100vw;
overflow-x: hidden;
height: 100vh;
display: flex;
flex-direction: column;
}

footer {
padding: 1rem;
display: flex;
justify-content: end;
}
28 changes: 28 additions & 0 deletions examples/ssg-app/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { Metadata } from "next";
import "./globals.css";

import { getCloudflareContext } from "@opennextjs/cloudflare";

export const metadata: Metadata = {
title: "SSG App",
description: "An app in which all the routes are SSG'd",
};

export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
const cloudflareContext = await getCloudflareContext({
async: true,
});

return (
<html lang="en">
<body>
{children}
<footer data-testid="app-version">{cloudflareContext.env.APP_VERSION}</footer>
</body>
</html>
);
}
17 changes: 17 additions & 0 deletions examples/ssg-app/app/page.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
.page {
display: grid;
grid-template-rows: 20px 1fr 20px;
align-items: center;
justify-items: center;
flex: 1;
border: 3px solid gray;
margin: 1rem;
margin-block-end: 0;
}

.main {
display: flex;
flex-direction: column;
gap: 32px;
grid-row-start: 2;
}
17 changes: 17 additions & 0 deletions examples/ssg-app/app/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import styles from "./page.module.css";
import { getCloudflareContext } from "@opennextjs/cloudflare";

export default async function Home() {
const cloudflareContext = await getCloudflareContext({
async: true,
});

return (
<div className={styles.page}>
<main className={styles.main}>
<h1>Hello from a Statically generated app</h1>
<p data-testid="my-secret">{cloudflareContext.env.MY_SECRET}</p>
</main>
</div>
);
}
17 changes: 17 additions & 0 deletions examples/ssg-app/e2e/base.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { test, expect } from "@playwright/test";

test("the index page should work", async ({ page }) => {
await page.goto("/");
await expect(page.getByText("Hello from a Statically generated app")).toBeVisible();
});

test("the APP_VERSION var from the cloudflare context should be displayed", async ({ page }) => {
await page.goto("/");
await expect(page.getByTestId("app-version")).toHaveText("1.2.345");
});

// Note: secrets from .dev.vars are also part of the SSG output, this is expected and nothing we can avoid
test("the MY_SECRET secret from the cloudflare context should be displayed", async ({ page }) => {
await page.goto("/");
await expect(page.getByTestId("my-secret")).toHaveText("psst... this is a secret!");
});
3 changes: 3 additions & 0 deletions examples/ssg-app/e2e/playwright.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { configurePlaywright } from "../../common/config-e2e";

export default configurePlaywright("ssg-app", { isCI: !!process.env.CI });
10 changes: 10 additions & 0 deletions examples/ssg-app/next.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import type { NextConfig } from "next";
import { initOpenNextCloudflareForDev } from "@opennextjs/cloudflare";

initOpenNextCloudflareForDev();

const nextConfig: NextConfig = {
/* config options here */
};

export default nextConfig;
26 changes: 26 additions & 0 deletions examples/ssg-app/open-next.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// default open-next.config.ts file created by @opennextjs/cloudflare

import cache from "@opennextjs/cloudflare/kv-cache";

const config = {
default: {
override: {
wrapper: "cloudflare-node",
converter: "edge",
incrementalCache: async () => cache,
tagCache: "dummy",
queue: "dummy",
},
},

middleware: {
external: true,
override: {
wrapper: "cloudflare-edge",
converter: "edge",
proxyExternalRequest: "fetch",
},
},
};

export default config;
28 changes: 28 additions & 0 deletions examples/ssg-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "ssg-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"build:worker": "opennextjs-cloudflare",
"preview": "pnpm build:worker && pnpm wrangler dev",
"e2e": "playwright test -c e2e/playwright.config.ts"
},
"dependencies": {
"react": "^19.0.0",
"react-dom": "^19.0.0",
"next": "15.1.7"
},
"devDependencies": {
"@opennextjs/cloudflare": "workspace:*",
"@playwright/test": "catalog:",
"@types/node": "catalog:",
"@types/react": "^19",
"@types/react-dom": "^19",
"typescript": "catalog:",
"wrangler": "catalog:"
}
}
27 changes: 27 additions & 0 deletions examples/ssg-app/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
5 changes: 5 additions & 0 deletions examples/ssg-app/worker-configuration.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
interface CloudflareEnv {
APP_VERSION: "1.2.345";
MY_SECRET: string;
ASSETS: Fetcher;
}
22 changes: 22 additions & 0 deletions examples/ssg-app/wrangler.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"$schema": "node_modules/wrangler/config-schema.json",
"main": ".open-next/worker.js",
"name": "ssg-app",
"compatibility_date": "2025-02-04",
"compatibility_flags": ["nodejs_compat"],
"assets": {
"directory": ".open-next/assets",
"binding": "ASSETS"
},
"vars": {
"APP_VERSION": "1.2.345"
},
"kv_namespaces": [
// Create a KV binding with the binding name "NEXT_CACHE_WORKERS_KV"
// to enable the KV based caching:
// {
// "binding": "NEXT_CACHE_WORKERS_KV",
// "id": "<BINDING_ID>"
// }
]
}
64 changes: 54 additions & 10 deletions packages/cloudflare/src/api/cloudflare-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,14 @@ type InternalGlobalThis<
__NEXT_DATA__: Record<string, unknown>;
};

type GetCloudflareContextOptions = Partial<{
/**
* Make `getCloudflareContext` return a promise of the cloudflare context instead of the object itself. This allows the
* function to be called in statically generated routes.
*/
async: boolean;
}>;

/**
* Utility to get the current Cloudflare context
*
Expand All @@ -53,26 +61,46 @@ type InternalGlobalThis<
export function getCloudflareContext<
CfProperties extends Record<string, unknown> = IncomingRequestCfProperties,
Context = ExecutionContext,
>(): CloudflareContext<CfProperties, Context> {
>(options: { async: true }): Promise<CloudflareContext<CfProperties, Context>>;
export function getCloudflareContext<
CfProperties extends Record<string, unknown> = IncomingRequestCfProperties,
Context = ExecutionContext,
>(options?: { async?: false }): CloudflareContext<CfProperties, Context>;
export function getCloudflareContext<
CfProperties extends Record<string, unknown> = IncomingRequestCfProperties,
Context = ExecutionContext,
>(
options: GetCloudflareContextOptions = {}
): CloudflareContext<CfProperties, Context> | Promise<CloudflareContext<CfProperties, Context>> {
const global = globalThis as InternalGlobalThis<CfProperties, Context>;

const cloudflareContext = global[cloudflareContextSymbol];

// whether `getCloudflareContext` is run in "async mode"
const asyncMode = options.async;

if (!cloudflareContext) {
// For SSG Next.js creates (jest) workers that run in parallel, those don't get the current global
// state so they can't get access to the cloudflare context, unfortunately there isn't anything we
// can do about this, so the only solution is to error asking the developer to opt-out of SSG
// Next.js sets globalThis.__NEXT_DATA__.nextExport to true for the worker, so we can use that to detect
// that the route is being SSG'd (source: https://github.com/vercel/next.js/blob/4e394608423/packages/next/src/export/worker.ts#L55-L57)
if (global.__NEXT_DATA__?.nextExport === true) {
// The non-async mode of `getCloudflareContext`, relies on the context set on the global state
// by either the worker entrypoint (in prod) or by `initOpenNextCloudflareForDev` (in dev), neither
// can work during SSG since for SSG Next.js creates (jest) workers that don't get access to the
// normal global state. There isn't much we can do about this so we can only throw with a helpful
// error message for the user.
// Note: Next.js sets globalThis.__NEXT_DATA__.nextExport to true for the worker, so we can use that to detect
// wether the route is being SSG'd (source: https://github.com/vercel/next.js/blob/4e394608423/packages/next/src/export/worker.ts#L55-L57)
if (!asyncMode && global.__NEXT_DATA__?.nextExport === true) {
throw new Error(
`\n\nERROR: \`getCloudflareContext\` has been called in a static route` +
` that is not allowed, please either avoid calling \`getCloudflareContext\`` +
` in the route or make the route non static (for example by exporting the` +
` \`dynamic\` route segment config set to \`'force-dynamic'\`.\n`
` that is not allowed, this can be solved in different ways:\n\n` +
` - call \`getCloudflareContext\` in \`async\` mode\n` +
` - avoid calling \`getCloudflareContext\` in the route\n` +
` - make the route non static\n`
);
}

if (options.async) {
return getAndSetCloudflareContextInNextDev();
}

// the cloudflare context is initialized by the worker and is always present in production/preview
// during local development (`next dev`) it might be missing only if the developers hasn't called
// the `initOpenNextCloudflareForDev` function in their Next.js config file
Expand Down Expand Up @@ -192,3 +220,19 @@ async function getCloudflareContextFromWrangler<
ctx: ctx as Context,
};
}

/**
* Gets a local proxy version of the cloudflare context (created using `getPlatformProxy`) when
* running in the standard next dev server (via `next dev`), is also sets this value on the
* globalThis so that it can be accessed later.
*
* @returns the local proxy version of the cloudflare context
*/
async function getAndSetCloudflareContextInNextDev<
CfProperties extends Record<string, unknown> = IncomingRequestCfProperties,
Context = ExecutionContext,
>(): Promise<CloudflareContext<CfProperties, Context>> {
const context = await getCloudflareContextFromWrangler();
addCloudflareContextToNodejsGlobal(context);
return context as unknown as CloudflareContext<CfProperties, Context>;
}
Loading

0 comments on commit 0d74780

Please sign in to comment.