Cross-cutting application middleware
Apply logging, authentication, parsing, or other shared processing across application requests.
Express.js · Function
app.use() binds application-level middleware to an Express app, globally or under a path. Middleware can handle a request, modify it, end the response, or pass control onward with next().
app.use() attaches middleware to an Express application. It can apply middleware globally or under a path, and middleware controls whether processing ends or continues by sending a response or calling next().
app.use([path,] callback [, callback...])| Name | Type | Description |
|---|---|---|
path | string or path pattern | Path or route where the middleware applies. |
middleware | function(req, res, next) | Middleware function to invoke for matching requests. |
The documentation does not specify a return value for app.use().
const express = require('express');
const app = express();
app.use('/user/:id', (req, res, next) => {
console.log('Request Type:', req.method);
next();
});
app.get('/user/:id', (req, res) => {
res.send(`User ${req.params.id}`);
});
app.listen(3000);Mounts application-level middleware for requests matching the path, then passes control to the route handler.
Apply logging, authentication, parsing, or other shared processing across application requests.
Run middleware only for a URL subtree such as /user/:id.
Compose several middleware functions into an ordered request pipeline.
app.use() binds application-level middleware to an Express app. With a path argument, the middleware applies to requests matching that path; without one, it can run for every request.
Follow-up: How do you attach middleware to only one HTTP method? Use app.METHOD(), such as app.get() or app.post(), with the method-specific handler.
A middleware function receives req, res, and next. It can execute code, modify the request or response, end the cycle, or call next() to transfer control to the following middleware.
Follow-up: What happens if it neither ends the cycle nor calls next()? The request remains unresolved and can hang.
Middleware is executed in registration order, so app.use() placement determines when it runs relative to other middleware and routes. A path-scoped middleware can inspect route parameters when mounted appropriately.
Follow-up: How is router-level middleware expressed? Use router.use() and router.METHOD() on an Express Router instance.
app.METHOD()router.use()router.METHOD()express.Router()