Node.js
app.use
Learn global middleware with app.use.
Global middleware with app.use
app.use(fn) registers a middleware globally for all requests. The registered middleware runs before all routes defined after app.use. Example: app.use((req, res, next) => { req.requestId = 1; next(); });.
This middleware adds a requestId property to every request. Later routes can access it via req.requestId. Global middleware is used for adding request properties (timestamps, request ids), logging and security checks. The key point is app.use order: if a middleware is not registered before route definitions it will not run for those routes.
Order matters
In Express registration order matters. Middlewares and routes run in the order they are registered. If app.use(logger) is called after app.get("/", handler), the logger will not run for that route.
The correct layout: first app.use for global middlewares, then routes. Example: app.use(express.json()); app.post("/data", handler);. Here express.json() is registered first, so req.body is filled in the /data route. If the order is wrong req.body stays undefined. This principle applies to all middlewares: register first, then use.
Exercise Add the requestId middleware
Add middleware with app.use((req, res, next) => { req.requestId = 1; next(); }). Define the route app.get("/", (req, res) => res.send("Request: " + req.requestId)). The server closes itself.
Show example solution
const express = require("express");
const app = express();
app.use((req, res, next) => {
req.requestId = 1;
next();
});
app.get("/", (req, res) => res.send("Request: " + req.requestId));
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
-
Complete the app.use call
app.____((req, res, next) => { req.requestId = 1; next(); });
Show answer
app.use((req, res, next) => { req.requestId = 1; next(); });
-
Match each piece to its role
- app.use
- Adds global middleware
- req.requestId
- Adds a property to request
- next()
- Continues the chain
- req, res, next
- Middleware parameters
-
When does an app.use middleware run?
app.use((req, res, next) => { next(); });
- Only on errors
- Only on POST requests
- On every request (for routes registered after it)
- When the server closes
Show answer
On every request (for routes registered after it) — It runs on all routes after registration.
Next lesson: Router middleware