davila7/claude-code-templates / cli-tool/components/skills/development/cloudflare-deploy
cloudflare-deploy
FlaggedDeploy applications and infrastructure to Cloudflare using Workers, Pages, and related platform services. Use when the user asks to deploy, host, publish, or set up a project on Cloudflare.
references/pages/api.md
View on GitHub# Functions API
## File-Based Routing
```
/functions/index.ts → example.com/
/functions/api/users.ts → example.com/api/users
/functions/api/users/[id].ts → example.com/api/users/:id
/functions/api/users/[[path]].ts → example.com/api/users/* (catchall)
/functions/_middleware.ts → Runs before all routes
```
**Rules**: `[param]` = single segment, `[[param]]` = multi-segment catchall, more specific wins.
## Request Handlers
```typescript
import type { PagesFunction } from '@cloudflare/workers-types';
interface Env {
DB: D1Database;
KV: KVNamespace;
}
// All methods
export const onRequest: PagesFunction<Env> = async (context) => {
return new Response('All methods');
};
// Method-specific
export const onRequestGet: PagesFunction<Env> = async (context) => {
const { request, env, params, data } = context;
const user = await env.DB.prepare(
'SELECT * FROM users WHERE id = ?'
).bind(params.id).first();
return Response.json(user);
};
export const onRequestPost: PagesFunction<Env> = async (context) => {
const body = await context.request.json();
return Response.json({ success: true });
};
// Also: onRequestPut, onRequestPatch, onRequestDelete, onRequestHead, onRequestOptions
```
## Context Object
```typescript
interface EventContext<Env, Params, Data> {
request: Request; // HTTP request
env: Env; // Bindings (KV, D1, R2, etc.)
params: Params; // Route parameters
data: Data; // Middleware-shared data
waitUntil: (promise: Promise<any>) => void; // Background tasks
next: () => Promise<Response>; // Next handler
passThroughOnException: () => void; // Error fallback (not in advanced mode)
}
```
## Dynamic Routes
```typescript
// Single segment: functions/users/[id].ts
export const onRequestGet: PagesFunction = async ({ params }) => {
// /users/123 → params.id = "123"
return Response.json({ userId: params.id });
};
// Multi-segment: functions/files/[[path]].ts
export const onRequestGet: PagesFunction = async ({ params }) => {
// /files/docs/api/v1.md → params.path = ["docs", "api", "v1.md"]
const filePath = (params.path as string[]).join('/');
return new Response(filePath);
};
```
## Middleware
```typescript
// functions/_middleware.ts
// Single
export const onRequest: PagesFunction = async (context) => {
const response = await context.next();
response.headers.set('X-Custom-Header', 'value');
return response;
};
// Chained (runs in order)
const errorHandler: PagesFunction = async (context) => {
try {
return await context.next();
} catch (err) {
return new Response(err.message, { status: 500 });
}
};
const auth: PagesFunction = async (context) => {
const token = context.request.headers.get('Authorization');
if (!token) return new Response('Unauthorized', { status: 401 });
context.data.userId = await verifyToken(token);
return context.next();
};
export const onRequest = [errorHandler, auth];
```
**Scope**: `functions/_middleware.ts` → all; `functions/api/_middleware.ts` → `/api/*` only
## Bindings Usage
```typescript
export const onRequestGet: PagesFunction<Env> = async ({ env }) => {
// KV
const cached = await env.KV.get('key', 'json');
await env.KV.put('key', JSON.stringify({data: 'value'}), {expirationTtl: 3600});
// D1
const result = await env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(userId).first();
// R2, Queue, AI - see respective reference docs
return Response.json({success: true});
};
```
## Advanced Mode
Full Workers API, bypasses file-based routing:
```javascript
// functions/_worker.js
export default {
async fetch(request, env, ctx) {
const url = new URL(request.url);
// Custom routing
if (url.pathname.startsWith('/api/')) {
return new Response('API response');
}
// REQUIRED: Serve static assets
return env.ASSETS.fetch(request);
}
};
```
**When to use**: WebSockets, complex routing, scheduled handlers, email handlers.
## Smart Placement
Automatically optimizes function execution location based on traffic patterns.
**Configuration** (in wrangler.jsonc):
```jsonc
{
"placement": {
"mode": "smart" // Enables optimization (default: off)
}
}
```
**How it works**: Analyzes traffic patterns over time and places functions closer to users or data sources (e.g., D1 databases). Requires no code changes.
**Trade-offs**: Initial requests may see slightly higher latency during learning period (hours-days). Performance improves as system optimizes.
**When to use**: Global apps with centralized databases or geographically concentrated traffic sources.
## getRequestContext (Framework SSR)
Access bindings in framework code:
```typescript
// SvelteKit
import type { RequestEvent } from '@sveltejs/kit';
export async function load({ platform }: RequestEvent) {
const data = await platform.env.DB.prepare('SELECT * FROM users').all();
return { users: data.results };
}
// Astro
const { DB } = Astro.locals.runtime.env;
const data = await DB.prepare('SELECT * FROM users').all();
// Solid Start (server function)
import { getRequestEvent } from 'solid-js/web';
const event = getRequestEvent();
const data = await event.locals.runtime.env.DB.prepare('SELECT * FROM users').all();
```
**✅ Supported adapters** (2026):
- **SvelteKit**: `@sveltejs/adapter-cloudflare`
- **Astro**: Built-in Cloudflare adapter
- **Nuxt**: Set `nitro.preset: 'cloudflare-pages'` in `nuxt.config.ts`
- **Qwik**: Built-in Cloudflare adapter
- **Solid Start**: `@solidjs/start-cloudflare-pages`
**❌ Deprecated/Unsupported**:
- **Next.js**: Official adapter (`@cloudflare/next-on-pages`) deprecated. Use Vercel or self-host on Workers.
- **Remix**: Official adapter (`@remix-run/cloudflare-pages`) deprecated. Migrate to supported frameworks.
See [gotchas.md](./gotchas.md#framework-specific) for migration guidance.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| writing-skillsobra/superpowersUse when creating new skills, editing existing skills, or verifying skills work before deployment | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| xlsxanthropics/skillsUse this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing .xlsx, .xlsm, .xltx, .csv, or .tsv file (e.g., adding columns, computing formulas, formatting, charting, cleaning messy data); create a new spreadsheet from scratch or from other data sources; or convert between tabular file formats. Trigger especially when the user references a spreadsheet file by name or path — even casually (like "the xlsx in my downloads") — and wants something done to it or produced from it. Also trigger for cleaning or restructuring messy tabular data files (malformed rows, misplaced headers, junk data) into proper spreadsheets. The deliverable must be a spreadsheet file. Do NOT trigger when the primary deliverable is a Word document, HTML report, standalone Python script, database pipeline, or Google Sheets API integration, even if tabular data is involved. | Stars: 197k | Updated | Claude CodeCodex | Verified | Install |
| shipping-and-launchaddyosmani/agent-skillsPrepares production launches. Use when preparing to deploy to production, or when asking what needs to be in place before shipping. Use when you need a pre-launch checklist, when setting up monitoring, when planning a staged rollout, or when you need a rollback strategy. | Stars: 119k | Updated | Claude CodeCodex | Verified | Install |
| childhoodthedotmack/claude-memBabysit a shipped release after merge, publication, or deployment. Verify published packages, production behavior, installed plugins, and late CI or user reports until the observation window is clean; use babysit for PR readiness before release. | Stars: 118k | Updated | Claude CodeCodex | Verified | Install |