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.4---56# Serverless Function Generator78## Prerequisites & Dependencies9- Node.js 18+ with npm or pnpm10- Cloudflare Wrangler (for Workers): `npm i -g wrangler` or AWS SAM/Serverless Framework (for Lambda)11- AWS CLI configured (for Lambda) or a Cloudflare account API token12- Optional: `npm i pino` for structured logging1314## Execution Steps151. Choose your target platform: Cloudflare Workers (JavaScript/TypeScript) or AWS Lambda (Node.js)162. Scaffold the project: `wrangler init my-worker` (Workers) or `mkdir my-lambda && cd my-lambda`173. Create the handler file: implement the core function with a consistent signature `(request) => Response`184. Add standardized CORS headers: `Access-Control-Allow-Origin: *`, `Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS`, `Access-Control-Allow-Headers: Content-Type, Authorization`195. 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)206. Add health check endpoint: `GET /healthz` that returns `200 OK` with `{ status: "ok" }`217. Deploy and test: `wrangler publish` (Workers) or `aws lambda create-function` (Lambda), then invoke and verify headers/body2223```javascript24// Cloudflare Worker: scaffolded handler with CORS and error handling25export default {26 async fetch(request, env, ctx) {27 // CORS preflight28 if (request.method === 'OPTIONS') {29 return new Response(null, {30 status: 200,31 headers: {32 'Access-Control-Allow-Origin': '*',33 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',34 'Access-Control-Allow-Headers': 'Content-Type, Authorization',35 },36 });37 }3839 try {40 const url = new URL(request.url);41 // Health check42 if (url.pathname === '/healthz') {43 return new Response(JSON.stringify({ status: 'ok' }), {44 headers: { 'Content-Type': 'application/json' },45 status: 200,46 });47 }4849 // Example route handling50 if (request.method === 'GET' && url.pathname === '/api/time') {51 return new Response(JSON.stringify({ time: new Date().toISOString() }), {52 headers: { 'Content-Type': 'application/json' },53 status: 200,54 });55 }5657 // 404 fallback58 return new Response('Not Found', { status: 404 });59 } catch (error) {60 // Structured error response61 return new Response(62 JSON.stringify({ error: 'Internal Server Error', message: error.message }),63 {64 headers: { 'Content-Type': 'application/json' },65 status: 500,66 }67 );68 }69 },70};71```7273```bash74# Deploy Cloudflare Worker75wrangler publish7677# Or deploy AWS Lambda with SAM78sam build79sam deploy --guided80```