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.
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 |
Successful responses logged with log , errors with error |
|
βοΈ Framework compatibility | Works with both Express and Fastify |
ποΈ Configurable logging levels | Control what data to log: headers, request body, response data |
Install the package using npm or yarn:
npm install @samofprog/nestjs-http-logger
# or
yarn add @samofprog/nestjs-http-logger
Use the helper function in your NestJS bootstrap file:
import { createHttpLoggerMiddleware } 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(createHttpLoggerMiddleware());
await app.listen(3000);
}
bootstrap();
For more advanced use cases with dependency injection:
import { createHttpLoggerProviders } from '@samofprog/nestjs-http-logger';
@Module({
providers: [
...createHttpLoggerProviders({
ignorePaths: ['/health'],
logHeaders: true,
}),
],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(HttpLoggerMiddleware).forRoutes('*');
}
}
You can customize the middleware behavior with options:
import { createHttpLoggerMiddleware } from '@samofprog/nestjs-http-logger';
app.use(createHttpLoggerMiddleware({
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`,
}));
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). | ['authorization', 'cookie', 'set-cookie', 'x-api-key'] |
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, body } . |
Default formatted string |
completedRequestMessage |
(details) => string |
Function returning the log message for completed requests. Receives { method, url, statusCode, durationMs, responseData } . |
Default formatted string |
logHeaders |
boolean |
Whether to include headers in the log messages. | false |
logRequestBody |
boolean |
Whether to include request body in the log messages. | false |
logResponseData |
boolean |
Whether to include response data in the log messages. | false |
app.use(createHttpLoggerMiddleware({
ignorePaths: ['/health', '/metrics'],
sensitiveHeaders: ['authorization', 'cookie'],
}));
app.use(createHttpLoggerMiddleware({
sanitizeHeaders: (headers) => {
const sanitized = { ...headers };
if (sanitized['authorization']) sanitized['authorization'] = '[TOKEN REDACTED]';
if (sanitized['cookie']) sanitized['cookie'] = '[COOKIE REDACTED]';
return sanitized;
}
}));
app.use(createHttpLoggerMiddleware({
logHeaders: true, // Include headers in logs (default: false)
logRequestBody: true, // Include request body in logs (default: false)
logResponseData: true, // Include response data in logs (default: false)
}));
import { Logger } from '@nestjs/common';
const customLogger = new Logger('MyCustomLogger');
app.use(createHttpLoggerMiddleware({ logger: customLogger }));
By default, the following headers are automatically masked:
const DEFAULT_SENSITIVE_HEADERS = [
'authorization',
'cookie',
'set-cookie',
'x-api-key'
];
This package is open-source and available under the MIT License.