NestJS Server-Sent Events (SSE) connection doesn’t close automatically and subsequent requests fail silently

I’m building a feature where the frontend sends a POST request to /mailer/inform with an array of email addresses. This triggers sending individual emails to those addresses. I’m using Server-Sent Events (SSE) at the /mailer/email-events endpoint to provide real-time updates to the frontend about the status of each email being sent (success/failure). I expected the SSE connection to close automatically after all email statuses were sent.

Here’s my current code:

mailer.service.ts:

import { Injectable } from '@nestjs/common';
import * as nodemailer from 'nodemailer';
import * as process from 'process';
import { MailerDto } from './mailer.dto';
import { from, Observable, of, Subject, lastValueFrom, share } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import * as EventEmitter from 'events';

@Injectable()
export class MailerService {
  private transporter: nodemailer.Transporter;

  emailEventEmitter = new EventEmitter();

  constructor() {
    this.transporter = nodemailer.createTransport({
      host: process.env.EMAIL_HOST,
      port: process.env.EMAIL_PORT,
      secure: true,
      auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASSWORD,
      },
    });
  }

  // Get email sent event stream
  getEmailSentStream(): Observable<any> {
    return new Observable<any>((observer) => {
      // Listen for 'emailSent' event
      this.emailEventEmitter.on('emailSent', (data: any) => {
        observer.next({ data }); // Send data to SSE
      });
    }).pipe(share());
  }

  // Send interview results emails
  async sendInterviewResults(mailerDto: MailerDto[]): Promise<void> {
    const emailSent$ = new Subject();

    Promise.allSettled(
      mailerDto.map(async (data: MailerDto) => {
        try {
          const result = await lastValueFrom(this.sendEmail(data));
          emailSent$.next(result);
        } catch (error) {
          emailSent$.next({ email: data.email, success: false, error });
        }
      }),
    ).finally(() => emailSent$.complete());

    emailSent$.subscribe((data) => {
      this.emailEventEmitter.emit('emailSent', data);
    });
  }

  private sendEmail(
    data: MailerDto,
  ): Observable<{ email: string; success: boolean; error?: any }> {
    const { email, username, isPassed } = data;
    const mailOptions: nodemailer.SendMailOptions = {
      from: `1*******@qq.com`,
      to: email,
      subject: 'Interview Result Notification',
      html: this.generateEmailContent(username, isPassed),
    };

    return from(this.transporter.sendMail(mailOptions)).pipe(
      map(() => ({ email, success: true })),
      catchError((error) => {
        console.error(`Failed to send interview result email to ${username} (${email}):`, error);
        return of({ email, success: false, error });
      }),
    );
  }

  private generateEmailContent(username: string, isPassed: boolean): string {
    const resultMessage = isPassed
      ? '???????????? Congratulations, you have passed the interview! ????????????'
      : '???????????? We regret to inform you that you did not pass this interview. ????????????';

    return `
      <div style="font-family: Arial, sans-serif; padding: 20px; border-radius: 5px; background-color: #f5f5f5;">
        <h3 style="color: #333;">Dear <span style="color: #007bff;">${username}</span>:</h3>
        <p style="font-size: 16px; line-height: 1.5;">${resultMessage}</p>
        <p style="font-size: 16px; line-height: 1.5;">Thank you for your interest in our organization!????</p>
        <br>
        <p style="font-size: 16px; line-height: 1.5;">Sincerely,</p>
        <p style="font-size: 16px; line-height: 1.5;">Information Technology Association (ITA)</p>
      </div>
    `;
  }
}

mailer.controller.ts:

import { Controller, Post, Body, Sse } from '@nestjs/common';
import { MailerService } from './mailer.service';
import { MailerDto } from './mailer.dto';
import { Observable } from 'rxjs';
import { Public } from '../../../utils/jwt/public.decorator';

@Controller('mailer')
export class MailerController {
  constructor(private readonly mailerService: MailerService) {}

  @Post('inform')
  triggerEmails(@Body() mailerDto: MailerDto[]) {
    this.mailerService.sendInterviewResults(mailerDto).then(() => {});
  }

  @Public()
  @Sse('email-events')
  getEmailEvents(): Observable<any> {
    return this.mailerService.getEmailSentStream();
  }
}

The problem is twofold:

Connection doesn’t close: Even though the frontend receives all email status updates, the SSE connection remains open indefinitely. I expect the connection to close gracefully after all email statuses have been sent.

Subsequent requests fail silently: When I make subsequent requests to the SSE endpoint, the frontend doesn’t receive any data. However, the backend successfully sends the emails, and the connection closes very quickly (within 10-20 milliseconds), without any errors on either side.

It seems like there might be an issue with how I’m handling the connection lifecycle or event listeners. The first request seems to work partially (data is received), but the connection persists, and subsequent requests are somehow blocked or ignored.

How can I ensure the SSE connection closes automatically after each request and that subsequent requests are handled correctly, delivering all email statuses to the frontend?

Any help in identifying the issue and finding a solution would be greatly appreciated!

The first request to the SSE endpoint seems to work partially. The frontend receives the status updates for each sent email. However, the connection remains open indefinitely, even after all email statuses have been delivered. Subsequent requests to the /mailer/email-events endpoint don’t deliver any data to the frontend, and the connection closes prematurely without any errors, despite the emails being sent successfully in the backend.

New contributor

ZK L is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật