Logging all the requests coming through an Express app
By Flavio Copes
Learn how to log all the requests coming through an Express app, using the express-requests-logger middleware or a simple custom middleware function.
To log all the requests coming through an Express app, you add a middleware that runs before your routes. Every request passes through it, so it’s the perfect place to print what’s happening to the console.
I had this need on one of my projects, in a simple way: log requests to the console. No time (and no need) for more complex setups.
Why a middleware?
Express handles each request through a chain of functions, in the order you register them. A function registered with app.use() runs for every request, no matter which route matches. That makes it the natural spot for logging.
Using express-requests-logger
I installed express-requests-logger:
npm install express-requests-logger
I imported it in my Node app:
import audit from 'express-requests-logger'
and added that as a middleware to my Express app:
app.use(audit())
Done!
Every request and its response now shows up in the logs. The library has lots of options, formatting and filters you can use without reinventing the wheel: you can mask sensitive body fields like passwords, exclude noisy URLs like a /health endpoint, and plug in your own logger.
Writing your own middleware
If you don’t want a dependency, a few lines of code do the job:
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`)
next()
})
Hit a few pages and this is what you get in the console:
GET /
GET /products
POST /cart
Be careful with console.log(req). It works, but it floods the terminal with hundreds of lines per request. Logging the method and the URL is usually all you need.
Remember to call next(). If you don’t, the request stops inside the middleware and Express never reaches your routes: the browser hangs until it times out.
One thing that bit me
Middleware order matters. Register the logger before your routes.
If you register it after, any route defined earlier sends its response and the logger never runs, so those requests don’t show up. Put app.use(audit()) at the top, right after you create the app object.
Related posts about node: