Node.js
What is middleware?
Learn the middleware concept and the next function.
What is middleware?
Middleware is a function inserted between a request and a response in Express. Each middleware takes three parameters: req (request), res (response) and next (pass to next). Example: function logger(req, res, next) { console.log(req.url); next(); }.
The next() call passes control to the next middleware or route. If next() is not called the request hangs; no response is ever sent. Middlewares form a chain: each runs in turn and calls next() to move on. This chain is the basis of request handling: you can split logging, authentication, data parsing into separate middlewares.
Middleware signature
A middleware function takes three parameters: (req, res, next). req is the incoming request, res the response, next the function to pass control.
Example logging middleware: function logger(req, res, next) { console.log(req.method + " " + req.url); next(); }. This prints the method and URL on every request and continues the chain with next(). We register it with app.use(logger) so it runs before all routes. If middleware is registered before route definitions it runs on every request; if after, only on routes that follow.
Exercise Write the logger middleware
Define logger(req, res, next) with body console.log(req.method + " " + req.url); next();. Add it with app.use(logger). Define the route app.get("/", (req, res) => res.send("Hello")). The server closes itself.
Show example solution
const express = require("express");
const app = express();
function logger(req, res, next) {
console.log(req.method + " " + req.url);
next();
}
app.use(logger);
app.get("/", (req, res) => res.send("Hello"));
const server = app.listen(3000, () => {
const http = require("http");
http.get("http://localhost:3000/", (res) => {
let body = "";
res.on("data", (c) => body += c);
res.on("end", () => { console.log("Reply: " + body); server.close(); });
});
});
Test yourself
-
What does next() do?
function mw(req, res, next) { next(); }
- Closes the server
- Passes control to the next one
- Sends the response
- Deletes the request
Show answer
Passes control to the next one — next() passes control to the next middleware.
-
Complete the logger body
function logger(req, res, next) {
console.log(req.method + " " + req.url);
____();
}
Show answer
function logger(req, res, next) {
console.log(req.method + " " + req.url);
next();
}
-
Match each piece to its role
- req
- Incoming request
- res
- Response object
- next
- Pass to next
- app.use
- Registers middleware
Next lesson: app.use