Search code examples
node.jsnestjsfastify

FST_ERR_REP_ALREADY_SENT when trying to sendFile on Nestjs notfoundExecption


I want to serve spa app with nestjs and fastify, it works but when I refresh a 404 is triggered. So I wrote an exception to catch the 404 and send the file but I keep getting FST_ERR_REP_ALREADY_SENT error.

My code below

import { Catch, ExceptionFilter, ArgumentsHost, HttpException, NotFoundException } from '@nestjs/common';
import { FastifyReply } from 'fastify';

@Catch(NotFoundException)
export class NotFoundExceptionFilter implements ExceptionFilter {
  catch(_exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse() as FastifyReply;
    response.sendFile('index.html');
  }
}

I want 404 to serve the index.html file


Solution

  • I have had this issue in the past and an update from Nest 8 to 9.x fixed the bug. @Cavdy you may want to update to the latest Nest, atleast anything >=9 and you should be good to go.