Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Comprehensive Cloudflare platform skill covering Workers, D1, R2, KV, AI, Durable Objects, and security.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/workers-playground/patterns.md
1# Workers Playground Patterns23## JSON API45```javascript6export default {7async fetch(request) {8const url = new URL(request.url);9if (url.pathname === '/api/hello') return Response.json({ message: 'Hello' });10if (url.pathname === '/api/echo' && request.method === 'POST') {11return Response.json({ received: await request.json() });12}13return Response.json({ error: 'Not found' }, { status: 404 });14}15};16```1718## Router Pattern1920```javascript21const routes = {22'/': () => new Response('Home'),23'/api/users': () => Response.json([{ id: 1, name: 'Alice' }])24};2526export default {27async fetch(request) {28const handler = routes[new URL(request.url).pathname];29return handler ? handler() : new Response('Not Found', { status: 404 });30}31};32```3334## Proxy Pattern3536```javascript37export default {38async fetch(request) {39const url = new URL(request.url);40url.hostname = 'api.example.com';41return fetch(url.toString(), {42method: request.method, headers: request.headers, body: request.body43});44}45};46```4748## CORS Handling4950```javascript51export default {52async fetch(request) {53if (request.method === 'OPTIONS') {54return new Response(null, {55headers: {56'Access-Control-Allow-Origin': '*',57'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',58'Access-Control-Allow-Headers': 'Content-Type, Authorization'59}60});61}62const response = await fetch('https://api.example.com', request);63const modified = new Response(response.body, response);64modified.headers.set('Access-Control-Allow-Origin', '*');65return modified;66}67};68```6970## Caching7172```javascript73export default {74async fetch(request) {75if (request.method !== 'GET') return fetch(request);76const cache = caches.default;77let response = await cache.match(request);78if (!response) {79response = await fetch('https://api.example.com');80if (response.status === 200) await cache.put(request, response.clone());81}82return response;83}84};85```8687## Hono Framework8889```javascript90import { Hono } from 'https://esm.sh/hono@3';91const app = new Hono();92app.get('/', (c) => c.text('Hello'));93app.get('/api/users/:id', (c) => c.json({ id: c.req.param('id') }));94app.notFound((c) => c.json({ error: 'Not found' }, 404));95export default app;96```9798## Authentication99100```javascript101export default {102async fetch(request) {103const auth = request.headers.get('Authorization');104if (!auth?.startsWith('Bearer ')) {105return Response.json({ error: 'Unauthorized' }, { status: 401 });106}107const token = auth.substring(7);108if (token !== 'secret-token') {109return Response.json({ error: 'Invalid token' }, { status: 403 });110}111return Response.json({ message: 'Authenticated' });112}113};114```115116## Error Handling117118```javascript119export default {120async fetch(request) {121try {122const response = await fetch('https://api.example.com');123if (!response.ok) throw new Error(`API returned ${response.status}`);124return response;125} catch (error) {126return Response.json({ error: error.message }, { status: 500 });127}128}129};130```131132**Note:** In-memory state (Maps, variables) resets on Worker cold start. Use Durable Objects or KV for persistence.133