跳到正文

Fullstack Next.js on Cloudflare

维护中
ifindev/fullstack-next-cloudflare

Next.js 15 + Cloudflare Workers 全栈模板,集成 D1 数据库、R2 存储、Better Auth 和 Server Actions。生产可用,自带 CI/CD,免费额度充足。

在 GitHub 查看
星标
1371
Fork
217
关注
1371
未关闭 Issue
19

该介绍目前仅提供英文版本。

Production-ready Next.js 15 + Cloudflare Workers template with D1 database, R2 storage, Better Auth, and Server Actions.

Overview

A modern, full-stack Next.js 15 template built specifically for Cloudflare’s edge computing platform. This production-ready template combines the power of Next.js with Cloudflare Workers, D1 database, R2 storage, and Better Auth to create a complete development solution with automated CI/CD and generous free tiers.

Built by Muhammad Arifin, this template leverages a feature-based/module-sliced architecture for better maintainability and scalability, making it perfect for building modern web applications that need global performance and edge-first deployment.

Key Features

  • 🚀 Next.js 15 + App Router: Latest Next.js with React Server Components, Server Actions, and optimized routing
  • ⚡ Cloudflare Workers: Edge-native runtime with global deployment and generous free tiers
  • 🗄️ Database Integration: Cloudflare D1 (SQLite) with Drizzle ORM for type-safe database operations
  • 📁 File Storage: Cloudflare R2 for scalable object storage and media handling
  • 🔐 Authentication: Better Auth with secure session management and OAuth providers
  • 🤖 AI Integration: Built-in AI summarization service using Cloudflare Workers AI
  • 🏗️ Module Architecture: Feature-based structure with clear separation of concerns
  • 🔧 Developer Experience: Wrangler CLI, TypeScript typegen, and hot module reloading
  • 🚀 CI/CD Pipeline: Automated deployment with GitHub Actions
  • 📊 Observability: Built-in analytics, error tracking, and performance monitoring

Architecture Benefits

  • 🎯 Feature Isolation: Each module contains its own actions, components, and logic
  • 🔄 Server Actions: Modern data mutations with automatic revalidation
  • 📊 React Server Components: Optimal performance with server-side rendering
  • 🛡️ Type Safety: End-to-end TypeScript from database to UI
  • 🧪 Testable: Clear separation of concerns makes testing easier

Project Structure

This template uses a feature-based/module-sliced architecture for better maintainability and scalability:

src/
├── app/                    # Next.js App Router
│   ├── (auth)/            # Auth-related pages
│   ├── api/               # API routes (for external access)
│   │   └── summarize/     # AI summarization endpoint
│   ├── dashboard/         # Dashboard pages
│   └── globals.css        # Global styles
├── components/            # Shared UI components
├── constants/             # App constants
├── db/                    # Database configuration
│   ├── index.ts          # DB connection
│   └── schema.ts         # Database schemas
├── lib/                   # Shared utilities
├── modules/               # Feature modules
│   ├── auth/             # Authentication module
│   │   ├── actions/      # Auth server actions
│   │   ├── components/   # Auth components
│   │   ├── hooks/        # Auth hooks
│   │   ├── models/       # Auth models
│   │   ├── schemas/      # Auth schemas
│   │   └── utils/        # Auth utilities
│   ├── dashboard/        # Dashboard module
│   └── todos/            # Todo module
│       ├── actions/      # Todo server actions
│       ├── components/   # Todo components
│       ├── models/       # Todo models
│       └── schemas/      # Todo schemas
├── services/              # Business logic services
│   └── summarizer.service.ts  # AI summarization service
└── drizzle/              # Database migrations

Quick Start

Prerequisites

  • Node.js 18+
  • pnpm (recommended)
  • Cloudflare account (free)

First-time Setup

  1. Generate Cloudflare types:

    pnpm run cf-typegen
  2. Setup database:

    pnpm run db:migrate:local
  3. Build application:

    pnpm run build:cf

