Code without servers
With Lambda, you upload a function and AWS runs it on demand — zero to thousands of copies — and bills by the millisecond. API Gateway turns each HTTP request into an event object; your handler returns { statusCode, headers, body }. No servers to patch, but each request must stand alone.
A tiny router
const json = (statusCode, data) => ({ statusCode, headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) });
function createHandler(routes) {
const table = Object.entries(routes).map(([route, fn]) => {
const [method, path] = route.split(" ");
const names = [];
const pattern = new RegExp(`^${path.replace(/\{(\w+)\}/g, (_, name) => (names.push(name), "([^/]+)"))}$`);
return { method, pattern, names, fn };
});
return async (event) => {
for (const { method, pattern, names, fn } of table) {
const m = event.path.match(pattern);
if (!m || method !== event.httpMethod) continue;
let body = null;
try {
body = event.body ? JSON.parse(event.body) : null;
} catch {
return json(400, { error: "Invalid JSON" });
}
const params = Object.fromEntries(names.map((n, i) => [n, decodeURIComponent(m[i + 1])]));
try {
const [status, data] = await fn({ params, body, query: event.queryStringParameters ?? {}, event });
return json(status, data);
} catch {
return json(500, { error: "Internal error" }); // never leak stack traces
}
}
return json(404, { error: "Not found" });
};
}