{"id":"6b09417d5ce40d447918f2a3","slug":"express","title":"REST API with Express 5 and TypeScript – from an empty folder to production","summary":"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.","servedLang":"en","availableLangs":["pl","en"],"topics":["express","typescript","layered-architecture"],"techs":["node","typescript"],"tags":["express-5","rest-api","zod","pino","helmet","cors","rate-limiting","vitest","supertest","docker"],"level":"intermediate","kind":"tutorial","access":"public","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":23,"stats":{"views":2,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-27T08:38:21.076Z","updatedAt":"2026-11-27T13:02:59.181Z","requestedLang":"en","theme":{"hero":"classic","heroMedia":null,"accent":"green","background":"dots","weaveResources":true,"toc":"right"},"seoDescription":"Express 5 + TypeScript step by step – ESM project layout, Zod validation, error middleware, async handlers, pino, helmet, cors, express-rate-limit, vitest + supertest tests, graceful shutdown and Docker.","wordCount":4432,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"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 "},{"type":"text","text":"async","marks":[{"type":"code"}]},{"type":"text","text":" 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."}]},{"type":"callout","attrs":{"variant":"info","title":"In a nutshell"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Express 5 forwards rejected promises to the error middleware by itself","marks":[{"type":"bold"}]},{"type":"text","text":" – no more "},{"type":"text","text":"try/catch","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"asyncHandler","marks":[{"type":"code"}]},{"type":"text","text":" wrappers in every handler."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Every input goes through a Zod schema","marks":[{"type":"bold"}]},{"type":"text","text":": environment variables at startup, body, query and params in handlers. The same schemas give you the TypeScript types."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The app is created by a ","marks":[{"type":"bold"}]},{"type":"text","text":"createApp(deps)","marks":[{"type":"code"}]},{"type":"text","text":" factory","marks":[{"type":"bold"}]},{"type":"text","text":" – the production server and the tests build it with different dependencies, and the business logic knows nothing about HTTP."}]}]}]}]},{"type":"callout","attrs":{"variant":"tip","title":"What you will build"},"content":[{"type":"paragraph","content":[{"type":"text","text":"The "},{"type":"text","text":"pierogi-api","marks":[{"type":"code"}]},{"type":"text","text":" service: placing orders ("},{"type":"text","text":"POST /api/orders","marks":[{"type":"code"}]},{"type":"text","text":"), a list with a filter and a limit, fetching by id and a status change reserved for the kitchen tablet (API key). Plus "},{"type":"text","text":"/health","marks":[{"type":"code"}]},{"type":"text","text":", JSON logs with a request id, security headers, a per-minute request limit, integration tests and a multi-stage "},{"type":"text","text":"Dockerfile","marks":[{"type":"code"}]},{"type":"text","text":". Download the code (17 files) as a ZIP using the icon next to the article – "},{"type":"text","text":"npm install && npm run dev","marks":[{"type":"code"}]},{"type":"text","text":" and it runs."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Prerequisites:","marks":[{"type":"bold"}]},{"type":"text","text":" Node.js 22.12+ (24 LTS recommended), TypeScript basics (types, unions, "},{"type":"text","text":"async/await","marks":[{"type":"code"}]},{"type":"text","text":" – see the "},{"type":"text","text":"TypeScript tutorial","marks":[{"type":"link","attrs":{"href":"/en/articles/typescript"}}]},{"type":"text","text":"), HTTP at the level of \"method, path, status, headers\"."}]},{"type":"stats","attrs":{"items":[{"value":"5","label":"Express version","hint":"stable since 2024, `latest` on npm since 2025"},{"value":"0","label":"`try/catch` in handlers","hint":"async errors reach the middleware"},{"value":"4","label":"layers","hint":"router → service → repository → domain"},{"value":"17","label":"files in the ZIP","hint":"including tests and the Dockerfile"}]}},{"type":"diagram","attrs":{"kind":"mermaid","code":"flowchart LR\n  C([Client]) --> L[pino-http<br/>request id + log]\n  L --> H[helmet<br/>headers]\n  H --> CO[cors]\n  CO --> J[express.json<br/>100 kB limit]\n  J --> RL[rate limit<br/>/api/*]\n  RL --> R[ordersRouter<br/>Zod.parse]\n  R --> S[OrdersService<br/>business rules]\n  S --> RE[(OrdersRepository)]\n  R -. \"throw / reject\" .-> E[errorHandler<br/>JSON with an error code]\n  S -. \"AppError\" .-> E","caption":"A request's path through the app – middleware order matters"}},{"type":"heading","attrs":{"level":2,"id":"step-1-the-project-esm-typescript-and-scripts"},"content":[{"type":"text","text":"Step 1. The project: ESM, TypeScript and scripts"}]},{"type":"paragraph","content":[{"type":"text","text":"We start with an empty folder. Dependencies fall into three groups: Express itself with middleware, Zod and pino, and the developer tooling."}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"mkdir pierogi-api && cd pierogi-api\nnpm init -y && npm pkg set type=module\nnpm install express zod pino pino-http helmet cors express-rate-limit\nnpm install -D typescript tsx vitest supertest pino-pretty @types/node @types/express @types/cors @types/supertest"}]},{"type":"codeGroup","attrs":{"title":"Project configuration"},"content":[{"type":"codeBlock","attrs":{"language":"json","filename":"package.json"},"content":[{"type":"text","text":"{\n  \"name\": \"pierogi-api\",\n  \"version\": \"1.0.0\",\n  \"private\": true,\n  \"type\": \"module\",\n  \"engines\": { \"node\": \">=22.12\" },\n  \"scripts\": {\n    \"dev\": \"tsx watch --env-file-if-exists=.env src/server.ts\",\n    \"build\": \"tsc -p tsconfig.build.json\",\n    \"start\": \"node --env-file-if-exists=.env dist/server.js\",\n    \"typecheck\": \"tsc --noEmit\",\n    \"test\": \"vitest run\"\n  },\n  \"dependencies\": {\n    \"cors\": \"^2.8.6\",\n    \"express\": \"^5.3.0\",\n    \"express-rate-limit\": \"^8.7.5\",\n    \"helmet\": \"^8.3.0\",\n    \"pino\": \"^10.4.0\",\n    \"pino-http\": \"^11.0.0\",\n    \"zod\": \"^4.6.7\"\n  },\n  \"devDependencies\": {\n    \"@types/cors\": \"^2.8.19\",\n    \"@types/express\": \"^5.0.6\",\n    \"@types/node\": \"^24.19.4\",\n    \"@types/supertest\": \"^7.2.1\",\n    \"pino-pretty\": \"^13.2.0\",\n    \"supertest\": \"^7.3.2\",\n    \"tsx\": \"^4.23.15\",\n    \"typescript\": \"^7.0.2\",\n    \"vitest\": \"^5.1.2\"\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.json"},"content":[{"type":"text","text":"{\n  \"compilerOptions\": {\n    \"target\": \"ES2024\",\n    \"module\": \"nodenext\",\n    \"strict\": true,\n    \"noUncheckedIndexedAccess\": true,\n    \"verbatimModuleSyntax\": true,\n    \"skipLibCheck\": true,\n    \"sourceMap\": true,\n    \"noEmit\": true,\n    \"types\": [\"node\"]\n  },\n  \"include\": [\"src\", \"test\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"json","filename":"tsconfig.build.json"},"content":[{"type":"text","text":"{\n  \"extends\": \"./tsconfig.json\",\n  \"compilerOptions\": { \"noEmit\": false, \"rootDir\": \"src\", \"outDir\": \"dist\" },\n  \"include\": [\"src\"]\n}"}]},{"type":"codeBlock","attrs":{"language":"plaintext","filename":".env.example"},"content":[{"type":"text","text":"NODE_ENV=development\nPORT=3000\nLOG_LEVEL=debug\nCORS_ORIGINS=http://localhost:5173\nTRUST_PROXY=0\nRATE_LIMIT_PER_MINUTE=120\n# openssl rand -hex 32\nKITCHEN_API_KEY=replace-with-a-long-random-secret-of-32-chars"}]}]},{"type":"paragraph","content":[{"type":"text","text":"A few decisions worth understanding:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"\"type\": \"module\"","marks":[{"type":"code"}]},{"type":"text","text":" and ","marks":[{"type":"bold"}]},{"type":"text","text":"\"module\": \"nodenext\"","marks":[{"type":"code"}]},{"type":"text","text":" – the project is native ESM. You write relative imports with the "},{"type":"text","text":".js","marks":[{"type":"code"}]},{"type":"text","text":" extension ("},{"type":"text","text":"./config.js","marks":[{"type":"code"}]},{"type":"text","text":") even though the source file is "},{"type":"text","text":"config.ts","marks":[{"type":"code"}]},{"type":"text","text":" – that is what the compiled code run by Node will look like."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"tsx watch","marks":[{"type":"code"}]},{"type":"text","text":" runs TypeScript without a build step and restarts the process when a file changes. Production runs the compiled JavaScript from "},{"type":"text","text":"dist/","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"--env-file-if-exists=.env","marks":[{"type":"code"}]},{"type":"text","text":" is Node.js' built-in "},{"type":"text","text":".env","marks":[{"type":"code"}]},{"type":"text","text":" support – no "},{"type":"text","text":"dotenv","marks":[{"type":"code"}]},{"type":"text","text":" package. In production the variables come from the platform (Kubernetes, ECS, Render) and the file simply does not exist."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Two ","marks":[{"type":"bold"}]},{"type":"text","text":"tsconfig","marks":[{"type":"code"}]},{"type":"text","text":" files","marks":[{"type":"bold"}]},{"type":"text","text":": the main one type-checks "},{"type":"text","text":"src","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"test","marks":[{"type":"code"}]},{"type":"text","text":", while "},{"type":"text","text":"tsconfig.build.json","marks":[{"type":"code"}]},{"type":"text","text":" compiles only "},{"type":"text","text":"src","marks":[{"type":"code"}]},{"type":"text","text":" into "},{"type":"text","text":"dist","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]}]},{"type":"callout","attrs":{"variant":"info","title":"TypeScript 7"},"content":[{"type":"paragraph","content":[{"type":"text","text":"npm install -D typescript","marks":[{"type":"code"}]},{"type":"text","text":" now installs TypeScript 7 – the compiler rewritten in Go, many times faster. It type-checks and builds a project like this one without changes. Two things to remember: it no longer includes every "},{"type":"text","text":"@types/*","marks":[{"type":"code"}]},{"type":"text","text":" package by default, hence the explicit "},{"type":"text","text":"\"types\": [\"node\"]","marks":[{"type":"code"}]},{"type":"text","text":" in "},{"type":"text","text":"tsconfig.json","marks":[{"type":"code"}]},{"type":"text","text":", and tools that rely on the old compiler API (e.g. Nest CLI, "},{"type":"text","text":"openapi-typescript","marks":[{"type":"code"}]},{"type":"text","text":") stay on TypeScript 5.9/6.0."}]}]},{"type":"heading","attrs":{"level":2,"id":"step-2-configuration-and-logging"},"content":[{"type":"text","text":"Step 2. Configuration and logging"}]},{"type":"paragraph","content":[{"type":"text","text":"The first rule of production services: "},{"type":"text","text":"bad configuration must stop the startup, not blow up at 3 a.m. on the first order","marks":[{"type":"bold"}]},{"type":"text","text":". Environment variables are just strings, so we run them through a Zod schema – with type coercion, defaults and a readable message."}]},{"type":"codeGroup","attrs":{"title":"Configuration and logger"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/config.ts"},"content":[{"type":"text","text":"import { z } from 'zod';\n\nconst EnvSchema = z.object({\n  NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),\n  PORT: z.coerce.number().int().min(1).max(65535).default(3000),\n  LOG_LEVEL: z.enum(['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent']).default('info'),\n  // Comma-separated list of front-end origins allowed by CORS.\n  CORS_ORIGINS: z\n    .string()\n    .default('http://localhost:5173')\n    .transform((value) => value.split(',').map((s) => s.trim()).filter(Boolean)),\n  // Number of reverse proxies in front of the app (load balancer = 1).\n  TRUST_PROXY: z.coerce.number().int().min(0).default(0),\n  RATE_LIMIT_PER_MINUTE: z.coerce.number().int().positive().default(120),\n  // Shared secret of the kitchen tablet (PATCH /status) – long and random.\n  KITCHEN_API_KEY: z.string().min(32),\n});\n\nexport type Config = z.infer<typeof EnvSchema>;\n\nexport function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {\n  const parsed = EnvSchema.safeParse(env);\n  if (!parsed.success) {\n    // Fail fast: a misconfigured service must not start at all.\n    console.error(`Invalid environment configuration:\\n${z.prettifyError(parsed.error)}`);\n    process.exit(1);\n  }\n  return parsed.data;\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/logger.ts"},"content":[{"type":"text","text":"import { pino } from 'pino';\nimport type { Config } from './config.js';\n\nexport function createLogger(config: Pick<Config, 'LOG_LEVEL' | 'NODE_ENV'>) {\n  return pino({\n    level: config.LOG_LEVEL,\n    // Never write credentials to the logs, not even by accident.\n    redact: {\n      paths: ['req.headers.authorization', 'req.headers.cookie', 'res.headers[\"set-cookie\"]', '*.password'],\n      censor: '[redacted]',\n    },\n    // Human-friendly output locally, plain JSON (one object per line) everywhere else.\n    transport: config.NODE_ENV === 'development' ? { target: 'pino-pretty', options: { singleLine: true } } : undefined,\n  });\n}\n\nexport type Logger = ReturnType<typeof createLogger>;"}]}]},{"type":"paragraph","content":[{"type":"text","text":"loadConfig()","marks":[{"type":"code"}]},{"type":"text","text":" takes the environment object as a parameter – tests pass their own without touching "},{"type":"text","text":"process.env","marks":[{"type":"code"}]},{"type":"text","text":". "},{"type":"text","text":"z.prettifyError()","marks":[{"type":"code"}]},{"type":"text","text":" (Zod 4) turns the list of issues into text like \"✖ KITCHEN_API_KEY: Too small…\"."}]},{"type":"paragraph","content":[{"type":"text","text":"The logger is "},{"type":"text","text":"pino","marks":[{"type":"link","attrs":{"href":"https://getpino.io"}}]},{"type":"text","text":" – one JSON object per line, so logs go to CloudWatch, Loki or Datadog without parsing. Locally "},{"type":"text","text":"pino-pretty","marks":[{"type":"code"}]},{"type":"text","text":" formats them for humans. The "},{"type":"text","text":"redact","marks":[{"type":"code"}]},{"type":"text","text":" option strips the "},{"type":"text","text":"Authorization","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"Cookie","marks":[{"type":"code"}]},{"type":"text","text":" headers and "},{"type":"text","text":"password","marks":[{"type":"code"}]},{"type":"text","text":" fields before anything is written – cheaper than explaining a token leak in your logs."}]},{"type":"heading","attrs":{"level":2,"id":"step-3-the-domain-schemas-repository-and-service"},"content":[{"type":"text","text":"Step 3. The domain: schemas, repository and service"}]},{"type":"paragraph","content":[{"type":"text","text":"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 ("},{"type":"text","text":"z.infer","marks":[{"type":"code"}]},{"type":"text","text":"). You never write a separate "},{"type":"text","text":"CreateOrderInput","marks":[{"type":"code"}]},{"type":"text","text":" interface – it always matches the validation."}]},{"type":"codeGroup","attrs":{"title":"Order schemas, repository and service"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/orders/order.schemas.ts"},"content":[{"type":"text","text":"import { z } from 'zod';\n\nexport const DISHES = ['ruskie', 'z-miesem', 'z-kapusta', 'z-jagodami'] as const;\nexport const ORDER_STATUSES = ['new', 'in-kitchen', 'ready', 'delivered', 'cancelled'] as const;\n\nexport const OrderItemSchema = z.object({\n  dish: z.enum(DISHES),\n  quantity: z.number().int().min(1).max(100),\n});\n\nexport const CreateOrderSchema = z.object({\n  customerName: z.string().trim().min(2).max(80),\n  phone: z.string().regex(/^\\+?[0-9 ]{9,15}$/, 'Invalid phone number'),\n  items: z.array(OrderItemSchema).min(1).max(10),\n  note: z.string().max(500).optional(),\n});\n\nexport const ListOrdersQuerySchema = z.object({\n  status: z.enum(ORDER_STATUSES).optional(),\n  // Query string values are always strings – coerce them.\n  limit: z.coerce.number().int().min(1).max(100).default(20),\n});\n\nexport const OrderSchema = CreateOrderSchema.extend({\n  id: z.uuid(),\n  status: z.enum(ORDER_STATUSES),\n  createdAt: z.iso.datetime(),\n});\n\nexport const OrderIdParamsSchema = z.object({ id: z.uuid() });\nexport const UpdateStatusSchema = z.object({ status: z.enum(ORDER_STATUSES) });\n\nexport type CreateOrderInput = z.infer<typeof CreateOrderSchema>;\nexport type Order = z.infer<typeof OrderSchema>;\nexport type ListOrdersQuery = z.infer<typeof ListOrdersQuerySchema>;\nexport type OrderItem = z.infer<typeof OrderItemSchema>;\nexport type OrderStatus = (typeof ORDER_STATUSES)[number];"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/orders/orders.repository.ts"},"content":[{"type":"text","text":"import type { ListOrdersQuery, Order } from './order.schemas.js';\n\nexport interface OrdersRepository {\n  insert(order: Order): Promise<void>;\n  findById(id: string): Promise<Order | undefined>;\n  list(query: ListOrdersQuery): Promise<Order[]>;\n  update(order: Order): Promise<void>;\n}\n\n// Good enough for the tutorial and for tests; replace with Postgres/Mongo later.\nexport class InMemoryOrdersRepository implements OrdersRepository {\n  private readonly orders = new Map<string, Order>();\n\n  async insert(order: Order): Promise<void> {\n    this.orders.set(order.id, structuredClone(order));\n  }\n\n  async findById(id: string): Promise<Order | undefined> {\n    const order = this.orders.get(id);\n    return order && structuredClone(order);\n  }\n\n  async list({ status, limit }: ListOrdersQuery): Promise<Order[]> {\n    return [...this.orders.values()]\n      .filter((o) => !status || o.status === status)\n      .sort((a, b) => b.createdAt.localeCompare(a.createdAt))\n      .slice(0, limit)\n      .map((o) => structuredClone(o));\n  }\n\n  async update(order: Order): Promise<void> {\n    this.orders.set(order.id, structuredClone(order));\n  }\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/orders/orders.service.ts"},"content":[{"type":"text","text":"import { randomUUID } from 'node:crypto';\nimport { conflict, notFound, unprocessable } from '../errors.js';\nimport type { CreateOrderInput, ListOrdersQuery, Order, OrderStatus } from './order.schemas.js';\nimport type { OrdersRepository } from './orders.repository.js';\n\nconst MAX_PIEROGI_PER_ORDER = 100;\n\n// Allowed status transitions – the kitchen cannot \"un-deliver\" an order.\nconst TRANSITIONS: Record<OrderStatus, readonly OrderStatus[]> = {\n  new: ['in-kitchen', 'cancelled'],\n  'in-kitchen': ['ready', 'cancelled'],\n  ready: ['delivered'],\n  delivered: [],\n  cancelled: [],\n};\n\nexport class OrdersService {\n  constructor(\n    private readonly repo: OrdersRepository,\n    private readonly now: () => Date = () => new Date(),\n  ) {}\n\n  async place(input: CreateOrderInput): Promise<Order> {\n    const total = input.items.reduce((sum, item) => sum + item.quantity, 0);\n    if (total > MAX_PIEROGI_PER_ORDER) {\n      throw unprocessable('TOO_MANY_PIEROGI', `Max ${MAX_PIEROGI_PER_ORDER} pierogi per order, got ${total}`);\n    }\n    const order: Order = { ...input, id: randomUUID(), status: 'new', createdAt: this.now().toISOString() };\n    await this.repo.insert(order);\n    return order;\n  }\n\n  list(query: ListOrdersQuery): Promise<Order[]> {\n    return this.repo.list(query);\n  }\n\n  async get(id: string): Promise<Order> {\n    const order = await this.repo.findById(id);\n    if (!order) throw notFound(`Order ${id}`);\n    return order;\n  }\n\n  async changeStatus(id: string, next: OrderStatus): Promise<Order> {\n    const order = await this.get(id);\n    if (!TRANSITIONS[order.status].includes(next)) {\n      throw conflict('INVALID_TRANSITION', `Cannot move order from \"${order.status}\" to \"${next}\"`);\n    }\n    const updated: Order = { ...order, status: next };\n    await this.repo.update(updated);\n    return updated;\n  }\n}"}]}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Layer"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"File"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Knows about HTTP?"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Responsible for"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Router"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"orders.router.ts","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"yes"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"paths, status codes, parsing input"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Service"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"orders.service.ts","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"no"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"rules: max 100 pierogi, allowed status transitions"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Repository"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"orders.repository.ts","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"no"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"storage (in memory today, Postgres tomorrow)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Schemas"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"order.schemas.ts","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"no"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"data shape and types"}]}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"The service throws an "},{"type":"text","text":"AppError","marks":[{"type":"code"}]},{"type":"text","text":" with a code ("},{"type":"text","text":"TOO_MANY_PIEROGI","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"INVALID_TRANSITION","marks":[{"type":"code"}]},{"type":"text","text":") and a status, but never touches "},{"type":"text","text":"res","marks":[{"type":"code"}]},{"type":"text","text":". It can be tested without Express, and when you move the API to NestJS one day (see the "},{"type":"text","text":"NestJS tutorial","marks":[{"type":"link","attrs":{"href":"/en/articles/nestjs"}}]},{"type":"text","text":"), the service will move almost unchanged. The clock ("},{"type":"text","text":"now","marks":[{"type":"code"}]},{"type":"text","text":") is injected – a test can set \"Friday 6 p.m.\" without hacks on the global "},{"type":"text","text":"Date","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"heading","attrs":{"level":2,"id":"step-4-routing-and-validation"},"content":[{"type":"text","text":"Step 4. Routing and validation"}]},{"type":"paragraph","content":[{"type":"text","text":"The router is a thin layer: parse the input, call the service, set the status. Note the missing "},{"type":"text","text":"try/catch","marks":[{"type":"code"}]},{"type":"text","text":" – that is the biggest change in Express 5."}]},{"type":"codeGroup","attrs":{"title":"Orders router and the kitchen API key"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/orders/orders.router.ts"},"content":[{"type":"text","text":"import { type RequestHandler, Router } from 'express';\nimport { CreateOrderSchema, ListOrdersQuerySchema, OrderIdParamsSchema, UpdateStatusSchema } from './order.schemas.js';\nimport type { OrdersService } from './orders.service.js';\n\nexport function createOrdersRouter(service: OrdersService, kitchenOnly: RequestHandler): Router {\n  const router = Router();\n\n  // Express 5: a rejected promise (or a throw) in an async handler goes straight\n  // to the error middleware – no try/catch, no asyncHandler wrapper.\n  router.post('/', async (req, res) => {\n    const input = CreateOrderSchema.parse(req.body);\n    const order = await service.place(input);\n    res.status(201).location(`/api/orders/${order.id}`).json(order);\n  });\n\n  router.get('/', async (req, res) => {\n    const query = ListOrdersQuerySchema.parse(req.query);\n    res.json({ items: await service.list(query) });\n  });\n\n  router.get('/:id', async (req, res) => {\n    const { id } = OrderIdParamsSchema.parse(req.params);\n    res.json(await service.get(id));\n  });\n\n  router.patch('/:id/status', kitchenOnly, async (req, res) => {\n    const { id } = OrderIdParamsSchema.parse(req.params);\n    const { status } = UpdateStatusSchema.parse(req.body);\n    res.json(await service.changeStatus(id, status));\n  });\n\n  return router;\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/middleware/require-api-key.ts"},"content":[{"type":"text","text":"import { timingSafeEqual } from 'node:crypto';\nimport type { RequestHandler } from 'express';\nimport { AppError } from '../errors.js';\n\nexport function requireApiKey(expectedKey: string): RequestHandler {\n  const expected = Buffer.from(expectedKey);\n  return (req, _res, next) => {\n    const provided = Buffer.from(req.get('x-api-key') ?? '');\n    // Constant-time comparison: do not leak how many characters matched.\n    if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) {\n      return next(new AppError(401, 'INVALID_API_KEY', 'Missing or invalid x-api-key header'));\n    }\n    next();\n  };\n}"}]}]},{"type":"paragraph","content":[{"type":"text","text":"If "},{"type":"text","text":"CreateOrderSchema.parse()","marks":[{"type":"code"}]},{"type":"text","text":" throws a "},{"type":"text","text":"ZodError","marks":[{"type":"code"}]},{"type":"text","text":" or the service rejects a promise, Express 5 calls "},{"type":"text","text":"next(err)","marks":[{"type":"code"}]},{"type":"text","text":" 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 "},{"type":"text","text":"asyncHandler()","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"paragraph","content":[{"type":"text","text":"The status change gets an extra "},{"type":"text","text":"kitchenOnly","marks":[{"type":"code"}]},{"type":"text","text":" middleware – the kitchen tablet sends an "},{"type":"text","text":"x-api-key","marks":[{"type":"code"}]},{"type":"text","text":" header. Comparing with "},{"type":"text","text":"timingSafeEqual","marks":[{"type":"code"}]},{"type":"text","text":" does not reveal how many characters matched. Customer login and registration are covered in a separate "},{"type":"text","text":"authentication tutorial","marks":[{"type":"link","attrs":{"href":"/en/articles/authentication"}}]},{"type":"text","text":"."}]},{"type":"paragraph","content":[{"type":"text","text":"Express 4 → 5: what else changed","marks":[{"type":"bold"}]}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Area"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Express 4"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Express 5"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Errors in "},{"type":"text","text":"async","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"caught by hand"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"rejection → "},{"type":"text","text":"next(err)","marks":[{"type":"code"}]},{"type":"text","text":" automatically"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"req.query","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"plain property, can be overwritten"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"read-only getter – keep the validation result in a variable"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"req.body","marks":[{"type":"code"}]},{"type":"text","text":" without a parser"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"{}","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"undefined","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Wildcard in a path"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"/files/*","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"/files/*splat","marks":[{"type":"code"}]},{"type":"text","text":" (named parameter)"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Optional parameter"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"/:id?","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"{/:id}","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"app.listen(port, cb)","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"startup error emitted as an event"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the error (e.g. "},{"type":"text","text":"EADDRINUSE","marks":[{"type":"code"}]},{"type":"text","text":") goes to "},{"type":"text","text":"cb(err)","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Removed APIs"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"–"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"req.param()","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"res.send(status)","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"app.del()","marks":[{"type":"code"}]},{"type":"text","text":" and a few more"}]}]}]}]},{"type":"callout","attrs":{"variant":"warning","title":"Common mistake: assigning to req.query"},"content":[{"type":"paragraph","content":[{"type":"text","text":"The Express 4 pattern \"middleware validates and overwrites "},{"type":"text","text":"req.query = parsed","marks":[{"type":"code"}]},{"type":"text","text":"\" throws a "},{"type":"text","text":"TypeError","marks":[{"type":"code"}]},{"type":"text","text":" in version 5 or silently does nothing. Keep the result of "},{"type":"text","text":"schema.parse(req.query)","marks":[{"type":"code"}]},{"type":"text","text":" in a local variable (as in the router above) or in "},{"type":"text","text":"res.locals","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"heading","attrs":{"level":2,"id":"step-5-consistent-error-handling"},"content":[{"type":"text","text":"Step 5. Consistent error handling"}]},{"type":"paragraph","content":[{"type":"text","text":"An API client should get a predictable error shape no matter what went wrong: "},{"type":"text","text":"{ code, message, ... }","marks":[{"type":"code"}]},{"type":"text","text":" and the right status. At the heart of it is middleware with "},{"type":"text","text":"four parameters","marks":[{"type":"bold"}]},{"type":"text","text":" – that is how Express recognizes an error handler."}]},{"type":"codeGroup","attrs":{"title":"Error class and error middleware"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/errors.ts"},"content":[{"type":"text","text":"// One error type for everything the client is allowed to see.\nexport class AppError extends Error {\n  readonly status: number;\n  readonly code: string;\n  readonly details?: unknown;\n\n  constructor(status: number, code: string, message: string, details?: unknown) {\n    super(message);\n    this.name = 'AppError';\n    this.status = status;\n    this.code = code;\n    this.details = details;\n  }\n}\n\nexport const notFound = (what: string) => new AppError(404, 'NOT_FOUND', `${what} not found`);\nexport const conflict = (code: string, message: string) => new AppError(409, code, message);\nexport const unprocessable = (code: string, message: string) => new AppError(422, code, message);"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/middleware/error-handler.ts"},"content":[{"type":"text","text":"import type { ErrorRequestHandler, RequestHandler } from 'express';\nimport { ZodError } from 'zod';\nimport { AppError } from '../errors.js';\n\nexport const notFoundHandler: RequestHandler = (req, _res, next) => {\n  next(new AppError(404, 'ROUTE_NOT_FOUND', `No route for ${req.method} ${req.path}`));\n};\n\n// Express recognizes error middleware by its four parameters (err, req, res, next).\nexport const errorHandler: ErrorRequestHandler = (err, req, res, next) => {\n  if (res.headersSent) return next(err);\n\n  if (err instanceof ZodError) {\n    res.status(400).json({\n      code: 'VALIDATION_FAILED',\n      message: 'Request validation failed',\n      errors: err.issues.map((issue) => ({ path: issue.path.join('.'), message: issue.message })),\n    });\n    return;\n  }\n\n  if (err instanceof AppError) {\n    res.status(err.status).json({ code: err.code, message: err.message, details: err.details });\n    return;\n  }\n\n  // body-parser errors (malformed JSON, payload too large) carry `status` and `type`.\n  if (typeof err?.status === 'number' && err.status < 500 && typeof err.type === 'string') {\n    res.status(err.status).json({ code: err.type.toUpperCase().replace(/\\W/g, '_'), message: err.message });\n    return;\n  }\n\n  req.log.error({ err }, 'Unhandled error');\n  res.status(500).json({ code: 'INTERNAL_ERROR', message: 'Something went wrong' });\n};"}]}]},{"type":"paragraph","content":[{"type":"text","text":"The mapping looks like this:"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Source"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Status"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"code","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ZodError","marks":[{"type":"code"}]},{"type":"text","text":" from validation"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"400"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"VALIDATION_FAILED","marks":[{"type":"code"}]},{"type":"text","text":" + an "},{"type":"text","text":"errors[]","marks":[{"type":"code"}]},{"type":"text","text":" list with fields"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Broken JSON in the body (body-parser)"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"400"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ENTITY_PARSE_FAILED","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Body over the limit"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"413"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ENTITY_TOO_LARGE","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"AppError","marks":[{"type":"code"}]},{"type":"text","text":" from the service"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"404 / 409 / 422"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"the service's code"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"No route"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"404"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"ROUTE_NOT_FOUND","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Anything else"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"500"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"INTERNAL_ERROR","marks":[{"type":"code"}]},{"type":"text","text":" – details only in the logs"}]}]}]}]},{"type":"callout","attrs":{"variant":"danger","title":"Never send a stack trace to the client"},"content":[{"type":"paragraph","content":[{"type":"text","text":"An unknown error is a 500 with a generic message. The exception text, an SQL query or a file path go to the logs (with the request id), not into the response – otherwise you hand an attacker a free map of your system. If you want a standard, look at the Problem Details format (RFC 9457, "},{"type":"text","text":"application/problem+json","marks":[{"type":"code"}]},{"type":"text","text":")."}]}]},{"type":"heading","attrs":{"level":2,"id":"step-6-putting-the-app-together-security-middleware-and-server-startup"},"content":[{"type":"text","text":"Step 6. Putting the app together: security middleware and server startup"}]},{"type":"paragraph","content":[{"type":"text","text":"Now we wire everything up in the "},{"type":"text","text":"createApp","marks":[{"type":"code"}]},{"type":"text","text":" factory. The order of "},{"type":"text","text":"app.use()","marks":[{"type":"code"}]},{"type":"text","text":" is the execution order – the logger goes first (to time the whole request), the 404 and error handlers go last."}]},{"type":"codeGroup","attrs":{"title":"App factory and server"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/app.ts"},"content":[{"type":"text","text":"import { randomUUID } from 'node:crypto';\nimport cors from 'cors';\nimport express from 'express';\nimport { rateLimit } from 'express-rate-limit';\nimport helmet from 'helmet';\nimport { pinoHttp } from 'pino-http';\nimport type { Config } from './config.js';\nimport type { Logger } from './logger.js';\nimport { errorHandler, notFoundHandler } from './middleware/error-handler.js';\nimport { requireApiKey } from './middleware/require-api-key.js';\nimport { createOrdersRouter } from './orders/orders.router.js';\nimport type { OrdersService } from './orders/orders.service.js';\n\nexport interface AppDeps {\n  config: Config;\n  logger: Logger;\n  ordersService: OrdersService;\n}\n\n// A factory instead of a global `app`: tests build their own instance with fakes.\nexport function createApp({ config, logger, ordersService }: AppDeps) {\n  const app = express();\n  app.set('trust proxy', config.TRUST_PROXY);\n\n  app.use(\n    pinoHttp({\n      logger,\n      // Reuse the caller's request id (e.g. from the load balancer) or create one.\n      genReqId: (req, res) => {\n        const id = req.headers['x-request-id']?.toString() ?? randomUUID();\n        res.setHeader('x-request-id', id);\n        return id;\n      },\n      customLogLevel: (_req, res, err) => (err || res.statusCode >= 500 ? 'error' : res.statusCode >= 400 ? 'warn' : 'info'),\n      autoLogging: { ignore: (req) => req.url === '/health' },\n      serializers: {\n        req: (req) => ({ id: req.id, method: req.method, url: req.url }),\n        res: (res) => ({ statusCode: res.statusCode }),\n      },\n    }),\n  );\n  app.use(helmet());\n  app.use(cors({ origin: config.CORS_ORIGINS, credentials: true, maxAge: 600 }));\n  app.use(express.json({ limit: '100kb' }));\n\n  app.get('/health', (_req, res) => {\n    res.json({ ok: true, uptimeSec: Math.round(process.uptime()) });\n  });\n\n  app.use(\n    '/api',\n    rateLimit({\n      windowMs: 60_000,\n      limit: config.RATE_LIMIT_PER_MINUTE,\n      standardHeaders: 'draft-8',\n      legacyHeaders: false,\n      message: { code: 'RATE_LIMITED', message: 'Too many requests, slow down' },\n    }),\n  );\n  app.use('/api/orders', createOrdersRouter(ordersService, requireApiKey(config.KITCHEN_API_KEY)));\n\n  app.use(notFoundHandler);\n  app.use(errorHandler);\n  return app;\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"src/server.ts"},"content":[{"type":"text","text":"import { createApp } from './app.js';\nimport { loadConfig } from './config.js';\nimport { createLogger } from './logger.js';\nimport { InMemoryOrdersRepository } from './orders/orders.repository.js';\nimport { OrdersService } from './orders/orders.service.js';\n\nconst config = loadConfig();\nconst logger = createLogger(config);\nconst ordersService = new OrdersService(new InMemoryOrdersRepository());\nconst app = createApp({ config, logger, ordersService });\n\n// Express 5 passes listen errors (e.g. EADDRINUSE) to the callback.\nconst server = app.listen(config.PORT, (err) => {\n  if (err) {\n    logger.fatal({ err }, 'Cannot start HTTP server');\n    process.exit(1);\n  }\n  logger.info(`Pierogi API listening on http://localhost:${config.PORT}`);\n});\n\n// Graceful shutdown: stop accepting new connections, let in-flight requests finish.\nfunction shutdown(signal: NodeJS.Signals) {\n  logger.info({ signal }, 'Shutting down');\n  server.close((err) => process.exit(err ? 1 : 0));\n  setTimeout(() => process.exit(1), 10_000).unref();\n}\nprocess.on('SIGTERM', shutdown);\nprocess.on('SIGINT', shutdown);"}]}]},{"type":"paragraph","content":[{"type":"text","text":"What each piece does:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"pino-http","marks":[{"type":"bold"}]},{"type":"text","text":" logs every request with its response time and id. It takes the id from the "},{"type":"text","text":"x-request-id","marks":[{"type":"code"}]},{"type":"text","text":" header (if a load balancer set it) and echoes it in the response – a customer complaint leads you straight to the right log line. "},{"type":"text","text":"customLogLevel","marks":[{"type":"code"}]},{"type":"text","text":" writes 4xx as "},{"type":"text","text":"warn","marks":[{"type":"code"}]},{"type":"text","text":" and 5xx as "},{"type":"text","text":"error","marks":[{"type":"code"}]},{"type":"text","text":", and "},{"type":"text","text":"/health","marks":[{"type":"code"}]},{"type":"text","text":" does not clutter the logs."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"helmet","marks":[{"type":"bold"}]},{"type":"text","text":" sets a dozen security headers (HSTS, "},{"type":"text","text":"X-Content-Type-Options","marks":[{"type":"code"}]},{"type":"text","text":", CSP, "},{"type":"text","text":"Referrer-Policy","marks":[{"type":"code"}]},{"type":"text","text":") and removes "},{"type":"text","text":"X-Powered-By","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"cors","marks":[{"type":"bold"}]},{"type":"text","text":" with an explicit list of origins. "},{"type":"text","text":"credentials: true","marks":[{"type":"code"}]},{"type":"text","text":" is needed when the front end sends cookies – and then the origin cannot be "},{"type":"text","text":"*","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"express.json({ limit: '100kb' })","marks":[{"type":"code"}]},{"type":"text","text":" – without a limit anyone can send you megabytes of JSON to parse."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"express-rate-limit","marks":[{"type":"bold"}]},{"type":"text","text":" – 120 requests per minute per IP for "},{"type":"text","text":"/api/*","marks":[{"type":"code"}]},{"type":"text","text":", with "},{"type":"text","text":"RateLimit","marks":[{"type":"code"}]},{"type":"text","text":" and "},{"type":"text","text":"RateLimit-Policy","marks":[{"type":"code"}]},{"type":"text","text":" headers."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Graceful shutdown","marks":[{"type":"bold"}]},{"type":"text","text":" – after "},{"type":"text","text":"SIGTERM","marks":[{"type":"code"}]},{"type":"text","text":" (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."}]}]}]},{"type":"callout","attrs":{"variant":"warning","title":"trust proxy and rate limiting"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Behind a load balancer every request comes from the balancer's address. Without "},{"type":"text","text":"TRUST_PROXY=1","marks":[{"type":"code"}]},{"type":"text","text":" the rate limit covers all clients at once and "},{"type":"text","text":"req.ip","marks":[{"type":"code"}]},{"type":"text","text":" in the logs is useless. On the other hand, "},{"type":"text","text":"trust proxy = true","marks":[{"type":"code"}]},{"type":"text","text":" on an app exposed directly to the internet lets anyone spoof their IP with an "},{"type":"text","text":"X-Forwarded-For","marks":[{"type":"code"}]},{"type":"text","text":" header. Set the exact number of proxies in front of the app."}]}]},{"type":"paragraph","content":[{"type":"text","text":"Run the project and place the first order:"}]},{"type":"codeBlock","attrs":{"language":"bash"},"content":[{"type":"text","text":"cp .env.example .env\nnpm run dev\ncurl -s -X POST localhost:3000/api/orders -H 'content-type: application/json' \\\n  -d '{\"customerName\":\"Zdzisław\",\"phone\":\"600 100 200\",\"items\":[{\"dish\":\"ruskie\",\"quantity\":20}]}'"}]},{"type":"heading","attrs":{"level":2,"id":"step-7-tests-without-opening-a-port"},"content":[{"type":"text","text":"Step 7. Tests without opening a port"}]},{"type":"paragraph","content":[{"type":"text","text":"Supertest takes the Express app object and sends requests to it in memory – no "},{"type":"text","text":"listen()","marks":[{"type":"code"}]},{"type":"text","text":", no port conflicts in CI. Every test builds a fresh app with an empty repository, so tests do not depend on their order."}]},{"type":"codeGroup","attrs":{"title":"API integration tests"},"content":[{"type":"codeBlock","attrs":{"language":"typescript","filename":"test/orders.test.ts"},"content":[{"type":"text","text":"import request from 'supertest';\nimport { describe, expect, it } from 'vitest';\nimport { createApp } from '../src/app.js';\nimport { loadConfig } from '../src/config.js';\nimport { createLogger } from '../src/logger.js';\nimport { InMemoryOrdersRepository } from '../src/orders/orders.repository.js';\nimport { OrdersService } from '../src/orders/orders.service.js';\n\nconst KITCHEN_API_KEY = 'test-kitchen-key-0123456789abcdef0123';\n\nfunction buildApp() {\n  const config = loadConfig({ NODE_ENV: 'test', LOG_LEVEL: 'silent', KITCHEN_API_KEY });\n  const ordersService = new OrdersService(new InMemoryOrdersRepository());\n  return createApp({ config, logger: createLogger(config), ordersService });\n}\n\nconst validOrder = { customerName: 'Zdzisław', phone: '600 100 200', items: [{ dish: 'ruskie', quantity: 20 }] };\n\ndescribe('orders API', () => {\n  it('creates an order and reads it back', async () => {\n    const app = buildApp();\n    const created = await request(app).post('/api/orders').send(validOrder).expect(201);\n    expect(created.headers.location).toBe(`/api/orders/${created.body.id}`);\n\n    const fetched = await request(app).get(`/api/orders/${created.body.id}`).expect(200);\n    expect(fetched.body).toMatchObject({ status: 'new', customerName: 'Zdzisław' });\n  });\n\n  it('returns 400 with field errors for an invalid body', async () => {\n    const res = await request(buildApp()).post('/api/orders').send({ items: [] }).expect(400);\n    expect(res.body.code).toBe('VALIDATION_FAILED');\n    expect(res.body.errors.map((e: { path: string }) => e.path)).toContain('phone');\n  });\n\n  it('rejects more than 100 pierogi with 422', async () => {\n    const order = { ...validOrder, items: [{ dish: 'ruskie', quantity: 60 }, { dish: 'z-miesem', quantity: 60 }] };\n    const res = await request(buildApp()).post('/api/orders').send(order).expect(422);\n    expect(res.body.code).toBe('TOO_MANY_PIEROGI');\n  });\n\n  it('returns 400 for malformed JSON', async () => {\n    await request(buildApp()).post('/api/orders').set('Content-Type', 'application/json').send('{\"oops\"').expect(400);\n  });\n\n  it('lets only the kitchen change the status', async () => {\n    const app = buildApp();\n    const { body } = await request(app).post('/api/orders').send(validOrder).expect(201);\n    const url = `/api/orders/${body.id}/status`;\n    await request(app).patch(url).send({ status: 'in-kitchen' }).expect(401);\n    await request(app).patch(url).set('x-api-key', KITCHEN_API_KEY).send({ status: 'delivered' }).expect(409);\n    await request(app).patch(url).set('x-api-key', KITCHEN_API_KEY).send({ status: 'in-kitchen' }).expect(200);\n  });\n});"}]}]},{"type":"paragraph","content":[{"type":"text","text":"npm test","marks":[{"type":"code"}]},{"type":"text","text":" runs five tests in a fraction of a second. They test what the client sees: status codes, the "},{"type":"text","text":"Location","marks":[{"type":"code"}]},{"type":"text","text":" header, error codes and the protection of the status change."}]},{"type":"heading","attrs":{"level":2,"id":"step-8-deployment"},"content":[{"type":"text","text":"Step 8. Deployment"}]},{"type":"paragraph","content":[{"type":"text","text":"The image is built in two stages: the first installs everything and compiles TypeScript, the second contains only "},{"type":"text","text":"dist/","marks":[{"type":"code"}]},{"type":"text","text":" and production dependencies, and the process runs as the "},{"type":"text","text":"node","marks":[{"type":"code"}]},{"type":"text","text":" user, not "},{"type":"text","text":"root","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"codeGroup","attrs":{"title":"Dockerfile"},"content":[{"type":"codeBlock","attrs":{"language":"dockerfile","filename":"Dockerfile"},"content":[{"type":"text","text":"# Build stage: install everything, compile TypeScript, drop dev dependencies.\nFROM node:24-alpine AS build\nWORKDIR /app\nCOPY package*.json ./\nRUN npm ci\nCOPY tsconfig*.json ./\nCOPY src ./src\nRUN npm run build && npm prune --omit=dev\n\n# Runtime stage: only compiled JS + production node_modules, non-root user.\nFROM node:24-alpine\nENV NODE_ENV=production\nWORKDIR /app\nCOPY --from=build /app/package.json ./\nCOPY --from=build /app/node_modules ./node_modules\nCOPY --from=build /app/dist ./dist\nUSER node\nEXPOSE 3000\nCMD [\"node\", \"dist/server.js\"]"}]}]},{"type":"paragraph","content":[{"type":"text","text":"Checklist before the first deployment:"}]},{"type":"taskList","content":[{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"NODE_ENV=production","marks":[{"type":"code"}]},{"type":"text","text":", secrets (e.g. "},{"type":"text","text":"KITCHEN_API_KEY","marks":[{"type":"code"}]},{"type":"text","text":") from a secrets manager, not from the repository."}]}]},{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"The platform's health check pointed at "},{"type":"text","text":"GET /health","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"Logs to stdout – the platform collects them; no log files or rotation inside the container."}]}]},{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"TRUST_PROXY","marks":[{"type":"code"}]},{"type":"text","text":" equal to the number of proxies in front of the app."}]}]},{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"The in-memory repository replaced with a database – with two instances each would have its own orders."}]}]},{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"With many instances, the rate limit in a shared store (e.g. Redis via "},{"type":"text","text":"rate-limit-redis","marks":[{"type":"code"}]},{"type":"text","text":"), otherwise each instance counts separately."}]}]},{"type":"taskItem","attrs":{"checked":false},"content":[{"type":"paragraph","content":[{"type":"text","text":"No PM2 or cluster inside the container – you scale with the number of containers and the orchestrator handles restarts."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"common-mistakes"},"content":[{"type":"text","text":"Common mistakes"}]},{"type":"callout","attrs":{"variant":"danger","title":"Error middleware without four parameters"},"content":[{"type":"paragraph","content":[{"type":"text","text":"Express treats "},{"type":"text","text":"app.use((err, req, res) => …)","marks":[{"type":"code"}]},{"type":"text","text":" with three parameters as regular middleware and never calls it with an error. The error handler must have the "},{"type":"text","text":"(err, req, res, next)","marks":[{"type":"code"}]},{"type":"text","text":" signature even if you do not use "},{"type":"text","text":"next","marks":[{"type":"code"}]},{"type":"text","text":" – in TypeScript the simplest way is to type it as "},{"type":"text","text":"ErrorRequestHandler","marks":[{"type":"code"}]},{"type":"text","text":"."}]}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Registering the error handler before the routers","marks":[{"type":"bold"}]},{"type":"text","text":" – it only covers what was registered earlier. 404 and errors go at the very end."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"cors()","marks":[{"type":"code"}]},{"type":"text","text":" with no options in production","marks":[{"type":"bold"}]},{"type":"text","text":" – lets any website read your API responses."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Sending the response twice","marks":[{"type":"bold"}]},{"type":"text","text":" ("},{"type":"text","text":"res.json()","marks":[{"type":"code"}]},{"type":"text","text":" inside an "},{"type":"text","text":"if","marks":[{"type":"code"}]},{"type":"text","text":", then again below) ends with "},{"type":"text","text":"ERR_HTTP_HEADERS_SENT","marks":[{"type":"code"}]},{"type":"text","text":". "},{"type":"text","text":"return","marks":[{"type":"code"}]},{"type":"text","text":" after sending a response."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Business logic in the router","marks":[{"type":"bold"}]},{"type":"text","text":" – half a year later you have 300-line handlers that cannot be tested without HTTP."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Trusting ","marks":[{"type":"bold"}]},{"type":"text","text":"req.body","marks":[{"type":"code"}]},{"type":"text","text":" without validation","marks":[{"type":"bold"}]},{"type":"text","text":" – "},{"type":"text","text":"{\"quantity\": \"1e9\"}","marks":[{"type":"code"}]},{"type":"text","text":" or an extra "},{"type":"text","text":"\"status\": \"delivered\"","marks":[{"type":"code"}]},{"type":"text","text":" field gets through if nobody checks the schema. "},{"type":"text","text":"z.object()","marks":[{"type":"code"}]},{"type":"text","text":" strips unknown keys by default."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"when-express-and-when-something-else"},"content":[{"type":"text","text":"When Express, and when something else"}]},{"type":"prosCons","attrs":{"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"],"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)"],"prosTitle":"Express pros","consTitle":"Express cons"}},{"type":"paragraph","content":[{"type":"text","text":"If the team is bigger and the project will grow for years, consider "},{"type":"text","text":"NestJS","marks":[{"type":"link","attrs":{"href":"/en/topics/nestjs"}}]},{"type":"text","text":" – 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."}]},{"type":"heading","attrs":{"level":2,"id":"check-yourself"},"content":[{"type":"text","text":"Check yourself"}]},{"type":"quiz","attrs":{"question":"An `async` handler in Express 5 throws after an `await`. What happens?","multiple":false,"options":[{"text":"The request hangs because the promise was rejected without a handler","correct":false,"explanation":"That was Express 4. Version 5 catches rejected promises itself."},{"text":"Express calls `next(err)` and the error middleware handles the request","correct":true,"explanation":"That is exactly why the router has no `try/catch` and no `asyncHandler`."},{"text":"The Node.js process exits with `unhandledRejection`","correct":false,"explanation":"Express 5 handles the rejection, so the `unhandledRejection` event never fires."}]}},{"type":"quiz","attrs":{"question":"The app runs behind an AWS load balancer and the 120 req/min limit blocks all clients at once. The most likely cause?","multiple":false,"options":[{"text":"The limit is too low","correct":false,"explanation":"It may be low, but \"everyone at once\" points to a shared limit key."},{"text":"Missing `trust proxy` – every request has the balancer's IP","correct":true,"explanation":"Set `TRUST_PROXY=1` (the number of proxies in front of the app) and `req.ip` will come from `X-Forwarded-For`."},{"text":"Helmet blocks the `RateLimit` headers","correct":false,"explanation":"Helmet does not touch the rate limit headers."}]}},{"type":"details","content":[{"type":"detailsSummary","content":[{"type":"text","text":"Interview question: how do you organize error handling in an Express API?"}]},{"type":"detailsContent","content":[{"type":"paragraph","content":[{"type":"text","text":"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 "},{"type":"text","text":"(err, req, res, next)","marks":[{"type":"code"}]},{"type":"text","text":" 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 "},{"type":"text","text":"async","marks":[{"type":"code"}]},{"type":"text","text":" 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 "},{"type":"text","text":"res.headersSent","marks":[{"type":"code"}]},{"type":"text","text":" is true."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"what-s-next"},"content":[{"type":"text","text":"What's next"}]},{"type":"paragraph","content":[{"type":"text","text":"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."}]},{"type":"linkCard","attrs":{"url":"/en/articles/nestjs","title":"NestJS in practice","description":"The same API with modules, DI, pipes and guards","kind":"article","ref":"nestjs"}},{"type":"linkCard","attrs":{"url":"/en/articles/swagger-openapi","title":"Swagger and OpenAPI","description":"Docs from Zod schemas and a typed client","kind":"article","ref":"swagger-openapi"}},{"type":"linkCard","attrs":{"url":"/en/articles/authentication","title":"Login and registration","description":"Passwords, sessions, JWT and refresh token rotation","kind":"article","ref":"authentication"}},{"type":"linkCard","attrs":{"url":"/en/topics/layered-architecture","title":"Layered architecture","description":"Where the router, service and repository split comes from","kind":"topic","ref":"layered-architecture"}}]},"toc":[{"id":"step-1-the-project-esm-typescript-and-scripts","text":"Step 1. The project: ESM, TypeScript and scripts","level":2,"locked":false},{"id":"step-2-configuration-and-logging","text":"Step 2. Configuration and logging","level":2,"locked":false},{"id":"step-3-the-domain-schemas-repository-and-service","text":"Step 3. The domain: schemas, repository and service","level":2,"locked":false},{"id":"step-4-routing-and-validation","text":"Step 4. Routing and validation","level":2,"locked":false},{"id":"step-5-consistent-error-handling","text":"Step 5. Consistent error handling","level":2,"locked":false},{"id":"step-6-putting-the-app-together-security-middleware-and-server-startup","text":"Step 6. Putting the app together: security middleware and server startup","level":2,"locked":false},{"id":"step-7-tests-without-opening-a-port","text":"Step 7. Tests without opening a port","level":2,"locked":false},{"id":"step-8-deployment","text":"Step 8. Deployment","level":2,"locked":false},{"id":"common-mistakes","text":"Common mistakes","level":2,"locked":false},{"id":"when-express-and-when-something-else","text":"When Express, and when something else","level":2,"locked":false},{"id":"check-yourself","text":"Check yourself","level":2,"locked":false},{"id":"what-s-next","text":"What's next","level":2,"locked":false}],"locked":false,"paywall":null,"previewRatio":0.3,"totalBlocks":70,"visibleBlocks":70,"resources":[{"id":"6b0857b13c96f2d34d0b3399","type":"repo","provider":"github","url":"https://github.com/goldbergyoni/nodebestpractices","embedUrl":null,"title":"goldbergyoni/nodebestpractices","description":"✅ The Node.js best practices list (July 2026)","author":"goldbergyoni","thumbnailUrl":"https://opengraph.githubassets.com/1/goldbergyoni/nodebestpractices","durationSec":null,"lang":"en","topics":["microservices"],"techs":["node","javascript"],"tags":["best-practices","es6","eslint","express","expressjs","javascript","testing","jest","microservices","mocha"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2017-09-15T08:33:19.000Z","popularity":97,"verifiedAt":"2026-11-26T10:52:30.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:49.541Z","updatedAt":"2026-11-26T16:00:49.541Z"},{"id":"6b0857c13c96f2d34d0b4451","type":"article","provider":"web","url":"https://khalilstemmler.com/articles/enterprise-typescript-nodejs/functional-error-handling","embedUrl":null,"title":"Functional Error Handling with Express.js and DDD | Enterprise Node.js + TypeScript | Khalil Stemmler","description":"How to expressively represent (database, validation and unexpected) errors as domain concepts using functional programming concepts and how to hook those errors up to our Express.js base controller.","author":"Khalil Stemmler","thumbnailUrl":"https://khalilstemmler.com/img/blog/enterprise-node/enterprise-node.png","durationSec":null,"lang":"en","topics":["ddd-strategic-design"],"techs":["node","javascript","typescript"],"tags":["databases","functional-programming","software-architecture"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":50,"verifiedAt":"2026-11-26T11:29:27.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857c73c96f2d34d0b4956","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=uvTT_0hqhyY","embedUrl":"https://www.youtube-nocookie.com/embed/uvTT_0hqhyY","title":"Handling HTTP API Errors with Problem Details","description":"If you're developing an HTTP API, having a consistent way of returning errors can make handling errors on the client-side simpler. I've talked about Problem Details in another video, which is a standard for returning machine-readable details of errors in an HTTP Response. In this video, I'll cover…","author":"CodeOpinion","thumbnailUrl":"https://i.ytimg.com/vi/uvTT_0hqhyY/hqdefault.jpg","durationSec":null,"lang":"en","topics":[],"techs":["dotnet"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"youtube-rss","publishedAt":"2021-09-29T14:00:34.000Z","popularity":64,"verifiedAt":"2026-11-26T10:53:36.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:10.095Z","updatedAt":"2026-11-26T16:01:10.095Z"},{"id":"6b0857b53c96f2d34d0b3896","type":"article","provider":"web","url":"https://stripe.com/blog/rate-limiters","embedUrl":null,"title":"Scaling your API with rate limiters","description":"Online payment processing for internet businesses. Stripe is a suite of payment APIs that powers commerce for businesses of all sizes.","author":"stripe.com","thumbnailUrl":null,"durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["hacker-news"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"hn","publishedAt":"2017-03-30T16:58:10.000Z","popularity":73,"verifiedAt":"2026-11-26T11:19:34.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:52.228Z","updatedAt":"2026-11-26T16:00:52.228Z"},{"id":"6b0857b33c96f2d34d0b3663","type":"repo","provider":"github","url":"https://github.com/NationalBankBelgium/REST-API-Design-Guide","embedUrl":null,"title":"NationalBankBelgium/REST-API-Design-Guide","description":"NBB's REST-ish API Design Guide","author":"NationalBankBelgium","thumbnailUrl":"https://opengraph.githubassets.com/1/NationalBankBelgium/REST-API-Design-Guide","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["design","design-pattern","design-patterns","rest","rest-api","restful","api-design","restful-api","restful-webservices"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"github","publishedAt":"2016-10-12T06:58:57.000Z","popularity":56,"verifiedAt":"2026-11-26T10:57:29.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:50.215Z","updatedAt":"2026-11-26T16:00:50.215Z"}],"challenges":[],"attachments":[],"hasCode":true,"repoUrl":null,"series":[],"prev":null,"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}