Polski

Tutorial · Express · TypeScript

REST API with Express 5 and TypeScript – from an empty folder to production

We build the order API of a pierogi shop with Express 5 and TypeScript – Zod-validated configuration, routing, request validation, centralized error handling, async handlers, pino logs, CORS, Helmet, rate limiting, tests with supertest and a Docker image.

By · · 23 min read

Express is well over a decade old and still the most popular HTTP framework for Node.js. Version 5 removed its biggest pain point – catching errors from async functions by hand – and cleaned up the route path syntax. In this tutorial you will build an order API for Halina's pierogi shop from scratch, the way production services are built: with validation, a consistent error format, searchable logs and tests that do not need an open port.

Prerequisites: Node.js 22.12+ (24 LTS recommended), TypeScript basics (types, unions, async/await – see the TypeScript tutorial), HTTP at the level of "method, path, status, headers".

5
Express version – stable since 2024, `latest` on npm since 2025
0
`try/catch` in handlers – async errors reach the middleware
4
layers – router → service → repository → domain
17
files in the ZIP – including tests and the Dockerfile
Diagram: A request's path through the app – middleware order matters

Step 1. The project: ESM, TypeScript and scripts

We start with an empty folder. Dependencies fall into three groups: Express itself with middleware, Zod and pino, and the developer tooling.

mkdir pierogi-api && cd pierogi-api
npm init -y && npm pkg set type=module
npm install express zod pino pino-http helmet cors express-rate-limit
npm install -D typescript tsx vitest supertest pino-pretty @types/node @types/express @types/cors @types/supertest

Project configuration

package.json
{
  "name": "pierogi-api",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "engines": { "node": ">=22.12" },
  "scripts": {
    "dev": "tsx watch --env-file-if-exists=.env src/server.ts",
    "build": "tsc -p tsconfig.build.json",
    "start": "node --env-file-if-exists=.env dist/server.js",
    "typecheck": "tsc --noEmit",
    "test": "vitest run"
  },
  "dependencies": {
    "cors": "^2.8.6",
    "express": "^5.3.0",
    "express-rate-limit": "^8.7.5",
    "helmet": "^8.3.0",
    "pino": "^10.4.0",
    "pino-http": "^11.0.0",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@types/cors": "^2.8.19",
    "@types/express": "^5.0.6",
    "@types/node": "^24.19.4",
    "@types/supertest": "^7.2.1",
    "pino-pretty": "^13.2.0",
    "supertest": "^7.3.2",
    "tsx": "^4.23.15",
    "typescript": "^7.0.2",
    "vitest": "^5.1.2"
  }
}
tsconfig.json
{
  "compilerOptions": {
    "target": "ES2024",
    "module": "nodenext",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true,
    "sourceMap": true,
    "noEmit": true,
    "types": ["node"]
  },
  "include": ["src", "test"]
}
tsconfig.build.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": { "noEmit": false, "rootDir": "src", "outDir": "dist" },
  "include": ["src"]
}
.env.example
NODE_ENV=development
PORT=3000
LOG_LEVEL=debug
CORS_ORIGINS=http://localhost:5173
TRUST_PROXY=0
RATE_LIMIT_PER_MINUTE=120
# openssl rand -hex 32
KITCHEN_API_KEY=replace-with-a-long-random-secret-of-32-chars

A few decisions worth understanding:

  • "type": "module" and "module": "nodenext" – the project is native ESM. You write relative imports with the .js extension (./config.js) even though the source file is config.ts – that is what the compiled code run by Node will look like.
  • tsx watch runs TypeScript without a build step and restarts the process when a file changes. Production runs the compiled JavaScript from dist/.
  • --env-file-if-exists=.env is Node.js' built-in .env support – no dotenv package. In production the variables come from the platform (Kubernetes, ECS, Render) and the file simply does not exist.
  • Two tsconfig files: the main one type-checks src and test, while tsconfig.build.json compiles only src into dist.

Step 2. Configuration and logging

The first rule of production services: bad configuration must stop the startup, not blow up at 3 a.m. on the first order. Environment variables are just strings, so we run them through a Zod schema – with type coercion, defaults and a readable message.

Configuration and logger

src/config.ts
import { z } from 'zod';

