Building a REST API with Node.js and Express: From Scratch to Production
Step-by-step tutorial building a production REST API with Node.js and Express. Covers routing, middleware, CORS, input validation, and error handling.
By Cometflow API Engineering Team • Updated 2026-10-06
Express remains one of the most widely deployed Node.js web frameworks. Taking an Express HTTP API from a prototype to production requires strict request body size limits, schema validation, centralized error middleware, and graceful shutdown handlers.
1. Production Express Server Blueprint (TypeScript)
import express, { Request, Response, NextFunction } from 'express';
const app = express();
app.disable('x-powered-by');
app.use(express.json({ limit: '100kb' })); // Prevent memory exhaustion payloads
app.get('/api/v1/health', (_req: Request, res: Response) => {
res.status(200).json({ status: 'ok', timestamp: new Date().toISOString() });
});
// Centralized Error Handling Middleware (4 arguments required)
app.use((err: Error, _req: Request, res: Response, _next: NextFunction) => {
console.error('[API Error]', err.message);
res.status(500).json({ error: 'internal_server_error', message: 'An unexpected error occurred.' });
});
Frequently Asked Questions (FAQ)
Why should I cap express.json({ limit })?
Without a strict payload limit, an attacker can send multi-megabyte deeply nested JSON bodies that block the single-threaded Node.js event loop during JSON.parse().