Skip to main content
ClaudeWave
Skill217 repo starsupdated 2d ago

cloudflare-nextjs

This Claude Code skill deploys Next.js applications to Cloudflare Workers using the OpenNext adapter, supporting SSR, ISR, and both App and Pages Routers. Use it when migrating Next.js projects to Cloudflare, integrating Cloudflare services like D1 or R2, or when encountering Worker size limits and runtime compatibility issues that require edge deployment solutions.

Install in Claude Code
Copy
git clone --depth 1 https://github.com/secondsky/claude-skills /tmp/cloudflare-nextjs && cp -r /tmp/cloudflare-nextjs/plugins/cloudflare-nextjs/skills/cloudflare-nextjs ~/.claude/skills/cloudflare-nextjs
Then start a new Claude Code session; the skill loads automatically.

SKILL.md

# OpenNext Cloudflare Adapter — Next.js on Workers

Deploy Next.js applications to **Cloudflare Workers** using the OpenNext adapter (`@opennextjs/cloudflare`). The adapter takes a standard Next.js build, runs `package.json` build script, then transforms the output to run on the Workers runtime using the Node.js compatibility layer (`nodejs_compat`) — **not** the Edge runtime.

## Critical Requirements (get these wrong and the build/runtime fails)

| Requirement | Value | Why |
|---|---|---|
| Runtime | **Node.js** (default). Remove every `export const runtime = "edge";` | Edge runtime is unsupported; OpenNext uses `nodejs_compat`. |
| `compatibility_flags` | `["nodejs_compat", "global_fetch_strictly_public"]` | Node APIs + allow `fetch()` in app code. |
| `compatibility_date` | **≥ `2024-09-23`**; **≥ `2025-05-05`** recommended (FinalizationRegistry) | Older dates break `FinalizationRegistry`, DOs, and more. |
| Wrangler | **≥ `3.99.0`** to deploy; **≥ `4.13.0`** for `keep_names`; **≥ `4.36.0`** for stable remote bindings | Feature gates in the docs. |
| Next.js | v16 all minors/patches supported; latest minors of v14 and v15; **v14 dropped Q1 2026** | Stated on the overview page. |
| Worker size (gzip) | **3 MiB Free / 10 MiB Paid** (compressed only) | Hard Cloudflare limits. |

**Windows:** not fully guaranteed (Next.js tooling issues). Use WSL, a Linux VM, or Linux/macOS CI. See known issue #1305.

## Disambiguation: this skill vs `nextjs`

- **`nextjs` skill** → framework/App Router/Server Components/Cache Components patterns, **any platform** (Vercel, self-hosted, ...). Use for `async params`, `proxy.ts` migration, `"use cache"`.
- **THIS skill (`cloudflare-nextjs`)** → deploying Next.js to **Workers** via the OpenNext adapter: `wrangler.jsonc`, `open-next.config.ts`, `getCloudflareContext`, caching tiers, bindings, skew protection, multi-worker, the Workers-specific errors.