const EnvSchema = z.object({
  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
  PORT: z.coerce.number().int().min(1).max(65535).default(3000),
  LOG_LEVEL: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']).default('info'),
  // Comma-separated list of front-end origins allowed by CORS.
  CORS_ORIGINS: z
    .string()
    .default('http://localhost:5173')
    .transform((value) => value.split(',').map((s) => s.trim()).filter(Boolean)),
  // Number of reverse proxies in front of the app (load balancer = 1).
  TRUST_PROXY: z.coerce.number().int().min(0).default(0),
  RATE_LIMIT_PER_MINUTE: z.coerce.number().int().positive().default(120),
  // Shared secret of the kitchen tablet (PATCH /status) – long and random.
  KITCHEN_API_KEY: z.string().min(32),
});

export type Config = z.infer<typeof EnvSchema>;

export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
  const parsed = EnvSchema.safeParse(env);
  if (!parsed.success) {
    // Fail fast: a misconfigured service must not start at all.
    console.error(`Invalid environment configuration:\n${z.prettifyError(parsed.error)}`);
    process.exit(1);
  }
  return parsed.data;
}
src/logger.ts
import { pino } from 'pino';
import type { Config } from './config.js';

export function createLogger(config: Pick<Config, 'LOG_LEVEL' | 'NODE_ENV'>) {
  return pino({
    level: config.LOG_LEVEL,
    // Never write credentials to the logs, not even by accident.
    redact: {
      paths: ['req.headers.authorization', 'req.headers.cookie', 'res.headers["set-cookie"]', '*.password'],
      censor: '[redacted]',
    },
    // Human-friendly output locally, plain JSON (one object per line) everywhere else.
    transport: config.NODE_ENV === 'development' ? { target: 'pino-pretty', options: { singleLine: true } } : undefined,
  });
}

export type Logger = ReturnType<typeof createLogger>;

loadConfig() takes the environment object as a parameter – tests pass their own without touching process.env. z.prettifyError() (Zod 4) turns the list of issues into text like "✖ KITCHEN_API_KEY: Too small…".

The logger is pino – one JSON object per line, so logs go to CloudWatch, Loki or Datadog without parsing. Locally pino-pretty formats them for humans. The redact option strips the Authorization and Cookie headers and password fields before anything is written – cheaper than explaining a token leak in your logs.

Step 3. The domain: schemas, repository and service

Before the first endpoint exists, we describe the pierogi shop's data and rules. Zod schemas play a double role: they validate input at runtime and they are the source of types (z.infer). You never write a separate CreateOrderInput interface – it always matches the validation.

Order schemas, repository and service

src/orders/order.schemas.ts
import { z } from 'zod';

export const DISHES = ['ruskie', 'z-miesem', 'z-kapusta', 'z-jagodami'] as const;
export const ORDER_STATUSES = ['new', 'in-kitchen', 'ready', 'delivered', 'cancelled'] as const;

export const OrderItemSchema = z.object({
  dish: z.enum(DISHES),
  quantity: z.number().int().min(1).max(100),
});

export const CreateOrderSchema = z.object({
  customerName: z.string().trim().min(2).max(80),
  phone: z.string().regex(/^\+?[0-9 ]{9,15}$/, 'Invalid phone number'),
  items: z.array(OrderItemSchema).min(1).max(10),
  note: z.string().max(500).optional(),
});

export const ListOrdersQuerySchema = z.object({
  status: z.enum(ORDER_STATUSES).optional(),
  // Query string values are always strings – coerce them.
  limit: z.coerce.number().int().min(1).max(100).default(20),
});

export const OrderSchema = CreateOrderSchema.extend({
  id: z.uuid(),
  status: z.enum(ORDER_STATUSES),
  createdAt: z.iso.datetime(),
});

export const OrderIdParamsSchema = z.object({ id: z.uuid() });
export const UpdateStatusSchema = z.object({ status: z.enum(ORDER_STATUSES) });

export type CreateOrderInput = z.infer<typeof CreateOrderSchema>;
export type Order = z.infer<typeof OrderSchema>;
export type ListOrdersQuery = z.infer<typeof ListOrdersQuerySchema>;
export type OrderItem = z.infer<typeof OrderItemSchema>;
export type OrderStatus = (typeof ORDER_STATUSES)[number];
src/orders/orders.repository.ts
import type { ListOrdersQuery, Order } from './order.schemas.js';

