REST API Design & Middleware

Difficulty: Intermediate

Question

How do you design a production-ready REST API in Node.js? Walk through the request lifecycle, middleware, validation, and error handling.

Answer

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.

Resource and URL design

The middleware pipeline

Order matters, because Express runs middleware in registration order:

  1. helmet() for security headers, cors() with an explicit origin allowlist.
  2. express.json({ limit: '100kb' }) so huge bodies cannot exhaust memory.
  3. Request ID and structured logging (pino-http).
  4. Rate limiting on public and auth routes.
  5. Route-level authenticate, authorize(role), validate(schema).
  6. The controller.
  7. A 404 handler, then the error handler (four arguments: err, req, res, next) registered last.

Layering: controller, service, repository

This separation lets you reuse the same service from a REST route, a queue consumer, or a cron job.

Error handling and validation

Production concerns beyond the code

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.

Request lifecycle in a layered Express API. Each layer has one job, and any error jumps straight to the central handler.
  1. Global middleware: helmet, CORS, JSON parser, logging, rate limit.
  2. Route middleware: Authenticate, authorize, validate input.
  3. Controller: Maps the HTTP request to a service call.
  4. Service: Business rules, framework independent.
  5. Repository / DB: Prisma or SQL queries.
  6. Error handler: Maps thrown errors to status codes and JSON.

Code examples

Wiring a production Express app (Express 5)

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.

Route, validation, controller, and service

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.

Key points

Common follow-up questions

Interview tips

Concepts covered

REST, Middleware Chain, Layered Architecture, Centralized Error Handling, Request Validation, Idempotency

More Node.js Interview questions