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
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();
import type { NextConfig } from "next";
const config: NextConfig = {
// Cloudflare-specific configuration
};
export default config;
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>
);
}
import type { website } from "./alchemy.run";
declare module "@cloudflare/next-on-pages" {
interface RequestContext {
env: typeof website.Env;
}
}
Key Features Explained
KV Namespace Integration
KV is bound to your Next.js application:Edge Runtime
Next.js pages run on Cloudflare’s edge:Adoption Mode
Theadopt: true flag allows reusing existing deployments: