Skip to content

Cloudflare Version

HaloLight Cloudflare version is built on Next.js 15 App Router + React 19, using @opennextjs/cloudflare adapter for Cloudflare Workers/Pages edge runtime, enabling global low-latency access.

Live Preview: https://halolight-cloudflare.h7ml.cn/

GitHub: https://github.com/halolight/halolight-cloudflare

Differences from Original

FeatureOriginal (Next.js)Cloudflare Version
Next.js14.x15.5.x
React18.x19.x
RuntimeNode.js (Vercel)Cloudflare Workers (Edge)
Deployment PlatformVercel / DockerCloudflare Pages
Development ToolswebpackTurbopack
Deployment Commandpnpm build && pnpm startpnpm deploy
SSR LocationServer/ServerlessGlobal edge nodes
Cold StartPlatform-dependent< 50ms

Tech Stack

TechnologyVersionDescription
Next.js15.5.xReact full-stack framework
React19.xUI library
TypeScript5.xType safety
Tailwind CSS4.xAtomic CSS
@opennextjs/cloudflare1.xCloudflare adapter layer
Wrangler4.xCloudflare CLI
shadcn/uilatestUI component library
Zustand5.xState management
TanStack Query5.xServer state
Vitest4.xUnit testing
Mock.js1.xData mocking

Directory Structure

halolight-cloudflare/
├── src/
│   ├── app/                      # App Router pages
│   │   ├── (dashboard)/          # Dashboard route group
│   │   ├── (auth)/               # Auth route group
│   │   ├── (legal)/              # Legal terms route group
│   │   ├── layout.tsx            # Root layout
│   │   └── page.tsx              # Homepage
│   ├── components/               # React components
│   │   ├── ui/                   # shadcn/ui components
│   │   ├── layout/               # Layout components
│   │   └── dashboard/            # Dashboard components
│   ├── hooks/                    # React Hooks
│   ├── stores/                   # Zustand Stores
│   ├── lib/                      # Utilities
│   ├── mock/                     # Mock data
│   ├── providers/                # Context Providers
│   ├── config/                   # Configuration files
│   └── __tests__/                # Unit tests
├── public/                       # Static assets
├── .github/workflows/            # GitHub Actions CI
├── .open-next/                   # OpenNext build output (auto-generated)
├── coverage/                     # Test coverage (auto-generated)
├── cloudflare-env.d.ts           # Cloudflare environment types
├── vitest.config.ts              # Vitest test configuration
├── open-next.config.ts           # OpenNext configuration
├── wrangler.jsonc                # Wrangler configuration
├── next.config.ts                # Next.js configuration
└── package.json

Quick Start

Requirements

  • Node.js >= 18
  • pnpm >= 8
  • Wrangler CLI (requires Cloudflare login)

Installation

bash
git clone https://github.com/halolight/halolight-cloudflare.git
cd halolight-cloudflare
pnpm install

Environment Variables

bash
cp .dev.vars.example .dev.vars
bash
# .dev.vars example
NEXT_PUBLIC_API_URL=/api
NEXT_PUBLIC_MOCK=true
NEXT_PUBLIC_APP_TITLE=HaloLight
NEXT_PUBLIC_BRAND_NAME=HaloLight
NEXT_PUBLIC_DEMO_EMAIL=admin@halolight.h7ml.cn
NEXT_PUBLIC_DEMO_PASSWORD=Admin@123

Start Development

bash
pnpm dev

Visit http://localhost:3000

Local Preview (Edge Environment)

bash
pnpm preview

Simulates Cloudflare Workers environment to detect Edge Runtime compatibility issues.

Deploy to Cloudflare

bash
wrangler login   # Login required for first time
pnpm deploy      # Build and deploy

Common Scripts

bash
pnpm dev          # Start development server (Turbopack, Node.js environment)
pnpm build        # Next.js production build
pnpm preview      # Local preview of Cloudflare environment
pnpm deploy       # Deploy to Cloudflare
pnpm upload       # Upload only without deployment
pnpm lint         # ESLint check
pnpm type-check   # TypeScript type check
pnpm test         # Run unit tests (watch mode)
pnpm test:run     # Run unit tests (single run)
pnpm test:coverage # Run tests and generate coverage report
pnpm cf-typegen   # Generate Cloudflare environment types

