Morgan HTTP Logger
Morgan is an HTTP request logger middleware for Node.js, often used with the Express framework. It allows developers to log request details such as method, URL, status, and response time in various predefined or custom formats. The current stable version is 1.10.1. Releases occur infrequently, with the latest update focusing on minor fixes and dependency updates, indicating a mature and stable library.
Common errors
-
SyntaxError: Cannot use import statement outside a module
cause Attempting to use ES module `import` syntax (`import morgan from 'morgan'`) in a CommonJS-only Node.js environment or for this CommonJS-only package.fixUse the CommonJS `require` syntax: `const morgan = require('morgan');` -
TypeError: app.use() requires a middleware function but got a Object
cause This error typically occurs in Express.js when you pass `morgan` (the module itself) directly to `app.use()` instead of calling it to get the middleware function (e.g., `morgan('dev')`).fixCall `morgan` with a format string or custom function to create the middleware, for example: `app.use(morgan('dev'));`
Warnings
- gotcha When using the `immediate: true` option, logs are written on request instead of response. This means response-specific data (like `:status` or `:res[content-length]`) will not be available in the log line, or may appear as `undefined`.
- deprecated The `DEBUG_FD` environment variable, used for debugging output stream, was deprecated in `morgan` v1.8.0.
- breaking The behavior of the `:response-time` token changed in v1.6.0. Previously, it might have included response latency (the time taken to *send* the response). From v1.6.0 onwards, it strictly measures the time from request start to when response headers are sent.
- gotcha Prior to v1.9.1, using certain special characters in custom format strings could lead to incorrect logging or parsing issues.
Install
-
npm install morgan -
yarn add morgan -
pnpm add morgan
Quickstart
const express = require('express');
const morgan = require('morgan');
const app = express();
const port = process.env.PORT ?? 3000;
// Use 'dev' format for concise colored output during development
app.use(morgan('dev'));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.get('/error', (req, res) => {
res.status(500).send('Something broke!');
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});