How to Log Requests in Express: Simple Middleware Example
next() to continue processing. Alternatively, use the morgan library for advanced logging.Syntax
Logging requests in Express is done using middleware functions. A middleware function takes three arguments: req (request), res (response), and next (to pass control). You log request details inside the middleware, then call next() to let Express continue handling the request.
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});Example
This example shows a complete Express app that logs each incoming request's method and URL to the console. It uses a simple middleware function before defining routes.
import express from 'express'; const app = express(); const port = 3000; // Middleware to log requests app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); }); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
Common Pitfalls
Not calling next(): If you forget to call next() in your logging middleware, the request will hang and never reach your routes.
Logging too much or too little: Logging only the method and URL is simple, but sometimes you want more details like headers or body. Be careful not to log sensitive data.
Using synchronous logging: Console logging is synchronous and can slow down your app if overused. For production, consider using logging libraries.
/* Wrong: missing next() causes request to hang */ app.use((req, res) => { console.log(`${req.method} ${req.url}`); // next() missing here }); /* Right: call next() to continue */ app.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next(); });
Quick Reference
- Middleware signature:
(req, res, next) => {} - Log request method and URL:
console.log(`${req.method} ${req.url}`) - Call
next()to continue: Always callnext()in middleware - Use
morganfor advanced logging: Install withnpm i morganand useapp.use(morgan('dev'))