export interface OrdersRepository {
  insert(order: Order): Promise<void>;
  findById(id: string): Promise<Order | undefined>;
  list(query: ListOrdersQuery): Promise<Order[]>;
  update(order: Order): Promise<void>;
}

// Good enough for the tutorial and for tests; replace with Postgres/Mongo later.
export class InMemoryOrdersRepository implements OrdersRepository {
  private readonly orders = new Map<string, Order>();

  async insert(order: Order): Promise<void> {
    this.orders.set(order.id, structuredClone(order));
  }

  async findById(id: string): Promise<Order | undefined> {
    const order = this.orders.get(id);
    return order && structuredClone(order);
  }

  async list({ status, limit }: ListOrdersQuery): Promise<Order[]> {
    return [...this.orders.values()]
      .filter((o) => !status || o.status === status)
      .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
      .slice(0, limit)
      .map((o) => structuredClone(o));
  }

  async update(order: Order): Promise<void> {
    this.orders.set(order.id, structuredClone(order));
  }
}
src/orders/orders.service.ts
import { randomUUID } from 'node:crypto';
import { conflict, notFound, unprocessable } from '../errors.js';
import type { CreateOrderInput, ListOrdersQuery, Order, OrderStatus } from './order.schemas.js';
import type { OrdersRepository } from './orders.repository.js';

const MAX_PIEROGI_PER_ORDER = 100;

// Allowed status transitions – the kitchen cannot "un-deliver" an order.
const TRANSITIONS: Record<OrderStatus, readonly OrderStatus[]> = {
  new: ['in-kitchen', 'cancelled'],
  'in-kitchen': ['ready', 'cancelled'],
  ready: ['delivered'],
  delivered: [],
  cancelled: [],
};

export class OrdersService {
  constructor(
    private readonly repo: OrdersRepository,
    private readonly now: () => Date = () => new Date(),
  ) {}

  async place(input: CreateOrderInput): Promise<Order> {
    const total = input.items.reduce((sum, item) => sum + item.quantity, 0);
    if (total > MAX_PIEROGI_PER_ORDER) {
      throw unprocessable('TOO_MANY_PIEROGI', `Max ${MAX_PIEROGI_PER_ORDER} pierogi per order, got ${total}`);
    }
    const order: Order = { ...input, id: randomUUID(), status: 'new', createdAt: this.now().toISOString() };
    await this.repo.insert(order);
    return order;
  }

  list(query: ListOrdersQuery): Promise<Order[]> {
    return this.repo.list(query);
  }

  async get(id: string): Promise<Order> {
    const order = await this.repo.findById(id);
    if (!order) throw notFound(`Order ${id}`);
    return order;
  }

  async changeStatus(id: string, next: OrderStatus): Promise<Order> {
    const order = await this.get(id);
    if (!TRANSITIONS[order.status].includes(next)) {
      throw conflict('INVALID_TRANSITION', `Cannot move order from "${order.status}" to "${next}"`);
    }
    const updated: Order = { ...order, status: next };
    await this.repo.update(updated);
    return updated;
  }
}
LayerFileKnows about HTTP?Responsible for
Routerorders.router.tsyespaths, status codes, parsing input
Serviceorders.service.tsnorules: max 100 pierogi, allowed status transitions
Repositoryorders.repository.tsnostorage (in memory today, Postgres tomorrow)
Schemasorder.schemas.tsnodata shape and types

The service throws an AppError with a code (TOO_MANY_PIEROGI, INVALID_TRANSITION) and a status, but never touches res. It can be tested without Express, and when you move the API to NestJS one day (see the NestJS tutorial), the service will move almost unchanged. The clock (now) is injected – a test can set "Friday 6 p.m." without hacks on the global Date.

Step 4. Routing and validation

The router is a thin layer: parse the input, call the service, set the status. Note the missing try/catch – that is the biggest change in Express 5.

Orders router and the kitchen API key

src/orders/orders.router.ts
import { type RequestHandler, Router } from 'express';
import { CreateOrderSchema, ListOrdersQuerySchema, OrderIdParamsSchema, UpdateStatusSchema } from './order.schemas.js';
import type { OrdersService } from './orders.service.js';

