Application-Level Middleware in Express.js
Application-level middleware is registered on an Express.js
application using methods such as app.use()
and app.METHOD().
It allows developers to execute common logic before a request reaches its route handler. For example, we can log incoming requests, check user authentication, validate request data, and add useful information to the request object.
In this tutorial, we will learn how to create application-level
middleware, apply it to all routes or selected paths, and
control request processing using next().
1. What Is Application-Level Middleware?
Application-level middleware is middleware registered directly
on an Express application instance, usually stored in a variable
named app.
It can run for every request or only for requests matching a particular path, depending on how it is registered.
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('Application middleware executed');
next();
});
Here, app.use() registers middleware on the
application. The middleware logs a message and calls
next() to pass control to the next middleware
or matching route handler.
2. Syntax of Application-Level Middleware
There are two common ways to register application-level middleware.
A. Using app.use()
app.use((req, res, next) => {
// Middleware logic
next();
});
Without a path argument, this middleware can run for requests that reach it, depending on the request method and middleware stack order.
B. Using a Specific Path
app.use('/admin', (req, res, next) => {
console.log('Admin middleware executed');
next();
});
This middleware runs for requests whose paths match
/admin, including paths such as
/admin/dashboard.
3. Application Middleware for All Requests
We can use application-level middleware to log every request that reaches the middleware. This is useful for understanding which routes users are accessing.
Example: Request Logging Middleware
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('Method:', req.method);
console.log('URL:', req.url);
next();
});
app.get('/', (req, res) => {
res.send('Welcome to Home Page');
});
app.get('/about', (req, res) => {
res.send('Welcome to About Page');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Run the application:
npm install express
node app.js
Open http://localhost:3000 and then
http://localhost:3000/about in your browser.
Example terminal output:
Server running on port 3000
Method: GET
URL: /
Method: GET
URL: /about
The middleware logs the HTTP method and URL before the corresponding route handler sends the response.
4. Application Middleware for a Specific Route
Sometimes, middleware should execute only for a particular section of an application. For example, we may want to run a check before allowing access to admin routes.
const express = require('express');
const app = express();
app.use('/admin', (req, res, next) => {
console.log('Admin section accessed');
next();
});
app.get('/admin', (req, res) => {
res.send('Admin Home Page');
});
app.get('/admin/dashboard', (req, res) => {
res.send('Admin Dashboard');
});
app.get('/', (req, res) => {
res.send('Public Home Page');
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Try these URLs:
| URL | Middleware Runs? | Response |
|---|---|---|
/ |
No | Public Home Page |
/admin |
Yes | Admin Home Page |
/admin/dashboard |
Yes | Admin Dashboard |
5. Middleware Using app.get()
Application-level middleware can also be registered using
HTTP method-specific methods. For example, a callback registered
with app.get() can execute as part of handling
matching GET requests.
const express = require('express');
const app = express();
app.get(
'/profile',
(req, res, next) => {
console.log('Profile middleware executed');
next();
},
(req, res) => {
res.send('User Profile Page');
}
);
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Here, the first callback acts as middleware for the GET
/profile request. It calls next(),
allowing the second callback to send the response.
Browser URL:
http://localhost:3000/profile
Browser output:
6. How Application-Level Middleware Works
Express processes middleware and route callbacks in their
registered order. Calling next() passes control
forward through the middleware stack.
Client Request
Browser requests a URL
Application Middleware
Logs, checks, or processes the request
next()
Passes control to the next handler
Route Handler
Processes the requested route
Response
Sends the result to the client
next(err). In those cases, the normal flow
can change.
7. Difference Between Global and Path-Specific Middleware
| Global Application Middleware | Path-Specific Middleware |
|---|---|
| Registered without a path. | Registered with a path such as /admin. |
| Can run for all matching requests reaching it. | Runs only for requests matching the specified path. |
| Useful for request logging and common processing. | Useful for processing a specific section of an application. |
app.use(middleware) |
app.use('/admin', middleware) |
Important Points to Remember
- Application-level middleware is registered on the Express application.
app.use()registers middleware with an optional path.- Middleware without a path can run for all requests that reach it.
- Path-specific middleware runs for matching paths.
app.get()can register callbacks for GET requests.- Middleware registration order matters.
- Call
next()to continue processing when appropriate. - Logging is not a replacement for authentication or authorization.
Summary
Application-level middleware is registered directly on an Express.js application. It can execute for all requests reaching it or only for requests matching a specified path.
By using app.use() and method-specific
registration such as app.get(), developers
can organize common request-processing logic and control
how requests move through the application.