Skip to content

Cannot get http-headers from FastifyReply res.getHeaders('content-length') - causing undefined #7

@ruwbine

Description

@ruwbine
  • In logger.middleware.ts here's a bug with undefined getHeaders with fastifyReply
  • Expected behavior - getting properly headers from response
// logging.middleware.ts
import { Injectable, NestMiddleware, Logger } from '@nestjs/common';
import { FastifyReply, FastifyRequest } from 'fastify';

@Injectable()
export class LoggingMiddleware implements NestMiddleware {
  private readonly logger = new Logger('HTTP');

  use(req: FastifyRequest, res: FastifyReply['raw'], next: () => void) {
    const { method, originalUrl } = req;
    const start = Date.now();

    res.on('finish', () => {
      const { statusCode } = res;
      // TODO: Consider using a more robust way to get content length, cause we're getting undefined from res.getHeader
      // This might be due to the way Fastify handles responses. 

      const contentLength = res.getHeader('content-length') || 0; // <-- The bug is here
      const responseTime = Date.now() - start;

      this.logger.log(
        `${method} from: ${originalUrl}, status_code: ${statusCode}, ${contentLength} - ${responseTime}ms from ip: ${req.ip}`,
      );
    });

    next();
  }
}

// This middleware logs HTTP requests and responses, including method, URL, status code, content length, and response time.
// It can be applied globally or to specific routes in a NestJS application.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions