0
0
ExpressHow-ToBeginner · 3 min read

How to Log Requests in Express: Simple Middleware Example

To log requests in Express, use middleware that runs on every request. You can create a simple function that logs details like method and URL, then call 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.

javascript
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.

javascript
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}`);
});
Output
Server running on http://localhost:3000 GET /
⚠️

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.

javascript
/* 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 call next() in middleware
  • Use morgan for advanced logging: Install with npm i morgan and use app.use(morgan('dev'))

Key Takeaways

Use middleware functions to log requests in Express.
Always call next() in your logging middleware to avoid hanging requests.
Log basic info like HTTP method and URL for simple debugging.
Consider using the morgan library for more detailed and configurable logging.
Avoid logging sensitive data and be mindful of performance in production.