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.