Skip to main content

Cloudflare Next.js Example

This example demonstrates deploying a Next.js application to Cloudflare using the Next.js adapter with KV Namespace integration.

Features

  • Next.js: Full-stack React framework with SSR and SSG
  • KV Namespace: Key-value storage for session data, caching, etc.
  • Cloudflare Pages: Automatic deployment with edge rendering

Project Setup

1
Install Dependencies
2
npm install alchemy
npm install next react react-dom
3
Create alchemy.run.ts
4
Create your infrastructure file:
5
import alchemy from "alchemy";
import { KVNamespace, Nextjs } from "alchemy/cloudflare";

const app = await alchemy("cloudflare-nextjs");

export const kv = await KVNamespace("kv");

export const website = await Nextjs("website", {
  adopt: true,
  bindings: { KV: kv },
});

console.log(`Website: ${website.url}`);

if (process.env.ALCHEMY_E2E) {
  const { test } = await import("./test/e2e.js");
  await test({
    url: website.url,
  });
}

await app.finalize();
6
Configure Next.js
7
Create next.config.ts for Cloudflare:
8
import type { NextConfig } from "next";

const config: NextConfig = {
  // Cloudflare-specific configuration
};

export default config;
9
Create Next.js Pages
10
Create src/app/page.tsx:
11
import { getRequestContext } from '@cloudflare/next-on-pages';

export const runtime = 'edge';

export default async function Home() {
  const ctx = getRequestContext();
  const kv = ctx.env.KV;
  
  // Access KV namespace
  const count = await kv.get('visit-count') || '0';
  const newCount = parseInt(count) + 1;
  await kv.put('visit-count', newCount.toString());

  return (
    <div>
      <h1>Next.js on Cloudflare</h1>
      <p>Visit count: {newCount}</p>
    </div>
  );
}
12
Environment Types
13
Create env.d.ts for TypeScript support:
14
import type { website } from "./alchemy.run";

declare module "@cloudflare/next-on-pages" {
  interface RequestContext {
    env: typeof website.Env;
  }
}
15
Deploy
16
Deploy your Next.js app to Cloudflare:
17
npm exec tsx alchemy.run.ts

Key Features Explained

KV Namespace Integration

KV is bound to your Next.js application:
export const kv = await KVNamespace("kv");

export const website = await Nextjs("website", {
  bindings: { KV: kv },
});

Edge Runtime

Next.js pages run on Cloudflare’s edge:
export const runtime = 'edge';

Adoption Mode

The adopt: true flag allows reusing existing deployments:
export const website = await Nextjs("website", {
  adopt: true,
  bindings: { KV: kv },
});

Source Code

View the complete source code: examples/cloudflare-nextjs

Build docs developers (and LLMs) love