Difficulty: Intermediate
How do you design a production-ready REST API in Node.js? Walk through the request lifecycle, middleware, validation, and error handling.
A production REST API in Node.js is a layered pipeline: global middleware (security headers, CORS, body parsing, logging), then per-route middleware (auth, validation), then a thin controller that calls a service layer, which talks to the database. Errors from any layer flow to one centralized error handler that returns a consistent JSON shape and the correct HTTP status code.
GET /orders, POST /orders, GET /orders/:id, PATCH /orders/:id, DELETE /orders/:id.GET /users/:id/orders./api/v1) so you can change contracts without breaking mobile apps that update slowly.201 with a Location header on create, 204 on delete, 400 for bad input, 401 unauthenticated, 403 forbidden, 404, 409 conflict, 422 semantic validation errors, 429 rate limited.limit.Idempotency-Key header on POST so a retried request from a flaky mobile network does not charge the user twice. Razorpay and Stripe both use this pattern.Order matters, because Express runs middleware in registration order:
helmet() for security headers, cors() with an explicit origin allowlist.express.json({ limit: '100kb' }) so huge bodies cannot exhaust memory.authenticate, authorize(role), validate(schema).err, req, res, next) registered last.req, calls a service, shapes the response. No SQL, no business rules.This separation lets you reuse the same service from a REST route, a queue consumer, or a cron job.
body, params, and query at the boundary with Zod (or Joi), and use the parsed output, not the raw input, so unknown fields are stripped.NotFoundError, ConflictError) from services and let the central handler map them to responses.async handlers to the error handler automatically. On Express 4 you need try/catch with next(err) or a wrapper.Health endpoints (/healthz, /readyz), graceful shutdown on SIGTERM, timeouts on outgoing calls, an OpenAPI spec generated from your schemas, and consistent error bodies like { "error": { "code": "ORDER_NOT_FOUND", "message": "..." } } that frontend and mobile teams can rely on.
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const pinoHttp = require('pino-http');
const { ordersRouter } = require('./routes/orders');
const app = express();
app.use(helmet());
app.use(cors({ origin: ['https://app.example.in'], credentials: true }));
app.use(express.json({ limit: '100kb' }));
app.use(pinoHttp());
app.get('/healthz', (req, res) => res.send('ok'));
app.use('/api/v1/orders', ordersRouter);
// 404 for unmatched routes
app.use((req, res) => {
res.status(404).json({ error: { code: 'NOT_FOUND', message: 'Route not found' } });
});
// Central error handler: must have 4 params and be registered last
app.use((err, req, res, next) => {
const status = err.statusCode ?? 500;
req.log.error({ err }, 'request failed');
res.status(status).json({
error: {
code: err.code ?? 'INTERNAL',
message: status < 500 ? err.message : 'Something went wrong',
},
});
});
module.exports = app;
Global middleware runs first, routes are versioned and mounted on a router, and the 404 and error handlers are registered last. In Express 5 an async handler that throws or rejects reaches the error handler without try/catch.
const { z } = require('zod');
const router = require('express').Router();
class AppError extends Error {
constructor(message, statusCode, code) {
super(message);
this.statusCode = statusCode;
this.code = code;
}
}
const validate = (schema) => (req, res, next) => {
const result = schema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({
error: { code: 'VALIDATION_FAILED', details: result.error.issues },
});
}
req.body = result.data; // use parsed, stripped data
next();
};
const createOrder = z.object({
productId: z.string().min(1),
quantity: z.number().int().min(1).max(10),
});
// service layer: no req/res here
async function getOrder(id, userId) {
const order = await db.order.findFirst({ where: { id, userId } });
if (!order) throw new AppError('Order not found', 404, 'ORDER_NOT_FOUND');
return order;
}
router.get('/:id', authenticate, async (req, res) => {
res.json(await getOrder(req.params.id, req.user.id));
});
router.post('/', authenticate, validate(createOrder), async (req, res) => {
const order = await db.order.create({ data: { ...req.body, userId: req.user.id } });
res.status(201).location(`/api/v1/orders/${order.id}`).json(order);
});
module.exports = { ordersRouter: router };
The route composes middleware, the controller stays thin, and the service throws a typed error that the central handler converts into a 404. safeParse keeps validation errors as a 400 with field details.
REST, Middleware Chain, Layered Architecture, Centralized Error Handling, Request Validation, Idempotency