app.use()
app.use() registers middleware to run for every request, or for requests under a path.
Syntax
app.use([path], middleware)You attach middleware with app.use(). With just a function, it runs for every request. With a path first, it runs only for requests whose URL starts with that path.
app.use(fn)— runs on all requests.app.use('/admin', fn)— runs only under/admin.
Mounting routers, as you saw earlier, is really just app.use() with a router as the function.
Example
// Runs for every request
app.use((req, res, next) => {
req.requestTime = Date.now();
next();
});
// Runs only for URLs starting with /admin
app.use('/admin', (req, res, next) => {
console.log('Admin area accessed');
next();
});When to use it
- A developer calls app.use(express.json()) once at the top of the app to parse JSON bodies for every POST/PUT route.
- A team mounts a router with app.use('/api/v1', apiRouter) to prefix all v1 routes without repeating the prefix in each route.
- A logging library is registered with app.use(morgan('dev')) so every request is automatically logged to stdout.
More examples
Global middleware with app.use
Registers two built-in parsers globally so all subsequent routes can read structured request bodies.
const express = require('express');
const app = express();
app.use(express.json()); // parse JSON bodies
app.use(express.urlencoded({ extended: true })); // parse form data
app.post('/data', (req, res) => res.json(req.body));
app.listen(3000);Path-scoped middleware
Scopes the adminOnly middleware to /admin so it runs only for paths that start with /admin.
function adminOnly(req, res, next) {
if (!req.user?.isAdmin) return res.status(403).send('Forbidden');
next();
}
app.use('/admin', adminOnly);
app.get('/admin/users', (req, res) => res.send('Admin users list'));
app.get('/public', (req, res) => res.send('Public page'));Mounting a router with app.use
Mounts a Router module under /users with app.use(), so all router paths are automatically prefixed.
const express = require('express');
const app = express();
const userRouter = express.Router();
userRouter.get('/', (req, res) => res.json([]));
userRouter.get('/:id', (req, res) => res.json({ id: req.params.id }));
app.use('/users', userRouter);
app.listen(3000);
Discussion