# REST API Design & Middleware

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

Canonical: https://www.internhack.in/learn/interview/nodejs-interview/node-rest-api-design
Last updated: 2026-11-28

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

- Use nouns and HTTP verbs: `GET /orders`, `POST /orders`, `GET /orders/:id`, `PATCH /orders/:id`, `DELETE /orders/:id`.
- Nest only one level for ownership: `GET /users/:id/orders`.
- Version the API (`/api/v1`) so you can change contracts without breaking mobile apps that update slowly.
- Return correct status codes: `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.
- Paginate list endpoints (cursor-based for large or fast-changing tables) and cap `limit`.
- For payments and other money operations, support an `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.

### 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

- **Controller**: reads `req`, calls a service, shapes the response. No SQL, no business rules.
- **Service**: business logic ("an order can be cancelled only before dispatch"). Framework-agnostic, so it is easy to unit test.
- **Repository / ORM**: data access via Prisma, Drizzle, or raw SQL.

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

### Error handling and validation

- Validate `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.
- Throw typed errors (`NotFoundError`, `ConflictError`) from services and let the central handler map them to responses.
- Express 5 (stable since late 2024) forwards rejected promises from `async` handlers to the error handler automatically. On Express 4 you need `try/catch` with `next(err)` or a wrapper.
- Never leak stack traces or database messages to clients; log them with the request ID instead.

### 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

- Middleware runs in registration order; the error handler has four parameters and goes last.
- Keep controllers thin and put business rules in a framework-agnostic service layer.
- Validate body, params and query at the edge and use the parsed output.
- Use correct status codes, versioned URLs, pagination, and a consistent error JSON shape.
- Express 5 forwards async errors automatically; Express 4 needs try/catch or a wrapper.

## Common follow-up questions

- How would you implement idempotency for a payment creation endpoint?
- Cursor vs offset pagination: when would you choose each?
- How do you version an API without breaking existing mobile clients?
- What is the difference between app.use() and app.get() in terms of path matching?
- How would you generate and keep an OpenAPI spec in sync with your code?

## Interview tips

- Describe the request lifecycle end to end in order; interviewers want to see that you think in layers.
- Mention at least one production detail beyond CRUD: idempotency keys, rate limits, request IDs, or graceful shutdown.
- If you have built an API, explain one design decision you would change now and why.

## Concepts covered

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

Previous: [Streams & Buffers](https://www.internhack.in/learn/interview/nodejs-interview/node-streams-buffers) · Next: [Node.js Basics & Runtime](https://www.internhack.in/learn/interview/nodejs-interview/node-basics-runtime) · [All of Node.js Interview](https://www.internhack.in/learn/interview/nodejs-interview)

## More Node.js Interview questions

- [Module System (CJS vs ESM)](https://www.internhack.in/learn/interview/nodejs-interview/node-module-system)
- [File System Operations](https://www.internhack.in/learn/interview/nodejs-interview/node-fs-operations)
- [Path & OS Modules](https://www.internhack.in/learn/interview/nodejs-interview/node-path-os)
- [HTTP Module & Server Creation](https://www.internhack.in/learn/interview/nodejs-interview/node-http-server)
- [Express.js Fundamentals](https://www.internhack.in/learn/interview/nodejs-interview/node-express-fundamentals)
- [Routing & Route Parameters](https://www.internhack.in/learn/interview/nodejs-interview/node-routing-params)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Node.js Interview](https://www.internhack.in/learn/interview/nodejs-interview)
