NestJS FCM – Error fetching access token: Error while making request: read ECONNRESET. Error code: ECONNRESET

I have set up a nestJS project to send messages using Firebace(FCM)

app.module.ts

import { Module } from '@nestjs/common';
import { FirebaseModule } from './firebase.module';
import { NotificationController } from './notification.controller';
import { NotificationService } from './notification.service';
import { AppService } from './app.service';
import { AppController } from './app.controller';

@Module({
  imports: [FirebaseModule],
  controllers: [NotificationController, AppController],
  providers: [NotificationService, AppService],
})
export class AppModule {}

app.controller.ts

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }

  @Get('readiness')
  getReadiness(): string {
    return this.appService.getReadiness();
  }

  @Get('liveness')
  getLiveness(): string {
    return this.appService.getLiveness();
  }
}

app.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }

  getLiveness(): string {
    return 'Alive';
  }

  getReadiness(): string {
    return 'Ready';
  }
}

firebase.module.ts

import { Module } from '@nestjs/common';
import * as admin from 'firebase-admin';
import { FirebaseService } from './firebase.service';

import * as serviceAccount from './google-services.json';

// import { applicationDefault } from 'firebase-admin/app';

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
});

@Module({
  providers: [
    {
      provide: 'FIREBASE_INSTANCE',
      useValue: admin,
    },
    FirebaseService,
  ],
  exports: [FirebaseService],
})
export class FirebaseModule {}


firebase.service.ts

import { Injectable, Inject, Logger } from '@nestjs/common';
import * as admin from 'firebase-admin';

@Injectable()
export class FirebaseService {
  private readonly logger = new Logger(FirebaseService.name);

  constructor(
    @Inject('FIREBASE_INSTANCE') private readonly firebase: admin.app.App,
  ) {}

  async sendPushNotification(deviceToken: string, payload: any) {
    try {
      const message = {
        data: payload,
        token: deviceToken,
      };
      const response = await this.firebase.messaging().send(message);
      console.log('Notification sent successfully: ', response);
      this.logger.log('Notification sent successfully: ', response);
    } catch (error) {
      console.error('Error sending notification: ', error);
      this.logger.error('Error sending notification: ', error);
      throw error;
    }
  }
}


notification.controller.ts

import {
  Body,
  Controller,
  HttpException,
  HttpStatus,
  Post,
} from '@nestjs/common';
import { NotificationService } from './notification.service';

@Controller('notifications')
export class NotificationController {
  constructor(private readonly notificationService: NotificationService) {}

  @Post('send')
  async sendPushNotification(
    @Body() body: { deviceToken: string; payload: any },
  ) {
    const { deviceToken, payload } = body;

    try {
      await this.notificationService.sendPushNotification(deviceToken, payload);
      return { message: 'Push notification sent' };
    } catch (error) {
      console.error('Error: ', error);
      throw new HttpException(
        'Failed to end push notification',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }
}


notification.service.ts

import { Injectable, Logger } from '@nestjs/common';
import { FirebaseService } from './firebase.service';

@Injectable()
export class NotificationService {
  private readonly logger = new Logger(NotificationService.name);

  constructor(private readonly firebaseService: FirebaseService) {}

  async sendPushNotification(deviceToken: string, payload: any) {
    try {
      await this.firebaseService.sendPushNotification(deviceToken, payload);
      this.logger.log('Push notification sent successfully');
    } catch (error) {
      this.logger.error('Error sending push notification:', error);
      throw error;
    }
  }
}


I tried a POST request to the service for sending the notification and I got the error:

Error sending notification:  FirebaseAppError: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: read ECONNRESET. Error code: ECONNRESET".
    at C:UsersachuanWORKfirebase-pocnode_modulesfirebase-adminlibappfirebase-app.js:86:19
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at FirebaseService.sendPushNotification (C:UsersachuanWORKfirebase-pocsrcfirebase.service.ts:18:24)
    at NotificationService.sendPushNotification (C:UsersachuanWORKfirebase-pocsrcnotification.service.ts:12:7)
    at NotificationController.sendPushNotification (C:UsersachuanWORKfirebase-pocsrcnotification.controller.ts:21:7)
    at C:UsersachuanWORKfirebase-pocnode_modules@nestjscorerouterrouter-execution-context.js:46:28    at C:UsersachuanWORKfirebase-pocnode_modules@nestjscorerouterrouter-proxy.js:9:17 {
  errorInfo: {
    code: 'app/invalid-credential',
    message: 'Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: read ECONNRESET. Error code: ECONNRESET".'
  },
  codePrefix: 'app'
}

Why am I getting this error and how do I fix this?

New contributor

Achu Anil 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