Handling Middleware in Express.js (app.use()
)
Hey there! If you’re working with Express.js, you’ve probably heard about middleware—the backbone of Express that helps in handling requests, responses, logging, authentication, and much more.
And the magic function that makes all this possible? app.use()
!
This post will break down app.use()
, its parameters, and practical use cases while using ECMAScript Modules (ESM) for a modern approach.
What is Middleware in Express.js?
Middleware functions in Express act as gatekeepers in the request-response cycle. They process the request before it reaches the final route handler.
Think of it like security checks at an airport—every passenger (request) must go through multiple checks (middleware) before boarding the flight (getting the response).
Middleware can:
- Modify the
req
(request) andres
(response) objects. - Execute any required code (e.g., authentication, logging).
- Stop the request-response cycle (
res.send()
orres.end()
). - Pass control to the next middleware using
next()
.
Understanding app.use()
in Express.js
The app.use()
method is used to apply middleware in Express. It can be applied globally (for all routes) or for specific routes only.
Syntax ofapp.use()
app.use([path], middlewareFunction);
path
(optional) → Specifies which route(s) the middleware applies to. If omitted, it applies to all routes.middlewareFunction
→ The function that processes the request and decides whether to pass it to the next handler.
Using ESM (ECMAScript Modules) in Express.js
By default, Node.js uses CommonJS (require
), but modern JavaScript prefers ECMAScript Modules (ESM), which uses import/export
.
Enable ESM in Your Express App
Modify your package.json
file:
{
"type": "module"
}
This tells Node.js to treat .js
files as ES modules instead of CommonJS.
Types of Middleware and How app.use()
Works
1️Application-Level Middleware
- This middleware executes for every request, regardless of the route.
Example: Logging Middleware
import express from 'express';
const app = express();
app.use((req, res, next) => {
console.log(`Request received: ${req.method} ${req.url}`);
next();
});
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => console.log('Server running on port 3000'));
2️ Built-in Middleware
Express has built-in middleware functions:
express.json()
→ Parses incoming JSON data.express.urlencoded()
→ Parses URL-encoded data.express.static()
→ Serves static files.
Example: Using express.json()
for JSON Parsing
app.use(express.json());
app.post('/data', (req, res) => {
res.json({ receivedData: req.body });
});
3️ Router-Level Middleware
Middleware for specific group of routes.
Example: Applying Middleware Only to /api
Routes
import { Router } from 'express';
const router = Router();
router.use((req, res, next) => {
console.log('API request received');
next();
});
router.get('/info', (req, res) => {
res.send('Router-level Middleware Example');
});
app.use('/api', router);
4️ Error-Handling Middleware
This middleware catches and handles errors.
Example: Custom Error Handler
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!');
});
5️ Third-Party Middleware
Third-party middleware adds extra features like logging and security.
Common Third-Party Middleware
Middleware | Purpose |
---|---|
morgan |
Logs HTTP requests. |
cors |
Enables Cross-Origin Resource Sharing. |
helmet |
Secures HTTP headers. |
cookie-parser |
Parses cookies. |
Example: Using morgan
for Logging
import morgan from 'morgan';
app.use(morgan('dev'));
app.get('/', (req, res) => {
res.send('Hello, World!');
});
Best Practices for Using app.use()
- Use Specific Middleware Only Where Needed → Avoid applying middleware globally if it’s only needed for a few routes.
- Order Matters → Always place error-handling middleware last.
- Use Third-Party Middleware Wisely → Some middleware (e.g.,
helmet
,cors
) enhance security and performance. - Enable ESM for Cleaner Code → Use
"type": "module"
inpackage.json
.
Final Thoughts
Middleware is what makes Express.js flexible and powerful. with app.use()
, you can log requests, parse data, handle errors, and enhance security.
By using ECMAScript Modules (ESM), your code remains modern, clean, and maintainable.
Got any questions? Drop them in the comments below! Happy coding!