Lesson 2.1

Routing and middleware

Middleware runs in order and each layer can inspect, modify, or short-circuit the request.

15mBeginner18.4k students

Overview

A request passes through a pipeline

Middleware runs in order and each layer can inspect, modify, or short-circuit the request. Parsing, authentication, logging, and rate limiting all belong here rather than repeated in every handler.

Order is behaviour. Authentication before authorisation, body parsing before validation, error handling last. A middleware in the wrong position is a bug that presents as inconsistent behaviour across routes.

Handlers should orchestrate, not implement. A handler that parses, validates, queries, and formats is untestable except through HTTP.

In this lesson you will:

  • Structure routes by resource
  • Compose cross-cutting concerns as middleware
  • Keep handlers thin

Resources

Previous Lesson
Next Lesson
Routing and middleware — API Design with Node.js — Vertex