Skip to main content
Node.js & Express·Lesson 3 of 5

Routing and Middleware

Routing determines how your application responds to client requests. Middleware functions are the backbone of Express — they process requests at every stage of the pipeline.

Route Methods

Express provides methods for every HTTP verb:

Ctrl+Enter
HTML
CSS
JS
Preview

HTTP Methods at a Glance

MethodPurposeIdempotent
GETRetrieve a resourceYes
POSTCreate a new resourceNo
PUTReplace a resource entirelyYes
PATCHPartially update a resourceYes
DELETERemove a resourceYes

Route Parameters

Capture dynamic values from the URL path:

Ctrl+Enter
HTML
CSS
JS
Preview

Query Parameters

Query parameters come after ? in the URL:

Ctrl+Enter
HTML
CSS
JS
Preview

Route Chaining with route()

Group different methods for the same path:

Ctrl+Enter
HTML
CSS
JS
Preview

What is Middleware?

Middleware functions have access to the request object, response object, and the next function. They can execute code, modify the request/response, end the request-response cycle, or call next() to pass control to the next middleware.

Ctrl+Enter
HTML
CSS
JS
Preview

The Middleware Pipeline

Requests flow through middleware in the order they are registered:

Request  Logger  Auth  Route Handler  Error Handler  Response
Ctrl+Enter
HTML
CSS
JS
Preview

Building Custom Middleware

Request Logger

Ctrl+Enter
HTML
CSS
JS
Preview

Request Validator

Ctrl+Enter
HTML
CSS
JS
Preview

Rate Limiter

Ctrl+Enter
HTML
CSS
JS
Preview

CORS Middleware

Cross-Origin Resource Sharing allows your API to be called from different domains:

npm install cors
Ctrl+Enter
HTML
CSS
JS
Preview

Serving Static Files

Ctrl+Enter
HTML
CSS
JS
Preview

Files in the public directory become accessible at the root URL (or under /assets with the prefix).

Error Handling Middleware

Error middleware has four parameters — Express identifies it by the (err, req, res, next) signature:

Ctrl+Enter
HTML
CSS
JS
Preview

Practical Exercise

Build a middleware stack for a production API:

Ctrl+Enter
HTML
CSS
JS
Preview

Key Takeaways

  • Express routes match HTTP methods and URL patterns to handler functions.
  • Middleware functions form a pipeline — each can modify the request/response or pass control with next().
  • Register middleware in order: parsers first, then loggers, auth, routes, and error handlers last.
  • Custom middleware like validators and rate limiters keep your route handlers clean.
  • Error-handling middleware must have exactly four parameters: (err, req, res, next).