> **proxy.ts caveat (Next 16):** Next 16 renamed `middleware.ts` → `proxy.ts`, but `@opennextjs/cloudflare` does **not** recognize `proxy.ts` yet (issue #1277) — on Cloudflare, keep using `middleware.ts`. This is the one place the `nextjs` skill's guidance does NOT apply here.

## Quick Start

### New project (recommended)

```bash
npm create cloudflare@latest -- my-next-app --framework=next --platform=workers
```

C3 scaffolds a Next.js app, installs `@opennextjs/cloudflare`, creates `wrangler.jsonc` + `open-next.config.ts` + `.dev.vars`, wires `package.json` scripts, and (if R2 is enabled) creates an R2 bucket for caching.

### Existing Next.js project (one command)

```bash
npx @opennextjs/cloudflare migrate
```

`migrate` automates: install adapter + wrangler, create `wrangler.jsonc`/`open-next.config.ts`/`.dev.vars`, update scripts, add `public/_headers`, add `.open-next` to `.gitignore`, wire `initOpenNextCloudflareForDev()` into `next.config.ts`, and create+configure an R2 cache bucket (only if R2 is enabled on the account).

<details><summary>Manual install (if you prefer not to run migrate)</summary>

```bash
npm install @opennextjs/cloudflare@latest
npm install --save-dev wrangler@latest
```

Then create the three files (see `references/wrangler.jsonc`, `references/open-next.config.ts`, `references/package.json`) and add the `dev`/`preview`/`deploy`/`upload`/`cf-typegen` scripts. **Pin adapter versions and audit before upgrading** — see the `dependency-upgrade` skill.

</details>

### The four scripts

```jsonc
// package.json
{
  "dev":     "next dev",                                                       // fast HMR via Next dev server
  "preview": "opennextjs-cloudflare build && opennextjs-cloudflare preview",   // build + run in workerd locally
  "deploy":  "opennextjs-cloudflare build && opennextjs-cloudflare deploy",    // build + serve immediately
  "upload":  "opennextjs-cloudflare build && opennextjs-cloudflare upload",    // build + upload a version (gradual rollout)
  "cf-typegen": "wrangler types --env-interface CloudflareEnv cloudflare-env.d.ts"
}
```

- `dev` — fastest feedback loop; add `initOpenNextCloudflareForDev()` to `next.config.ts` so `getCloudflareContext()` works locally with simulated/remote bindings.
- `preview` — runs in the **actual Workers runtime** (not Node). Always run before `deploy` to catch runtime-only issues.
- `deploy` — populates the **remote** cache, then `wrangler deploy`. App serves immediately.
- `upload` — populates remote cache, then `wrangler versions upload`. Does NOT serve automatically; for gradual deployments.

`build`, `preview`, `deploy`, `upload` all implicitly call `populateCache` — you do not need to run it manually.

### Dev `next.config.ts`

```ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = { /* ... */ };
export default nextConfig;

import { initOpenNextCloudflareForDev } from "@opennextjs/cloudflare";
initOpenNextCloudflareForDev();
```

## Accessing Cloudflare Bindings — `getCloudflareContext()`

**Do NOT use `process.env` for bindings.** The official API is `getCloudflareContext()` from `@opennextjs/cloudflare`.

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

export async function GET() {
  const { env, cf, ctx } = getCloudflareContext();
  await env.MY_KV.put("foo", "bar");
  return new Response(await env.MY_KV.get("foo"));
}
```

**Static routes (ISR/SSG) MUST use async mode** — and be careful: secrets/local values are used during static generation.

```ts
const { env } = await getCloudflareContext({ async: true });
```

**TypeScript types:** `npm run cf-typegen` generates `cloudflare-env.d.ts` (re-run after any binding change).

**Remote bindings (local dev → real resources):** stabilized in **Wrangler 4.36.0**. On older wrangler, enable via `initOpenNextCloudflareForDev({ experimental: { remoteBindings: true } })` and use the `experimental_remote` (not `remote`) key on binding options. Note: remote bindings are also used **during build**.

Full patterns (D1/R2/KV/AI/Hyperdrive, Drizzle,
access-control-rbacSkill

Role-based access control (RBAC) with permissions and policies. Use for admin dashboards, enterprise access, multi-tenant apps, fine-grained authorization, or encountering permission hierarchies, role inheritance, policy conflicts.

aceternity-uiSkill

100+ animated React components (Aceternity UI) for Next.js with Tailwind. Use for hero sections, parallax, 3D effects, or encountering animation, shadcn CLI integration errors.

ai-elements-chatbotSkill

shadcn/ui AI chat components for conversational interfaces. Use for streaming chat, tool/function displays, reasoning visualization, or encountering Next.js App Router setup, Tailwind v4 integration, AI SDK v5 migration errors.

ai-sdk-coreSkill

Vercel AI SDK v5 for backend AI (text generation, structured output, tools, agents). Multi-provider. Use for server-side AI or encountering AI_APICallError, AI_NoObjectGeneratedError, streaming failures.

ai-sdk-uiSkill

Vercel AI SDK v5 React hooks (useChat, useCompletion, useObject) for AI chat interfaces. Use for React/Next.js AI apps or encountering parse stream errors, no response, streaming issues.

api-authenticationSkill

Secure API authentication with JWT, OAuth 2.0, API keys. Use for authentication systems, third-party integrations, service-to-service communication, or encountering token management, security headers, auth flow errors.

api-changelog-versioningSkill

Creates comprehensive API changelogs documenting breaking changes, deprecations, and migration strategies for API consumers. Use when managing API versions, communicating breaking changes, or creating upgrade guides.

api-contract-testingSkill

Verifies API contracts between services using consumer-driven contracts, schema validation, and tools like Pact. Use when testing microservices communication, preventing breaking changes, or validating OpenAPI specifications.