Daily Development

  1. Start D1 access (Terminal 1):

    pnpm run wrangler:dev
  2. Start Next.js with HMR (Terminal 2):

    pnpm run dev

After Schema Changes

  1. Generate migration:

    pnpm run db:generate
  2. Apply to local DB:

    pnpm run db:migrate:local

AI Development & Testing

Testing the AI API

⚠️ Authentication Required: Login to your app first, then test the API.

Browser Console (Easiest):

  1. Login at http://localhost:3000
  2. Open DevTools Console (F12)
  3. Run:
fetch('/api/summarize', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  credentials: 'include',
  body: JSON.stringify({
    text: "Your text to summarize here...",
    config: { maxLength: 100, style: "concise" }
  })
}).then(r => r.json()).then(console.log);

AI Service Architecture

The AI integration follows a clean service-based architecture:

  1. API Route (/api/summarize) - Handles HTTP requests, authentication, and validation
  2. Authentication Layer - Validates user session before processing requests
  3. SummarizerService - Encapsulates AI business logic
  4. Error Handling - Comprehensive error responses with proper status codes
  5. Type Safety - Full TypeScript support with Zod validation

Supported AI Models

  • @cf/meta/llama-3.2-1b-instruct - Text generation (current)
  • @cf/meta/llama-3.2-3b-instruct - More capable text generation
  • @cf/meta/m2m100-1.2b - Translation
  • @cf/baai/bge-base-en-v1.5 - Text embeddings
  • @cf/microsoft/resnet-50 - Image classification

Deployment

Push to main branch triggers automatic deployment via GitHub Actions:

git add .
git commit -m "feat: add new feature"
git push origin main

Deployment Pipeline:

  1. ✅ Install dependencies
  2. ✅ Build application
  3. ✅ Run database migrations
  4. ✅ Deploy to Cloudflare Workers

Manual Deployment

# Deploy to production
pnpm run deploy

# Deploy to preview environment
pnpm run deploy:preview

Performance & Monitoring

Built-in Observability:

  • ✅ Cloudflare Analytics (enabled by default)
  • ✅ Real User Monitoring (RUM)
  • ✅ Error tracking and logging
  • ✅ Performance metrics

Database Monitoring:

# Monitor database performance
wrangler d1 insights next-cf-app

# View database metrics in Cloudflare Dashboard
# Navigate to Workers & Pages → D1 → next-cf-app → Metrics

Development Scripts

Database Management

Script Description
pnpm run db:generate Generate database migrations
pnpm run db:migrate:local Apply migrations to local DB
pnpm run db:studio:local Open Drizzle Studio for local DB
pnpm run db:reset:local Reset local database

Deployment & Production

Script Description
pnpm run deploy Deploy to production
pnpm run deploy:preview Deploy to preview environment
pnpm run cf-typegen Generate Cloudflare TypeScript types
pnpm run cf:secret Add secrets to Cloudflare Workers

Roadmap

🤖 AI Features

  • Add text translation service with @cf/meta/m2m100-1.2b
  • Implement text embeddings for semantic search
  • Add image classification API
  • Create chat/conversation API with memory
  • Add content moderation with AI classification

💳 Payments & Communication

  • Implement email sending with Resend & Cloudflare Email Routing
  • Implement international payment gateway with Polar.sh
  • Implement Indonesian payment gateway (Xendit, Midtrans, or Duitku)

📊 Analytics & Performance

  • Add Cloudflare Analytics integration
  • Implement custom metrics tracking
  • Add performance monitoring dashboard
  • Create AI usage analytics and cost tracking

License

This project is licensed under the MIT License - see the LICENSE file for details.


© 2025 Muhammad Arifin. All rights reserved.

Ready to build your next application? Clone this template and start building with the power of Next.js 15 and Cloudflare’s edge network!

按共同分类和标签排序的同类开源项目。

全部 Web 框架项目 →