Express app.use() Method
What you’ll learn
- How to mount middleware globally and by path using
app.use(). - How path prefixes affect middleware execution.
- How to mount and organize router modules with
app.use(). - How to avoid middleware order and scope mistakes.
Overview
app.use() is the main way to register middleware and mount router modules in Express.
Global middleware
Register middleware for all routes by calling app.use(middleware).
Path-scoped middleware
Limit middleware execution with prefixes like /api or /admin.
Router mounting
Mount feature routers cleanly, for example app.use('/users', userRouter).
Syntax
javascript
app.use(middleware)
app.use(path, middleware)
app.use(path, router)- path: optional prefix for middleware matching.
- middleware: function with
(req, res, next)signature. - router: Express router instance created by
express.Router().
1
Global middleware example
javascript
app.use(function (req, res, next) {
console.log(req.method, req.url);
next();
});2
Mount router with prefix
javascript
const userRouter = require('./routes/users');
app.use('/users', userRouter);📋 app.use() vs app.get()
| Method | Scope | Typical use |
|---|---|---|
app.use() | Middleware/routers (all methods) | Cross-cutting logic and module mounting |
app.get() | GET-only route handler | Endpoint response for GET requests |
🧪 Testing checklist
- Confirm middleware executes for expected path prefixes only.
- Verify router mount paths produce the intended final URLs.
- Check middleware execution order with logging tests.
- Ensure each middleware calls
next()or ends response.
Pitfalls to avoid
Wrong ordering
Middleware not applied
Register middleware before routes that depend on it.
Missing next()
Hanging requests
Always call next() or send response in middleware.
Prefix confusion
Unexpected route matches
Test mounted paths to ensure URL composition is correct.
❓ FAQ
It mounts middleware functions or routers into the request handling pipeline.
Yes. Mounted middleware runs for matching paths regardless of HTTP method unless filtered later.
Using app.use('/api', middleware) means the middleware runs for routes starting with /api.
Yes. app.use('/users', userRouter) mounts all routes defined inside that router under /users.
app.use() mounts middleware broadly, while app.get() defines a GET-only route handler.
Summary
- Core use:
app.use()mounts middleware and routers into Express pipeline. - Scope control: use optional path prefixes for targeted execution.
- Practice: keep middleware order explicit and test mounted paths.
Did you know?
app.use() mounts middleware or routers and can be scoped globally or to specific path prefixes.
4 people found this page helpful
