All skills
openai avatar

/cloudflare-deploy

@bf9e226 official
by openaiopenai/skills28k stars
1,891

Deploy 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.

Use this Skill: https://skilld.dev/gh/openai/skills/cloudflare-deploy

This session only. Nothing lands on disk.

referencespages-functionspatterns.md

≈1.1k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Common Patterns

Background Tasks (waitUntil)

Non-blocking tasks after response sent (analytics, cleanup, webhooks):

export async function onRequest(ctx: EventContext<Env>) {
  const res = Response.json({ success: true });
  
  ctx.waitUntil(ctx.env.KV.put('last-visit', new Date().toISOString()));
  ctx.waitUntil(Promise.all([
    ctx.env.ANALYTICS.writeDataPoint({ event: 'view' }),
    fetch('https://webhook.site/...', { method: 'POST' })
  ]));
  
  return res; // Returned immediately
}

Middleware & Auth

// functions/_middleware.js (global) or functions/users/_middleware.js (scoped)
export async function onRequest(ctx) {
  try { return await ctx.next(); } 
  catch (err) { return new Response(err.message, { status: 500 }); }
}

// Chained: export const onRequest = [errorHandler, auth, logger];

// Auth
async function auth(ctx: EventContext<Env>) {
  const token = ctx.request.headers.get('authorization')?.replace('Bearer ', '');
  if (!token) return new Response('Unauthorized', { status: 401 });
  const session = await ctx.env.KV.get(`session:${token}`);
  if (!session) return new Response('Invalid', { status: 401 });
  ctx.data.user = JSON.parse(session);
  return ctx.next();
}

CORS & Rate Limiting

// CORS middleware
const cors = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST' };
export async function onRequestOptions() { return new Response(null, { headers: cors }); }
export async function onRequest(ctx) {
  const res = await ctx.next();
  Object.entries(cors).forEach(([k, v]) => res.headers.set(k, v));
  return res;
}

// Rate limiting (KV-based)
async function rateLimit(ctx: EventContext<Env>) {
  const ip = ctx.request.headers.get('CF-Connecting-IP') || 'unknown';
  const count = parseInt(await ctx.env.KV.get(`rate:${ip}`) || '0');
  if (count >= 100) return new Response('Rate limited', { status: 429 });
  await ctx.env.KV.put(`rate:${ip}`, (count + 1).toString(), { expirationTtl: 3600 });
  return ctx.next();
}

Forms, Caching, Redirects

// JSON & file upload
export async function onRequestPost(ctx) {
  const ct = ctx.request.headers.get('content-type') || '';
  if (ct.includes('application/json')) return Response.json(await ctx.request.json());
  if (ct.includes('multipart/form-data')) {
    const file = (await ctx.request.formData()).get('file') as File;
    await ctx.env.BUCKET.put(file.name, file.stream());
    return Response.json({ uploaded: file.name });
  }
}

// Cache API
export async function onRequest(ctx) {
  let res = await caches.default.match(ctx.request);
  if (!res) {
    res = new Response('Data');
    res.headers.set('Cache-Control', 'public, max-age=3600');
    ctx.waitUntil(caches.default.put(ctx.request, res.clone()));
  }
  return res;
}

// Redirects
export async function onRequest(ctx) {
  if (new URL(ctx.request.url).pathname === '/old') {
    return Response.redirect(new URL('/new', ctx.request.url), 301);
  }
  return ctx.next();
}

Testing

Unit tests (Vitest + cloudflare:test):

import { env } from 'cloudflare:test';
import { it, expect } from 'vitest';
import { onRequest } from '../functions/api';

it('returns JSON', async () => {
  const req = new Request('http://localhost/api');
  const ctx = { request: req, env, params: {}, data: {} } as EventContext;
  const res = await onRequest(ctx);
  expect(res.status).toBe(200);
});

Integration: wrangler pages dev + Playwright/Cypress

Advanced Mode (_worker.js)

Use _worker.js for complex routing (replaces /functions):

interface Env { ASSETS: Fetcher; KV: KVNamespace; }

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    if (url.pathname.startsWith('/api/')) {
      return Response.json({ data: await env.KV.get('key') });
    }
    return env.ASSETS.fetch(request); // Static files
  }
} satisfies ExportedHandler<Env>;

When: Existing Worker, framework-generated (Next.js/SvelteKit), custom routing logic

See also: api.md for env.ASSETS.fetch() | gotchas.md for debugging

Source: SKILL.md on GitHub

2 warnings17d5 checks · Risk SAFE
  • Gen Agent Trust Hub17d

    This skill provides comprehensive guidance for deploying and managing infrastructure on the Cloudflare platform. It includes extensive educational material on secure development practices, such as preventing SQL injection and managing secrets effectively. No malicious patterns or security risks were identified.

  • Socket17d

    2 alerts: gptAnomaly

  • Snyk17d

    Risk: LOW · No issues

  • Runlayer7mo

    310/310 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at bf9e226. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Activeupdated 8 months ago

README badge

README badge for openai/skills/cloudflare-deploy

Deploys applications and infrastructure to Cloudflare's platform, including Workers, Pages, D1, R2, Durable Objects, KV, and other services. Use decision trees to route to the right Cloudflare product based on compute, storage, AI, networking, security, or media needs.

Generated from the current SKILL.md.

Does this skill cover all Cloudflare products?
The skill is a consolidated index covering compute, storage, AI, networking, security, media, and developer tools on Cloudflare. It uses decision trees to route you to the right product reference, then loads detailed guidance for that product.
What authentication is required before deploying?
Run `npx wrangler whoami` to check if authenticated. For local deployment, use `wrangler login` (one-time OAuth). For CI/CD, set the `CLOUDFLARE_API_TOKEN` environment variable.
What should I do if deployment fails due to network issues?
Rerun the deploy with `sandbox_permissions=require_escalated` to grant elevated network access, which is required for outbound requests to Cloudflare during deployment.
How long does a Cloudflare deployment typically take?
Deployments may take several minutes. Use appropriate timeout values in your configuration or CI/CD environment.

Generated from the current SKILL.md. These answers refresh after source changes.