Skip to content

Commit b883de7

Browse files
authored
Add an example for importing cloudflare:* modules (#1067)
1 parent 0230cbe commit b883de7

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import module from "node:module";
2+
3+
export const dynamic = "force-dynamic";
4+
5+
export async function GET() {
6+
if (globalThis.Cloudflare) {
7+
// Importing `cloudflare:*` does not work in dev (using `next dev`) because the Node runtime is used there.
8+
// Then you should avoid it to write portable code.
9+
// To access `env` and bindings, using `getCloudflareContext()` is the preferred way.
10+
// See https://opennext.js.org/cloudflare/bindings
11+
const req = module.createRequire("file:///");
12+
const { env } = req("cloudflare:workers");
13+
return Response.json({ cloudflare: true, env });
14+
}
15+
16+
return Response.json({ cloudflare: false });
17+
}

examples/playground15/e2e/cloudflare.spec.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,14 @@ test.describe("playground/cloudflare", () => {
1414
expect(nextConfig.output).toEqual("standalone");
1515
});
1616
});
17+
18+
test.describe("using cloudflare:* modules", () => {
19+
test("NextConfig", async ({ page }) => {
20+
const res = await page.request.get("/api/cloudflare");
21+
expect(res.status()).toEqual(200);
22+
const { cloudflare, env } = await res.json();
23+
expect(cloudflare).toBe(true);
24+
expect(env.NEXTJS_ENV).toEqual("development");
25+
expect(env.ASSETS).toBeDefined();
26+
});
27+
});

0 commit comments

Comments
 (0)