export function createOrdersRouter(service: OrdersService, kitchenOnly: RequestHandler): Router {
  const router = Router();

  // Express 5: a rejected promise (or a throw) in an async handler goes straight
  // to the error middleware – no try/catch, no asyncHandler wrapper.
  router.post('/', async (req, res) => {
    const input = CreateOrderSchema.parse(req.body);
    const order = await service.place(input);
    res.status(201).location(`/api/orders/${order.id}`).json(order);
  });

  router.get('/', async (req, res) => {
    const query = ListOrdersQuerySchema.parse(req.query);
    res.json({ items: await service.list(query) });
  });

  router.get('/:id', async (req, res) => {
    const { id } = OrderIdParamsSchema.parse(req.params);
    res.json(await service.get(id));
  });

  router.patch('/:id/status', kitchenOnly, async (req, res) => {
    const { id } = OrderIdParamsSchema.parse(req.params);
    const { status } = UpdateStatusSchema.parse(req.body);
    res.json(await service.changeStatus(id, status));
  });

  return router;
}
src/middleware/require-api-key.ts
import { timingSafeEqual } from 'node:crypto';
import type { RequestHandler } from 'express';
import { AppError } from '../errors.js';

export function requireApiKey(expectedKey: string): RequestHandler {
  const expected = Buffer.from(expectedKey);
  return (req, _res, next) => {
    const provided = Buffer.from(req.get('x-api-key') ?? '');
    // Constant-time comparison: do not leak how many characters matched.
    if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) {
      return next(new AppError(401, 'INVALID_API_KEY', 'Missing or invalid x-api-key header'));
    }
    next();
  };
}

If CreateOrderSchema.parse() throws a ZodError or the service rejects a promise, Express 5 calls next(err) itself and the request lands in the error middleware. In Express 4 an unhandled rejection left the request hanging (the client waited until a timeout), which is why every project had its own asyncHandler().

The status change gets an extra kitchenOnly middleware – the kitchen tablet sends an x-api-key header. Comparing with timingSafeEqual does not reveal how many characters matched. Customer login and registration are covered in a separate authentication tutorial.

Express 4 → 5: what else changed

