Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
How to handle when client disconnects on NestJS

I am working with NestJS and I need to know when a client has forced the disconnection or has canceled it. (either by mistake or because they wanted to).

For exaple, in Express it's as easy as:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (expressRequest, expressResponse) => {

    // Detecting close event
    expressRequest.on('close', function() {
        console.log('Client connection closed....!');
    });
    // Detecting end event
    expressRequest.on('end', function() {
        console.log('Client connection end....!');
    });

    expressResponse.send('Hello World!')
})

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
})

The question is: working with NestJS, what is the correct way to do it?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Nestjs has many different components that are executed at different times during the life cycle of a request.

The order in which these components are executed would be the following

NestJs request Life cycle

  • Incoming request
  • Globally bound middleware
  • Module bound middleware
  • Global guards
  • Controller guards
  • Route guards
  • Global interceptors (pre-controller)
  • Controller interceptors (pre-controller)
  • Route interceptors (pre-controller)
  • Global pipes
  • Controller pipes
  • Route pipes
  • Route parameter pipes
  • Controller (method handler)
  • Service (if exists)
  • Route interceptor (post-request)
  • Controller interceptor (post-request)
  • Global interceptor (post-request)
  • Exception filters (route, then controller, then global)
  • Server response**

The answer to your question: I think it should be detected in the following points

  • Global interceptor (post-request)
  • Controller interceptor (post-request)
over 4 years ago · Santiago Trujillo Relatório

0

The first thing I would try is using the @Req() param decorator. Assuming you're using Nests default Express adapter, then the request object received is the Express req object.

The following should work for you. The rest of this post is just cleaning it up and making it more "Nest".

import { Controller, Get, Req } from '@nestjs/common';
import { Request } from 'express';

@Controller()
export class AppController{
  @Get()
  test(@Req() req: Request): string {
   
    req.on('close', () => console.log('Doing something with closed connection'))

    return "Hello, world!"
  }
}

If you're planning to reuse this logic in a few controller methods, then I would also consider creating a custom decorator for it:

import { createParamDecorator, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Request } from 'express';

export const OnConnectionClosed = createParamDecorator(
  (data: unknown, ctx: ExecutionContext) =>
    new Observable((observer) => {
      const request = ctx.switchToHttp().getRequest<Request>();

      request.on('close', () => observer.complete());
    }),
);

And then using it like the following:

@Controller()
export class AppController{

  @Get()
  test(@OnConnectionClosed() onClosed: Observable<void>): string {
    onClosed.subscribe({
      complete: () => console.log('Connection closed'),
    });

    return 'Hello, world!';
  }
}

And with that, you've created your own "Nest" way to listen for close events on the incoming request.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda