A production-ready template for building serverless APIs with Cloudflare Pages Functions.
- 🚀 Edge Functions - Server-side code that runs at the edge
- 📁 File-based Routing - Automatic route generation from file structure
- 🔷 TypeScript Support - Full type safety and IntelliSense
- 🛠️ Middleware - Global request/response processing
- 🔒 CORS Configured - Ready for cross-origin requests
- 📝 Well Documented - Clear examples and patterns
``` /functions /_middleware.ts # Global middleware for all routes /types.d.ts # TypeScript definitions /api /hello.ts # GET /api/hello /time.ts # GET /api/time /echo.ts # POST /api/echo /user /[id].ts # GET/PUT /api/user/:id (dynamic route) ```
Simple greeting endpoint.
Response: ```json { "message": "Hello from Cloudflare Pages Functions!", "timestamp": "2024-01-15T12:00:00.000Z" } ```
Returns current server time with optional format parameter.
Query Parameters:
- `format` - Time format: `iso` (default), `unix`, or `utc`
Response: ```json { "time": "2024-01-15T12:00:00.000Z", "format": "iso", "timezone": "UTC" } ```
Echoes back the request body.
Request Body: ```json { "message": "Hello" } ```
Response: ```json { "success": true, "echo": { "message": "Hello" }, "receivedAt": "2024-01-15T12:00:00.000Z" } ```
Retrieves user by ID (dynamic route example).
Response: ```json { "success": true, "user": { "id": "123", "name": "User 123", "email": "user123@example.com", "createdAt": "2024-01-15T12:00:00.000Z" } } ```
- Node.js 18+ installed
- Cloudflare account (for deployment)
```bash
npm install
npm run dev ```
Visit http://localhost:3000 to see the app.
- Push your code to GitHub
- Go to Cloudflare Dashboard
- Navigate to Pages
- Click "Create a project" → "Connect to Git"
- Select your repository
- Cloudflare will automatically detect Next.js and deploy
```bash
npm install -g wrangler
wrangler login
wrangler pages deploy ```
To add environment variables:
- Go to Cloudflare Dashboard → Pages → Your Project
- Navigate to Settings → Environment Variables
- Add your variables for Production/Preview environments
Access them in your functions: ```typescript export async function onRequestGet(context: EventContext<CloudflareEnv, string, unknown>) { const apiKey = context.env.API_KEY // Use the variable } ```
Create a new file in `/functions/api/`:
```typescript // /functions/api/new-route.ts
export async function onRequestGet(context: EventContext<unknown, string, unknown>) { return new Response( JSON.stringify({ message: 'New route!' }), { headers: { 'Content-Type': 'application/json' } } ) } ```
The route will automatically be available at `/api/new-route`.
MIT