🎓 A1Learner
🔍
0 of 50 lessons completed

Middleware

Middleware is a function that runs between the ask and the route. Each ask passes through it on the way to the route.

A print step

This step prints the method and the path of each ask.

app.use((req, res, next) => {
  console.log(req.method, req.path);
  next();
});

Ask for the notes

This command asks for the notes list.

curl http://localhost:3000/notes

Example

const express = require("express");

const app = express();
const notes = [{ id: 1, text: "Buy milk" }];

app.use((req, res, next) => {
  console.log(req.method, req.path);
  next();
});

app.get("/notes", (req, res) => {
  res.json(notes);
});

app.listen(3000, () => {
  console.log("Notes API running on http://localhost:3000");
});

Key points

  • Middleware is a function that runs between the ask and the route.
  • Each ask passes through it on the way to the route.
  • Use app.use with a function to add middleware.
  • The function takes a request, a response, and next.
  • next is a function that passes the ask onward.
  • Call next() to hand the ask to the next step.

In this example, the app.use line adds a print step. The step prints the method and the path of each ask. Then next() hands the ask to the route. The GET route sends the notes back as JSON. When a browser asks for /notes, the server prints GET /notes first.

Note

Without next(), the ask stops and the route never runs.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does next() do in middleware?