Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@samofprog/nestjs-http-logger

samofprog193MIT2.0.1TypeScript support: included

A NestJS middleware for logging HTTP requests

nestjs, fastify, middleware, http, logger, logging, http-logging, request-logging, response-logging, error-logging, nodejs, typescript, api, monitoring, debugging, performance

readme

📡 HttpLoggerMiddleware

npm version License: MIT

HttpLoggerMiddleware is a powerful and configurable middleware for logging HTTP requests and responses in your NestJS application.
It provides detailed logs about incoming requests and completed responses, including HTTP method, URL, headers, response status, and processing duration.
Additional features include masking sensitive headers, ignoring specific paths, and supporting custom loggers.

✨ Features

Feature Description
📥 Detailed request and response logging Logs HTTP method, URL, headers, status codes, and duration
🔒 Sensitive header masking Allows masking sensitive headers like Authorization or Cookie
🚫 Path ignoring Ignore logging on specific paths
📝 Custom log message formatting Customize incoming and completed request log messages
🛠 Custom logger support Use your own LoggerService or fallback to NestJS global logger
⚠️ Log level distinction Successful responses logged with log, errors with error
⚙️ Framework compatibility Works with both Express and Fastify

📦 Installation

Install the package using npm or yarn:

npm install @samofprog/nestjs-http-logger
# or
yarn add @samofprog/nestjs-http-logger

🚀 Usage

Use the middleware in your NestJS bootstrap file:

import { HttpLoggerMiddleware } from '@samofprog/nestjs-http-logger';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.use(HttpLoggerMiddleware.create());

  await app.listen(3000);
}
bootstrap();

⚙️ Usage with Custom Configuration

You can customize the middleware behavior with options:

app.use(HttpLoggerMiddleware.create({
  ignorePaths: ['/health', '/metrics'],
  sensitiveHeaders: ['authorization', 'cookie'],
  sanitizeHeaders: (headers) => {
    const sanitized = { ...headers };
    ['authorization', 'cookie'].forEach(key => {
      if (sanitized[key]) sanitized[key] = '[REDACTED]';
    });
    return sanitized;
  },
  incomingRequestMessage: (details) =>
    `Incoming: ${details.method} ${details.url} → headers: ${JSON.stringify(details.headers)}`,
  completedRequestMessage: (details) =>
    `Completed: ${details.method} ${details.url} ← status ${details.statusCode} in ${details.durationMs} ms`,
}));

🛠 Options

Option Type Description Default
logger LoggerService Custom logger implementing NestJS LoggerService interface. NestJS default logger
ignorePaths string[] List of URL paths to ignore from logging. []
sensitiveHeaders string[] List of header names to mask in logs (case-insensitive). []
sanitizeHeaders (headers: Record<string, any>) => Record<string, any> Function to transform headers before logging (e.g., to mask values). Identity function (no change)
incomingRequestMessage (details) => string Function returning the log message for incoming requests. Receives { method, url, headers }. Default formatted string
completedRequestMessage (details) => string Function returning the log message for completed requests. Receives { method, url, statusCode, durationMs }. Default formatted string

🧩 Examples

🚫 Ignore paths and 🔒 mask sensitive headers

app.use(HttpLoggerMiddleware.create({
  ignorePaths: ['/health', '/metrics'],
  sensitiveHeaders: ['authorization', 'cookie'],
}));

🧼 Custom sanitization of headers

app.use(HttpLoggerMiddleware.create({
  sanitizeHeaders: (headers) => {
    const sanitized = { ...headers };
    if (sanitized['authorization']) sanitized['authorization'] = '[TOKEN REDACTED]';
    if (sanitized['cookie']) sanitized['cookie'] = '[COOKIE REDACTED]';
    return sanitized;
  }
}));

🧼 Custom sanitization of headers

import { Logger } from '@nestjs/common';

const customLogger = new Logger('MyCustomLogger');

app.use(HttpLoggerMiddleware.create({ logger: customLogger }));

📄 License

This package is open-source and available under the MIT License.

changelog

CHANGELOG.md

All notable changes to this project will be documented in this file.

[2.0.1] - 2025-05-22

Added

  • Added sensitiveHeaders option to mask sensitive headers in logs
  • Implemented default header sanitizer function
  • Added header sanitization to protect sensitive information
  • Improved response time precision using process.hrtime()

Changed

  • Updated default log messages to include sanitized headers
  • Improved type safety for header handling

Fixed

  • Fixed potential security issue with logging sensitive headers

[2.0.0] - 2025-05-06

Added

  • Enhanced compatibility with both Express and Fastify frameworks
  • Improved request and response message format with additional details
  • Added support for logging headers in incoming requests
  • Enhanced high-precision response time calculation using process.hrtime
  • Better error detection with differential logging for responses with status codes >= 300

Changed

  • Completely redesigned message format customization through new parameter structure
  • Updated signature for incomingRequestMessage and completedRequestMessage callback functions
  • Improved framework detection and adaptation for request/response handling

Fixed

  • Fixed event handling for both Express and Fastify response objects
  • Ensured compatibility with both frameworks when accessing URL and status information

[1.0.4] - 2025-02-17

Added

  • Added support for ignored paths in logging middleware to prevent logging of specific routes like Swagger assets, CSS, JS, and favicon requests.

[1.0.2] - 2025-01-13

Added

  • Introduced the create static method for easier instantiation of HttpLoggerMiddleware.
  • Added support for a custom logger by providing a logger option in HttpLoggerOptions.
  • Enhanced documentation with examples for using a custom logger and the create method.

Changed

  • Updated middleware implementation to use the logger option, allowing integration with the application's global or custom logger.

[1.0.1] - 2025-01-07

Added

  • Added keywords in package.json to optimize search results.

Fixed

  • Corrected an issue with the middleware that caused it to behave incorrectly with Fastify.

Removed

  • Removed unit tests to rewrite them later with improved coverage and structure.

Updated

  • Updated project documentation and README.

[1.0.0] - 2025-01-06

Added

  • Initial release of the http-logger-middleware package for NestJS.
  • Middleware to log HTTP requests and responses in a customizable manner.
  • Support for logging incoming requests with HTTP method and URL.
  • Support for logging completed requests with HTTP method, URL, status code, and duration.
  • Customizable messages for logging using HttpLoggerOptions.
  • Optional configuration for error logging for requests with status codes >= 300.
  • Added MIT License to the project.

Changed

  • N/A

Fixed

  • N/A