1. Concept library
  2. Backend with Node.js
  3. Module 3: Building REST APIs

Concept

Middleware

Middleware runs before or around route handlers to do shared work: logging, authentication, parsing, rate limiting. Each piece does one thing and passes the request along, or ends it with a response.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what middleware does and how a request passes along the chain
  2. Write a logging middleware and an authentication middleware
  3. Spot the middleware that neither calls next nor responds on an error path

In practice

A few lines that show Middleware doing its job.

JavaScript
app.addHook("onRequest", async (req) => {
  req.startedAt = performance.now();
});

app.addHook("onResponse", async (req, reply) => {
  req.log.info({ method: req.method, url: req.url, status: reply.statusCode,
    ms: Math.round(performance.now() - req.startedAt) });
});

app.decorateRequest("user", null);
app.addHook("preHandler", requireUser);   // sets req.user or replies 401

The common mistake

Watch for

Middleware that forgets to call next() or send a response on an error path. The request hangs with no log line, and it only shows up as a timeout in production.

What to know first

Your roadmap puts these before Middleware, unless you already know them.

How it stays learned

Once a session shows you understand Middleware, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on Middleware.

Previous in the module← Routing
Next in the moduleRequest validation →