Edge Runtime Constraints

Cloudflare Workers is an edge runtime, some Node.js APIs are unavailable:

Unavailable APIs:

  • fs - File system operations
  • child_process - Child processes
  • net, dgram - Native network sockets
  • crypto.createCipher and other legacy crypto APIs

Partially Available (via nodejs_compat):

  • Buffer - Binary data processing
  • process.env - Environment variables
  • crypto partial APIs - such as randomUUID()

Note

When using @opennextjs/cloudflare, the entire application automatically runs in edge environment, no need to manually declare export const runtime = 'edge'.

Cloudflare Services Integration

Available Services

ServicePurposeDescription
KVKey-value storageGlobally distributed cache
D1SQLite databaseEdge SQL database
R2Object storageS3-compatible storage
QueuesMessage queuesAsync task processing
Durable ObjectsStateful objectsReal-time collaboration
Workers AIAI inferenceEdge AI models

Usage Example

ts
import { getRequestContext } from '@opennextjs/cloudflare';

export async function GET() {
  const { env } = getRequestContext();
  const value = await env.MY_KV.get('key');
  return Response.json({ value });
}

Configure KV Storage

jsonc
// wrangler.jsonc
{
  "kv_namespaces": [
    { "binding": "MY_KV", "id": "xxx" }
  ]
}

Configure D1 Database

jsonc
// wrangler.jsonc
{
  "d1_databases": [
    { "binding": "MY_DB", "database_id": "xxx" }
  ]
}

SSR/SSG/ISR Support

Rendering ModeSupport StatusDescription
SSR✅ SupportedEach request renders at the edge
SSG✅ SupportedStatic pages generated at build time
ISR⚠️ PartialRequires R2 cache configuration

Enable ISR

ts
// open-next.config.ts
import { defineCloudflareConfig } from "@opennextjs/cloudflare";
import r2IncrementalCache from "@opennextjs/cloudflare/overrides/incremental-cache/r2-incremental-cache";

export default defineCloudflareConfig({
  incrementalCache: r2IncrementalCache,
});

CI/CD

Project has complete GitHub Actions CI workflow configured:

JobDescription
lintESLint + TypeScript type check
testVitest unit tests + Codecov coverage
buildOpenNext Cloudflare production build
securityDependency security audit
dependency-reviewPR dependency change review

Deployment Workflow Example

yaml
# .github/workflows/deploy.yml
name: Deploy to Cloudflare

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: pnpm/action-setup@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: pnpm
      - run: pnpm install
      - run: pnpm deploy
        env:
          CLOUDFLARE_API_TOKEN: ${{ secrets.CF_API_TOKEN }}

Deployment Architecture

User Request → Cloudflare CDN → Workers (Edge) → KV/D1/R2/External API

          300+ global nodes
          Nearby response < 50ms

Quota Limits

LimitFree TierPaid Tier
Worker script size1MB (compressed)10MB
CPU time10-50msSeconds
Memory128MB128MB
Subrequests501000
Request duration30s30s

Reference

For actual limits, check Cloudflare official documentation.

Version Rollback

Cloudflare Pages retains deployment history, supporting the following rollback methods:

  1. Dashboard Rollback:

    • Cloudflare Dashboard → Workers & Pages → Project → Deployments
    • Select historical version → "Rollback to this deployment"
  2. Redeploy Specific Commit:

    bash
    git checkout <commit-hash>
    pnpm deploy

Common Issues

"Cannot find module 'fs'" Error

Edge Runtime doesn't support Node.js built-in modules. Use Web APIs instead or ensure the code only runs on the client side.

Build Size Too Large

  • Check if dependencies have Node.js-specific code
  • Use dynamic imports to split code
  • Remove unused dependencies

Slow Cold Start

  • Reduce Worker script size
  • Use Smart Placement for nearby deployment
  • Warm up critical paths