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 a Nest exception filter such as AllExceptionsFilter plays.

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…

15 questions · concept 5 · syntax 3 · practical 4 · logic 3

1. How does Express match a route?
Concept
2. In what order does Express run middleware?
Syntax
3. When is req.body available for JSON?
Practical
4. What does next(err) typically do?
Logic
5. Why learn Express middleware for Nest?
Concept
6. Which middleware mistake breaks JSON APIs?
Practical
7. What is a reasonable 404 strategy?
Syntax
8. How should you end a response in middleware?
Logic
9. Which claim about route params is true?
Concept
10. What does app.use(path, mw) do?
Practical
11. req.body is undefined in this route. What fixes it?
Conceptintermediate
app.post('/tickets', (req, res) => {
  res.json({ title: req.body.title });
});
// no other app.use(...) calls exist
12. This Express error handler never runs. What is wrong?
Syntaxadvanced
app.use((err, req, res) => {
  res.status(500).json({ message: err.message });
});
13. Which handler runs for DELETE /tickets/5?
Practicalintermediate
app.get('/tickets/:id', h1);
app.post('/tickets', h2);
// request: DELETE /tickets/5
14. What bug does this auth middleware have?
Logicadvanced
app.use((req, res, next) => {
  if (!req.headers.auth) res.status(401).end();
  next();
});
15. A route GET / inside apiRouter is reachable at which path?
Conceptintermediate
app.use('/api', apiRouter);

Checking your session…