Serverless Function Generator
Prerequisites & Dependencies
- Node.js 18+ with npm or pnpm
- Cloudflare Wrangler (for Workers):
npm i -g wrangler or AWS SAM/Serverless Framework (for Lambda)
- AWS CLI configured (for Lambda) or a Cloudflare account API token
- Optional:
npm i pino for structured logging
Execution Steps
- Choose your target platform: Cloudflare Workers (JavaScript/TypeScript) or AWS Lambda (Node.js)
- Scaffold the project:
wrangler init my-worker (Workers) or mkdir my-lambda && cd my-lambda
- Create the handler file: implement the core function with a consistent signature
(request) => Response
- Add standardized CORS headers:
Access-Control-Allow-Origin: *, Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, Access-Control-Allow-Headers: Content-Type, Authorization
- Implement error handling: wrap logic in
try/catch, return structured JSON error responses with statusCode and body, and set appropriate HTTP status codes (400, 401, 404, 500)
- Add health check endpoint:
GET /healthz that returns 200 OK with { status: "ok" }
- Deploy and test:
wrangler publish (Workers) or aws lambda create-function (Lambda), then invoke and verify headers/body
// Cloudflare Worker: scaffolded handler with CORS and error handling
export default {
async fetch(request, env, ctx) {
// CORS preflight
if (request.method === 'OPTIONS') {
return new Response(null, {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
});
}
try {
const url = new URL(request.url);
// Health check
if (url.pathname === '/healthz') {
return new Response(JSON.stringify({ status: 'ok' }), {
headers: { 'Content-Type': 'application/json' },
status: 200,
});
}
// Example route handling
if (request.method === 'GET' && url.pathname === '/api/time') {
return new Response(JSON.stringify({ time: new Date().toISOString() }), {
headers: { 'Content-Type': 'application/json' },
status: 200,
});
}
// 404 fallback
return new Response('Not Found', { status: 404 });
} catch (error) {
// Structured error response
return new Response(
JSON.stringify({ error: 'Internal Server Error', message: error.message }),
{
headers: { 'Content-Type': 'application/json' },
status: 500,
}
);
}
},
};
# Deploy Cloudflare Worker
wrangler publish
# Or deploy AWS Lambda with SAM
sam build
sam deploy --guided
1---2name: serverless-function-generator3description: Scaffold lightweight serverless handlers for Cloudflare Workers or AWS Lambda with standard CORS and error handling.4metadata:5 source: skills/serverless-function-generator/serverless-function-generator.md6---78# Serverless Function Generator910## Prerequisites & Dependencies11- Node.js 18+ with npm or pnpm12- Cloudflare Wrangler (for Workers): `npm i -g wrangler` or AWS SAM/Serverless Framework (for Lambda)13- AWS CLI configured (for Lambda) or a Cloudflare account API token14- Optional: `npm i pino` for structured logging1516## Execution Steps171. Choose your target platform: Cloudflare Workers (JavaScript/TypeScript) or AWS Lambda (Node.js)182. Scaffold the project: `wrangler init my-worker` (Workers) or `mkdir my-lambda && cd my-lambda`193. Create the handler file: implement the core function with a consistent signature `(request) => Response`204. Add standardized CORS headers: `Access-Control-Allow-Origin: *`, `Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS`, `Access-Control-Allow-Headers: Content-Type, Authorization`215. Implement error handling: wrap logic in `try/catch`, return structured JSON error responses with `statusCode` and `body`, and set appropriate HTTP status codes (400, 401, 404, 500)226. Add health check endpoint: `GET /healthz` that returns `200 OK` with `{ status: "ok" }`237. Deploy and test: `wrangler publish` (Workers) or `aws lambda create-function` (Lambda), then invoke and verify headers/body2425```javascript26// Cloudflare Worker: scaffolded handler with CORS and error handling27export default {28 async fetch(request, env, ctx) {29 // CORS preflight30 if (request.method === 'OPTIONS') {31 return new Response(null, {32 status: 200,33 headers: {34 'Access-Control-Allow-Origin': '*',35 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',36 'Access-Control-Allow-Headers': 'Content-Type, Authorization',37 },38 });39 }4041 try {42 const url = new URL(request.url);43 // Health check44 if (url.pathname === '/healthz') {45 return new Response(JSON.stringify({ status: 'ok' }), {46 headers: { 'Content-Type': 'application/json' },47 status: 200,48 });49 }5051 // Example route handling52 if (request.method === 'GET' && url.pathname === '/api/time') {53 return new Response(JSON.stringify({ time: new Date().toISOString() }), {54 headers: { 'Content-Type': 'application/json' },55 status: 200,56 });57 }5859 // 404 fallback60 return new Response('Not Found', { status: 404 });61 } catch (error) {62 // Structured error response63 return new Response(64 JSON.stringify({ error: 'Internal Server Error', message: error.message }),65 {66 headers: { 'Content-Type': 'application/json' },67 status: 500,68 }69 );70 }71 },72};73```7475```bash76# Deploy Cloudflare Worker77wrangler publish7879# Or deploy AWS Lambda with SAM80sam build81sam deploy --guided82```