What Is the Express Morgan Module? A Complete Guide to HTTP Request Logging

The express morgan module is a third-party HTTP request logger middleware that automatically captures and outputs details of every incoming request to your Node.js application.

The express morgan module provides structured, configurable logging capabilities that help developers monitor traffic, debug issues, and analyze application performance. Unlike built-in Express functionality, morgan is maintained as a separate package within the Express.js ecosystem, offering specialized request instrumentation without bloating the core framework.

What Is the Express Morgan Module?

morgan is not part of the Express core; it is a standalone npm package (morgan) developed under the Express.js organization. When integrated into an Express application, the module functions as middleware that intercepts every incoming HTTP request, extracts metadata such as the HTTP method, URL, status code, response time, and user-agent, then writes formatted log entries to a specified output stream.

The express morgan module supports multiple predefined formats including combined, common, dev, short, and tiny, each optimized for different environments and use cases.

How the Morgan Middleware Works in Express

Understanding the architectural role of the express morgan module helps developers implement it effectively without impacting application logic.

Request-Level Instrumentation

The morgan middleware registers a function that executes before your route handlers receive the request. In the morgan source code at morgan/index.js, the middleware captures the req and res objects, attaches listeners to the response finish event, and calculates metrics like response time by comparing timestamps between request arrival and response completion.

Non-Intrusive Integration

Because morgan follows the standard Express middleware signature (req, res, next), adding it to your application requires zero changes to existing route logic. The middleware calls next() immediately after setting up its event listeners, allowing the request to propagate through the remainder of the middleware stack uninterrupted.

Pluggable Formats and Custom Tokens

The express morgan module exposes a token-based architecture. Developers can define custom tokens using morgan.token() to capture application-specific data such as authenticated user IDs or request body sizes. These tokens integrate seamlessly with predefined formats or custom format strings.

Installing and Configuring the Express Morgan Module

Implementing the express morgan module involves installing the package and selecting the appropriate configuration for your environment.

Basic Console Logging

For development environments, the dev format provides colorized, concise output that includes response times.

const express = require('express')
const morgan = require('morgan')

const app = express()

// Log in the predefined "dev" format (colorized, concise)
app.use(morgan('dev'))

app.get('/', (req, res) => {
  res.send('Hello World')
})

app.listen(3000, () => console.log('Server listening on port 3000'))

Production Logging to File

For production environments, use the combined format (Apache-style logs) and write to a rotating file stream to prevent disk space issues.

const express = require('express')
const morgan = require('morgan')
const fs = require('fs')
const path = require('path')
const rfs = require('rotating-file-stream')

const app = express()

// Create a rotating write stream (daily rotation)
const logDirectory = path.join(__dirname, 'log')
fs.mkdirSync(logDirectory, { recursive: true })
const accessLogStream = rfs.createStream('access.log', {
  interval: '1d',
  path: logDirectory
})

// Use the "combined" Apache style format, writing to the rotating file
app.use(morgan('combined', { stream: accessLogStream }))

Custom Tokens for Advanced Tracking

Extend the express morgan module to log application-specific data such as authenticated user IDs.

const express = require('express')
const morgan = require('morgan')

const app = express()

// Define a token that extracts req.user.id if present
morgan.token('user-id', (req) => (req.user && req.user.id) ? req.user.id : '-')

// Include the custom token in the log format
app.use(
  morgan(':method :url :status :response-time ms - :res[content-length] :user-id')
)

Environment-Conditional Logging

Load the express morgan module only in development to avoid performance overhead in production.

if (process.env.NODE_ENV === 'development') {
  const morgan = require('morgan')
  app.use(morgan('dev'))
}

Summary

  • The express morgan module is a third-party middleware package, not part of Express core, that provides HTTP request logging.
  • It operates by registering a middleware function that captures request metadata before route handlers execute, calculating metrics like response time when the response finishes.
  • The module supports multiple predefined formats (dev, combined, common, short, tiny) and allows custom token definitions for application-specific data.
  • Configuration varies by environment: use colorized console output for development and structured file logging with rotation for production.
  • Integration requires no changes to existing route logic, maintaining clean separation between instrumentation and business concerns.

Frequently Asked Questions

Is morgan part of Express core?

No, morgan is not part of the Express core framework. It is a standalone npm package maintained under the Express.js organization. You must install it separately using npm install morgan and require it in your application before adding it to your middleware stack with app.use().

What log formats does morgan support?

The express morgan module ships with five predefined formats: combined (Apache-style logs with referrer and user-agent), common (shorter Apache style), dev (colorized output with response times for development), short (minimal output with response time), and tiny (minimal output without response time). You can also define custom format strings using tokens.

How do I log to a file instead of console?

To write logs to a file, pass a stream option to the morgan middleware. Create a write stream using Node.js fs module or a rotating file stream package, then configure morgan like this: app.use(morgan('combined', { stream: accessLogStream })). This approach keeps logs persistent and manageable through file rotation.

Can I create custom logging tokens?

Yes, the express morgan module exposes a token() method that allows you to define custom data points. Use morgan.token('name', (req, res) => { return value }) to register a new token, then reference it in your format string using :name. This is commonly used to log authenticated user IDs, request IDs, or custom headers.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →