この紹介文は現在英語版のみです。
Build and deploy production-ready SaaS applications with Next.js on Cloudflare’s edge network.
Overview
The Cloudflare Workers Next.js SaaS Template is a comprehensive, production-ready starter template that combines the power of Next.js with Cloudflare’s serverless edge computing platform. This template provides everything you need to build, deploy, and scale modern SaaS applications with exceptional performance and global reach.
Built specifically for developers who want to leverage Cloudflare’s ecosystem, this template offers a complete full-stack solution with authentication, database integration, payments, and deployment automation - all optimized for edge computing.
Key Features
- 🌐 Edge-First Architecture: Built from the ground up for Cloudflare Workers and Pages
- ⚡ Next.js Integration: Latest Next.js features with App Router and React Server Components
- 🔐 Authentication System: Complete user authentication with session management
- 💳 Payment Integration: Stripe integration for subscription and payment processing
- 🗄️ Database Support: Prisma ORM with Cloudflare D1 database integration
- 🎨 Modern UI/UX: TailwindCSS with responsive design and dark mode support
- 📧 Email Service: Integrated email functionality using Cloudflare Workers
- 🔒 Security: Built-in security best practices and CSRF protection
- 📊 Analytics: Performance monitoring and user analytics
- 🚀 One-Click Deployment: Automated deployment with GitHub Actions
Technology Stack
Frontend
- Next.js 14+: Latest features with App Router and Server Components
- React 18: Modern React with Suspense and Concurrent Features
- TypeScript: Full type safety throughout the application
- TailwindCSS: Utility-first CSS framework with custom design system
- Radix UI: Accessible UI components with consistent design
Backend & Infrastructure
- Cloudflare Workers: Serverless edge computing for APIs
- Cloudflare Pages: Static site hosting with edge optimization
- Cloudflare D1: SQLite-compatible serverless database
- Cloudflare R2: Object storage for file uploads and media
- Cloudflare KV: Key-value storage for sessions and caching
Development Tools
- Prisma: Type-safe database ORM with migrations
- ESLint: Code linting with custom rules
- Prettier: Code formatting and style consistency
- Wrangler: Cloudflare development and deployment CLI
- Vitest: Fast unit testing framework
Quick Start
Prerequisites
# Required tools
- Node.js 18+
- npm/yarn/pnpm
- Cloudflare account
- Git
Installation
-
Create a new project from template:
git clone https://github.com/LubomirGeorgiev/cloudflare-workers-nextjs-saas-template.git my-saas-app cd my-saas-app -
Install dependencies:
npm install # or yarn install # or pnpm install -
Environment setup:
cp .env.example .env.local -
Configure environment variables:
# Cloudflare CLOUDFLARE_API_TOKEN=your_api_token CLOUDFLARE_ACCOUNT_ID=your_account_id # Database DATABASE_URL=your_d1_database_url # Auth NEXTAUTH_SECRET=your_secret NEXTAUTH_URL=http://localhost:3000 # Stripe (optional) STRIPE_SECRET_KEY=your_stripe_secret STRIPE_PUBLISHABLE_KEY=your_stripe_publishable -
Start development server:
npm run dev
Project Structure
├── app/ # Next.js App Router pages
│ ├── (auth)/ # Authentication routes
│ ├── (dashboard)/ # Protected dashboard routes
│ ├── api/ # API routes
│ └── globals.css # Global styles
├── components/ # Reusable React components
│ ├── ui/ # Base UI components
│ ├── forms/ # Form components
│ └── layout/ # Layout components
├── lib/ # Utility libraries
│ ├── auth.ts # Authentication configuration
│ ├── db.ts # Database configuration
│ └── utils.ts # Utility functions
├── prisma/ # Database schema and migrations
├── public/ # Static assets
├── workers/ # Cloudflare Workers
└── wrangler.toml # Cloudflare configuration
Authentication
The template includes a complete authentication system:
// Example: Protected API route
import { getUser } from '@/lib/auth'
export async function GET(request: Request) {
const user = await getUser(request)
if (!user) {
return new Response('Unauthorized', { status: 401 })
}
return Response.json({ user })
}
Features
- User Registration: Email/password with verification
- Login/Logout: Secure session management
- Password Reset: Email-based password recovery
- Social Auth: OAuth integration (Google, GitHub)
- Role-Based Access: Admin and user roles
Database Integration
Powered by Prisma and Cloudflare D1:
// Example: Database model
model User {
id String @id @default(cuid())
email String @unique
name String?
createdAt DateTime @default(now())
subscriptions Subscription[]
@@map("users")
}
Features
- Type-Safe Queries: Full TypeScript support
- Migrations: Automated database migrations
- Seeding: Database seeding for development
- Backup: Automated backup strategies
Payment Integration
Stripe integration for subscription management:
// Example: Create subscription
import { stripe } from '@/lib/stripe'
export async function createSubscription(
customerId: string,
priceId: string
) {
return await stripe.subscriptions.create({
customer: customerId,
items: [{ price: priceId }],
payment_behavior: 'default_incomplete',
expand: ['latest_invoice.payment_intent'],
})
}
Deployment
Cloudflare Pages
-
Connect your repository to Cloudflare Pages
-
Configure build settings:
Build command: npm run build Build output directory: .next -
Set environment variables in the Cloudflare dashboard
-
Deploy: Automatic deployments on git push
Manual Deployment
# Deploy to Cloudflare
npm run deploy
# Deploy with custom environment
npm run deploy:production
Configuration
Cloudflare Services
# wrangler.toml
name = "my-saas-app"
compatibility_date = "2024-01-01"
[vars]
ENVIRONMENT = "production"
[[d1_databases]]
binding = "DB"
database_name = "my-saas-db"
database_id = "your-database-id"
[[kv_namespaces]]
binding = "SESSIONS"
id = "your-kv-id"
Custom Domain
- Add your domain to Cloudflare
- Configure DNS settings
- Update environment variables
- Redeploy the application
Performance Optimization
- Edge Caching: Automatic caching at edge locations
- Image Optimization: Next.js Image component with Cloudflare
- Code Splitting: Automatic code splitting for optimal loading
- Compression: Gzip/Brotli compression enabled
- CDN: Global content delivery network
Security Features
- HTTPS Only: Enforced SSL/TLS encryption
- CSRF Protection: Cross-site request forgery prevention
- Rate Limiting: API rate limiting with Cloudflare
- Input Validation: Server-side input validation
- Secure Headers: Security headers configuration
Analytics & Monitoring
- Cloudflare Analytics: Built-in traffic and performance analytics
- Error Tracking: Comprehensive error logging
- Performance Monitoring: Core Web Vitals tracking
- User Analytics: Custom event tracking
Development Workflow
# Start development
npm run dev
# Run tests
npm run test
# Lint code
npm run lint
# Format code
npm run format
# Type check
npm run type-check
# Build for production
npm run build
# Preview production build
npm run preview
Contributing
We welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
Support
- Documentation: Full Documentation
- Issues: GitHub Issues
- Discussions: Community Discussions
License
This project is licensed under the MIT License - see the LICENSE file for details.
Ready to build your next SaaS application? Clone this template and start building with the power of Next.js and Cloudflare’s edge network!