Back to home

Complete Guide Deploying Next.js Applications to Cloudflare Pages

76 min read

In modern web development, Next.js has gained immense popularity for its powerful full-stack development capabilities. This guide will walk you through the process of deploying your Next.js application to Cloudflare Pages, helping you build high-performance, globally distributed applications.

I. Foundation Knowledge

1.1 Runtime Selection

Next.js provides two runtime environments:

  • Edge Runtime: Lightweight runtime, suitable for Cloudflare Pages
  • Node.js Runtime: Full Node.js API support

There are two main deployment adapters:

  • @cloudflare/next-on-pages: Official support, Edge Runtime only
  • @opennextjs/cloudflare: Supports Node.js Runtime, still in development

1.2 Supported Next.js Versions

  • Supports all minor and patch versions of Next.js 13 and 14
  • Regular compatibility testing ensures stability

II. Deployment Steps

2.1 Quick Start for New Projects

For creating a new project, use the official scaffolding:

pnpm create cloudflare@latest my-next-app --framework=next

2.2 Steps for Existing Projects

1) Install Dependencies

npm install --save-dev @cloudflare/next-on-pages

2) Add Configuration File

Create wrangler.toml in the project root:

name = "my-app"
compatibility_date = "2024-07-29"
compatibility_flags = ["nodejs_compat"]
pages_build_output_dir = ".vercel/output/static"

3) Update Next.js Configuration

Modify next.config.mjs:

import { setupDevPlatform } from '@cloudflare/next-on-pages/next-dev';

/** @type {import('next').NextConfig} */
const nextConfig = {};

if (process.env.NODE_ENV === 'development') {
  await setupDevPlatform();
}

export default nextConfig;

4) Configure Server-Side Routes

All server-rendered routes must use Edge Runtime:

// app/api/hello/route.js
export const runtime = "edge";

export async function GET() {
  return new Response('Hello World');
}

5) Update package.json

Add necessary script commands:

{
  "scripts": {
    "pages:build": "npx @cloudflare/next-on-pages",
    "preview": "npm run pages:build && wrangler pages dev",
    "deploy": "npm run pages:build && wrangler pages deploy"
  }
}

III. Advanced Features Configuration

3.1 Binding Integration

For using Cloudflare services like KV or R2, you need to configure bindings.

  1. First, install type declarations:
npm install --save-dev @cloudflare/workers-types
  1. Create type declaration file env.d.ts:
interface CloudflareEnv {
  MY_KV: KVNamespace;
  MY_R2: R2Bucket;
}
  1. Use bindings in your code:
import { getRequestContext } from "@cloudflare/next-on-pages";

export const runtime = "edge";
export async function GET(request) {
  const { env } = getRequestContext();
  const data = await env.MY_KV.get("key");
  return new Response(data);
}

3.2 Custom Worker Entry Point

For adding custom logic before/after request handling:

import nextOnPagesHandler from "@cloudflare/next-on-pages/fetch-handler";

export default {
  async fetch(request, env, ctx) {
    // Pre-request handling
    console.log("Request received:", request.url);
    
    const response = await nextOnPagesHandler.fetch(request, env, ctx);
    
    // Post-response handling
    response.headers.set("X-Custom-Header", "value");
    
    return response;
  },
} as ExportedHandler<{ ASSETS: Fetcher }>;

3.3 Static Asset Routing

Create _routes.json to customize static asset handling:

{
  "version": 1,
  "exclude": [
    "/favicon.ico",
    "/static/*"
  ]
}

IV. Deployment and Testing

4.1 Local Testing

npm run preview

4.2 Production Deployment

npm run deploy

4.3 Continuous Integration

  1. Connect GitHub/GitLab repository
  2. Configure automatic build and deployment
  3. Set up environment variables and bindings

V. Troubleshooting Common Issues

  1. Runtime Errors

    • Verify Edge Runtime is set for all server-side routes
    • Check Node.js API usage compliance
  2. Build Failures

    • Confirm dependency version compatibility
    • Validate configuration file formats
  3. Binding Access Issues

    • Verify binding configurations
    • Check permission settings

Conclusion

Deploying a Next.js application to Cloudflare Pages is a straightforward process that requires attention to detail. Through this guide's step-by-step instructions and best practices, you should now have a solid understanding of the complete development-to-deployment workflow.

Key takeaways:

  1. Choose appropriate runtime and adapter
  2. Configure server-side routes correctly
  3. Use bindings and custom features wisely
  4. Prioritize local testing and continuous integration

Follow us for more web development technical insights!