Run logging or request preprocessing
Cross-cutting request processing
Express.js · Module
app.use() mounts application-level middleware, optionally at a path. Express runs matching middleware in registration order, and each middleware either completes the response or passes control onward with next().
app.use() adds application-level middleware to the request pipeline. With an optional path, Express runs it when the request path matches that mount point; middleware can inspect or modify the request and response, finish the response, or call next() to continue.
app.use([path,] callback [, callback...])| Name | Type | Description |
|---|---|---|
path | string or path pattern | Optional mount path at which the middleware is applied; defaults to / when omitted. |
callback | function | One or more middleware callback functions to execute for matching requests. |
The page documents app.use() as a middleware-registration method but does not specify a return value.
/, making it eligible for every request./static prefix./admin applies to /admin and paths such as /admin/reports.const express = require('express');
const app = express();
app.use('/admin', (req, res, next) => {
console.log(req.method, req.path);
next();
});
app.get('/admin', (req, res) => res.send('Admin'));
app.listen(3000);Logs requests under /admin, then passes control to the matching route.
Cross-cutting request processing
Scoped processing
Static assets
Request pipeline composition
app.use() do?app.use() registers application-level middleware. It can be mounted globally or at a path, and the middleware receives req, res, and next.
Follow-up: How would you restrict handling to one HTTP method? Use app.METHOD(), such as app.get(), because app.use() is not method-specific.
The first argument may be a mount path; when omitted, the path defaults to /, so the middleware runs for every request. A path such as /user/:id limits execution to matching requests.
Follow-up: What happens for /user/42/profile? It can still match because the request path follows the mounted path with /.
next()?Middleware can end the request-response cycle or call next() to transfer control to the next middleware. If it does neither, the request remains pending.
Follow-up: Why can registration order change behavior? Earlier middleware executes first and may modify, terminate, or prevent later processing.
app.METHOD()app.all()app.route()express.static()router.use()