Fullstack CourseLearn by building
Back to week 1

Topic

Express routing, middleware & errors

Definition

Express is a minimal Node.js web framework that maps HTTP methods and paths to handlers and composes middleware functions over request, response, and next to build an ordered request-processing pipeline.

In simpler words

Express gives Node an HTTP routing and middleware model. Each request moves through matching functions until one sends a response or passes control onward.

Nest uses Express (or Fastify) as its HTTP platform adapter. Learn the raw request flow first so Nest modules, guards, and pipes map to something concrete.

After this you can

  • Define routes with method + path and return JSON responses
  • Order middleware for parsing, logging, auth, and errors
  • Read req.params, req.query, and req.body safely
  • Explain what Nest adds on top of Express routing

Routes and handlers

Definition

An Express route binds an HTTP method and path pattern to a handler function that receives request and response objects and may call next to delegate control.

In simpler words

app.get, app.post, app.patch, and app.delete register handlers. Handlers should stay thin and delegate business logic to services.

Path parameters live in req.params; query strings in req.query; JSON bodies in req.body after body-parsing middleware runs.

Set the status code explicitly for creates and errors. Return JSON with res.json or res.status(...).json(...).

A handler that throws without an error boundary can crash the process unless async errors are forwarded with next(error).

Minimal Notes routes

const app = express();
app.use(express.json());

app.get('/notes', async (_req, res) => {
  res.json(await notes.list());
});

app.post('/notes', async (req, res) => {
  const note = await notes.create(req.body);
  res.status(201).json(note);
});

This is the shape Nest controllers reproduce with decorators, DTO validation, and dependency injection.

Middleware order and error handling

Definition

Express middleware is a function (req, res, next) registered in order; each piece may end the response, mutate the request, or call next() to continue the chain.

In simpler words

Order matters: parsers and correlation IDs first, auth before protected routes, and error middleware after routes.

Global middleware such as express.json() should run before route handlers that read req.body.

Route-specific middleware can enforce authentication before a handler executes.

A four-argument error handler (err, req, res, next) formats failures consistently — the same role AllExceptionsFilter plays in apps/api.

Middleware chain

app.use(express.json());
app.use(correlationIdMiddleware);

app.use('/notes', requireAuth);
app.use('/notes', notesRouter);

app.use((err, _req, res, _next) => {
  res.status(err.status ?? 500).json({
    statusCode: err.status ?? 500,
    message: err.message ?? 'Internal server error',
  });
});

Nest keeps the same ordering idea: middleware → guards → pipes → handler → exception filters.

Keep in mind

  • Keep handlers thin — validation and persistence belong in dedicated layers.
  • Register error middleware after routes so thrown errors have one exit path.
  • Nest is not a replacement for Node or Express; it structures the HTTP layer Nest already sits on.

Test

Check your understanding

At least 10 questions — mix of concept, syntax, practical, and logic. Score ≥ 80% (enforced by the API) to save progress.

Checking your session…

10 questions · concept 3 · syntax 2 · practical 3 · logic 2

Concept1. Which statement best defines Express routing and middleware?
Syntax2. Which code-level choice matches Express routing and middleware?
Practical3. A reviewer spots a bug related to Express routing and middleware. What is the right fix?
Logic4. Which reasoning correctly explains Express routing and middleware?
Concept5. Which boundary does correct use of Express routing and middleware preserve?
Practical6. What is the safest next step when applying Express routing and middleware?
Syntax7. Which implementation direction matches the rule for Express routing and middleware?
Logic8. Which consequence follows from applying Express routing and middleware correctly?
Concept9. Which claim about Express routing and middleware is true in this Nest + Postgres monorepo?
Practical10. Which team practice best demonstrates Express routing and middleware?