Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!