AreaExpress 4Express 5
Errors in asynccaught by handrejection → next(err) automatically
req.queryplain property, can be overwrittenread-only getter – keep the validation result in a variable
req.body without a parser{}undefined
Wildcard in a path/files/*/files/*splat (named parameter)
Optional parameter/:id?{/:id}
app.listen(port, cb)startup error emitted as an eventthe error (e.g. EADDRINUSE) goes to cb(err)
Removed APIs–req.param(), res.send(status), app.del() and a few more

Step 5. Consistent error handling

An API client should get a predictable error shape no matter what went wrong: { code, message, ... } and the right status. At the heart of it is middleware with four parameters – that is how Express recognizes an error handler.

Error class and error middleware

src/errors.ts
// One error type for everything the client is allowed to see.
export class AppError extends Error {
  readonly status: number;
  readonly code: string;
  readonly details?: unknown;

  constructor(status: number, code: string, message: string, details?: unknown) {
    super(message);
    this.name = 'AppError';
    this.status = status;
    this.code = code;
    this.details = details;
  }
}

export const notFound = (what: string) => new AppError(404, 'NOT_FOUND', `${what} not found`);
export const conflict = (code: string, message: string) => new AppError(409, code, message);
export const unprocessable = (code: string, message: string) => new AppError(422, code, message);
src/middleware/error-handler.ts
import type { ErrorRequestHandler, RequestHandler } from 'express';
import { ZodError } from 'zod';
import { AppError } from '../errors.js';

export const notFoundHandler: RequestHandler = (req, _res, next) => {
  next(new AppError(404, 'ROUTE_NOT_FOUND', `No route for ${req.method} ${req.path}`));
};

// Express recognizes error middleware by its four parameters (err, req, res, next).
export const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
  if (res.headersSent) return next(err);

  if (err instanceof ZodError) {
    res.status(400).json({
      code: 'VALIDATION_FAILED',
      message: 'Request validation failed',
      errors: err.issues.map((issue) => ({ path: issue.path.join('.'), message: issue.message })),
    });
    return;
  }

  if (err instanceof AppError) {
    res.status(err.status).json({ code: err.code, message: err.message, details: err.details });
    return;
  }

  // body-parser errors (malformed JSON, payload too large) carry `status` and `type`.
  if (typeof err?.status === 'number' && err.status < 500 && typeof err.type === 'string') {
    res.status(err.status).json({ code: err.type.toUpperCase().replace(/\W/g, '_'), message: err.message });
    return;
  }

  req.log.error({ err }, 'Unhandled error');
  res.status(500).json({ code: 'INTERNAL_ERROR', message: 'Something went wrong' });
};

The mapping looks like this:

SourceStatuscode
ZodError from validation400VALIDATION_FAILED + an errors[] list with fields
Broken JSON in the body (body-parser)400ENTITY_PARSE_FAILED
Body over the limit413ENTITY_TOO_LARGE
AppError from the service404 / 409 / 422the service's code
No route404ROUTE_NOT_FOUND
Anything else500INTERNAL_ERROR – details only in the logs

Step 6. Putting the app together: security middleware and server startup

Now we wire everything up in the createApp factory. The order of app.use() is the execution order – the logger goes first (to time the whole request), the 404 and error handlers go last.

App factory and server

src/app.ts
import { randomUUID } from 'node:crypto';
import cors from 'cors';
import express from 'express';
import { rateLimit } from 'express-rate-limit';
import helmet from 'helmet';
import { pinoHttp } from 'pino-http';
import type { Config } from './config.js';
import type { Logger } from './logger.js';
import { errorHandler, notFoundHandler } from './middleware/error-handler.js';
import { requireApiKey } from './middleware/require-api-key.js';
import { createOrdersRouter } from './orders/orders.router.js';
import type { OrdersService } from './orders/orders.service.js';

export interface AppDeps {
  config: Config;
  logger: Logger;
  ordersService: OrdersService;
}

// A factory instead of a global `app`: tests build their own instance with fakes.
export function createApp({ config, logger, ordersService }: AppDeps) {
  const app = express();
  app.set('trust proxy', config.TRUST_PROXY);

  app.use(
    pinoHttp({
      logger,
      // Reuse the caller's request id (e.g. from the load balancer) or create one.
      genReqId: (req, res) => {
        const id = req.headers['x-request-id']?.toString() ?? randomUUID();
        res.setHeader('x-request-id', id);
        return id;
      },
      customLogLevel: (_req, res, err) => (err || res.statusCode >= 500 ? 'error' : res.statusCode >= 400 ? 'warn' : 'info'),
      autoLogging: { ignore: (req) => req.url === '/health' },
      serializers: {
        req: (req) => ({ id: req.id, method: req.method, url: req.url }),
        res: (res) => ({ statusCode: res.statusCode }),
      },
    }),
  );
  app.use(helmet());
  app.use(cors({ origin: config.CORS_ORIGINS, credentials: true, maxAge: 600 }));
  app.use(express.json({ limit: '100kb' }));

  app.get('/health', (_req, res) => {
    res.json({ ok: true, uptimeSec: Math.round(process.uptime()) });
  });

  app.use(
    '/api',
    rateLimit({
      windowMs: 60_000,
      limit: config.RATE_LIMIT_PER_MINUTE,
      standardHeaders: 'draft-8',
      legacyHeaders: false,
      message: { code: 'RATE_LIMITED', message: 'Too many requests, slow down' },
    }),
  );
  app.use('/api/orders', createOrdersRouter(ordersService, requireApiKey(config.KITCHEN_API_KEY)));

  app.use(notFoundHandler);
  app.use(errorHandler);
  return app;
}
src/server.ts
import { createApp } from './app.js';
import { loadConfig } from './config.js';
import { createLogger } from './logger.js';
import { InMemoryOrdersRepository } from './orders/orders.repository.js';
import { OrdersService } from './orders/orders.service.js';

const config = loadConfig();
const logger = createLogger(config);
const ordersService = new OrdersService(new InMemoryOrdersRepository());
const app = createApp({ config, logger, ordersService });

// Express 5 passes listen errors (e.g. EADDRINUSE) to the callback.
const server = app.listen(config.PORT, (err) => {
  if (err) {
    logger.fatal({ err }, 'Cannot start HTTP server');
    process.exit(1);
  }
  logger.info(`Pierogi API listening on http://localhost:${config.PORT}`);
});

// Graceful shutdown: stop accepting new connections, let in-flight requests finish.
function shutdown(signal: NodeJS.Signals) {
  logger.info({ signal }, 'Shutting down');
  server.close((err) => process.exit(err ? 1 : 0));
  setTimeout(() => process.exit(1), 10_000).unref();
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);

What each piece does:

  • pino-http logs every request with its response time and id. It takes the id from the x-request-id header (if a load balancer set it) and echoes it in the response – a customer complaint leads you straight to the right log line. customLogLevel writes 4xx as warn and 5xx as error, and /health does not clutter the logs.
  • helmet sets a dozen security headers (HSTS, X-Content-Type-Options, CSP, Referrer-Policy) and removes X-Powered-By.
  • cors with an explicit list of origins. credentials: true is needed when the front end sends cookies – and then the origin cannot be *.
  • express.json({ limit: '100kb' }) – without a limit anyone can send you megabytes of JSON to parse.
  • express-rate-limit – 120 requests per minute per IP for /api/*, with RateLimit and RateLimit-Policy headers.
  • Graceful shutdown – after SIGTERM (that is how Kubernetes and ECS stop containers) the server stops accepting connections and finishes in-flight requests, with a forced exit after 10 s.

Run the project and place the first order:

cp .env.example .env
npm run dev
curl -s -X POST localhost:3000/api/orders -H 'content-type: application/json' \
  -d '{"customerName":"Zdzisław","phone":"600 100 200","items":[{"dish":"ruskie","quantity":20}]}'

Step 7. Tests without opening a port

Supertest takes the Express app object and sends requests to it in memory – no listen(), no port conflicts in CI. Every test builds a fresh app with an empty repository, so tests do not depend on their order.

API integration tests

test/orders.test.ts
import request from 'supertest';
import { describe, expect, it } from 'vitest';
import { createApp } from '../src/app.js';
import { loadConfig } from '../src/config.js';
import { createLogger } from '../src/logger.js';
import { InMemoryOrdersRepository } from '../src/orders/orders.repository.js';
import { OrdersService } from '../src/orders/orders.service.js';

const KITCHEN_API_KEY = 'test-kitchen-key-0123456789abcdef0123';

function buildApp() {
  const config = loadConfig({ NODE_ENV: 'test', LOG_LEVEL: 'silent', KITCHEN_API_KEY });
  const ordersService = new OrdersService(new InMemoryOrdersRepository());
  return createApp({ config, logger: createLogger(config), ordersService });
}

const validOrder = { customerName: 'Zdzisław', phone: '600 100 200', items: [{ dish: 'ruskie', quantity: 20 }] };

describe('orders API', () => {
  it('creates an order and reads it back', async () => {
    const app = buildApp();
    const created = await request(app).post('/api/orders').send(validOrder).expect(201);
    expect(created.headers.location).toBe(`/api/orders/${created.body.id}`);

    const fetched = await request(app).get(`/api/orders/${created.body.id}`).expect(200);
    expect(fetched.body).toMatchObject({ status: 'new', customerName: 'Zdzisław' });
  });

  it('returns 400 with field errors for an invalid body', async () => {
    const res = await request(buildApp()).post('/api/orders').send({ items: [] }).expect(400);
    expect(res.body.code).toBe('VALIDATION_FAILED');
    expect(res.body.errors.map((e: { path: string }) => e.path)).toContain('phone');
  });

  it('rejects more than 100 pierogi with 422', async () => {
    const order = { ...validOrder, items: [{ dish: 'ruskie', quantity: 60 }, { dish: 'z-miesem', quantity: 60 }] };
    const res = await request(buildApp()).post('/api/orders').send(order).expect(422);
    expect(res.body.code).toBe('TOO_MANY_PIEROGI');
  });

  it('returns 400 for malformed JSON', async () => {
    await request(buildApp()).post('/api/orders').set('Content-Type', 'application/json').send('{"oops"').expect(400);
  });

  it('lets only the kitchen change the status', async () => {
    const app = buildApp();
    const { body } = await request(app).post('/api/orders').send(validOrder).expect(201);
    const url = `/api/orders/${body.id}/status`;
    await request(app).patch(url).send({ status: 'in-kitchen' }).expect(401);
    await request(app).patch(url).set('x-api-key', KITCHEN_API_KEY).send({ status: 'delivered' }).expect(409);
    await request(app).patch(url).set('x-api-key', KITCHEN_API_KEY).send({ status: 'in-kitchen' }).expect(200);
  });
});

npm test runs five tests in a fraction of a second. They test what the client sees: status codes, the Location header, error codes and the protection of the status change.

Step 8. Deployment

The image is built in two stages: the first installs everything and compiles TypeScript, the second contains only dist/ and production dependencies, and the process runs as the node user, not root.

Dockerfile

Dockerfile
# Build stage: install everything, compile TypeScript, drop dev dependencies.
FROM node:24-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY tsconfig*.json ./
COPY src ./src
RUN npm run build && npm prune --omit=dev

# Runtime stage: only compiled JS + production node_modules, non-root user.
FROM node:24-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build /app/package.json ./
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]

Checklist before the first deployment:

  • ☐ NODE_ENV=production, secrets (e.g. KITCHEN_API_KEY) from a secrets manager, not from the repository.
  • ☐ The platform's health check pointed at GET /health.
  • ☐ Logs to stdout – the platform collects them; no log files or rotation inside the container.
  • ☐ TRUST_PROXY equal to the number of proxies in front of the app.
  • ☐ The in-memory repository replaced with a database – with two instances each would have its own orders.
  • ☐ With many instances, the rate limit in a shared store (e.g. Redis via rate-limit-redis), otherwise each instance counts separately.
  • ☐ No PM2 or cluster inside the container – you scale with the number of containers and the orchestrator handles restarts.

Common mistakes

  • Registering the error handler before the routers – it only covers what was registered earlier. 404 and errors go at the very end.
  • cors() with no options in production – lets any website read your API responses.
  • Sending the response twice (res.json() inside an if, then again below) ends with ERR_HTTP_HEADERS_SENT. return after sending a response.
  • Business logic in the router – half a year later you have 300-line handlers that cannot be tested without HTTP.
  • Trusting req.body without validation – {"quantity": "1e9"} or an extra "status": "delivered" field gets through if nobody checks the schema. z.object() strips unknown keys by default.

When Express, and when something else

Express pros

  • minimal, predictable, a huge middleware ecosystem
  • version 5 solved the `async` error problem
  • easy to start with, easy to understand someone else's project
  • architectural freedom – you decide on the layers

Express cons

  • architectural freedom – every project looks different
  • no built-in validation, DI or OpenAPI documentation
  • slower than Fastify and Hono in benchmarks (rarely matters with a database behind it)

If the team is bigger and the project will grow for years, consider NestJS – it enforces modules, dependency injection and conventions (and runs on Express by default). When raw performance or JSON schemas on input matter – Fastify. For edge runtimes (Cloudflare Workers, Deno, Bun) – Hono.

Check yourself

Question: An `async` handler in Express 5 throws after an `await`. What happens?

  • The request hangs because the promise was rejected without a handler
  • Express calls `next(err)` and the error middleware handles the request
  • The Node.js process exits with `unhandledRejection`

Question: The app runs behind an AWS load balancer and the 120 req/min limit blocks all clients at once. The most likely cause?

  • The limit is too low
  • Missing `trust proxy` – every request has the balancer's IP
  • Helmet blocks the `RateLimit` headers
Interview question: how do you organize error handling in an Express API?

A good answer: one application error class (status + machine-readable code + message) thrown by services that do not know HTTP; input validation (Zod/Joi) throwing errors mapped to 400 with a list of fields; a single (err, req, res, next) middleware registered last that maps known errors to statuses and unknown ones to a detail-free 500, logging them with the request id. Plus: in Express 5 errors from async code land there automatically, in Express 4 a wrapper was needed. Bonus points for mentioning RFC 9457 (Problem Details) and delegating to the default handler when res.headersSent is true.

What's next

This API will come in handy in the next tutorials: you will document it with OpenAPI, add customer accounts, pierogi photos in S3 and an order queue in SQS.