Itamar Gil
Itamar Gil

Reputation: 1

Atlas Function with firebase-admin dependency failing to send push notification

I’m trying to send a push notification to an iOS client from an Atlas Function but I get error Error sending notification: FunctionError: TypeError: Value is not an object: undefined on line await admin.messaging().send(message);

Here’s the function:

async function sendPushNotification(token, title, body) {
  const admin = require('firebase-admin');
  
  const credentials = {
    projectId: '<project id>',
    clientEmail: '<client email>',
    privateKey: '<private key>',
  };

  admin.initializeApp({
   credential: admin.credential.cert(credentials)
 });
 
 const message = {
    notification:{
      body: body,
      title: title
    },
    token: token
  };

  try {
    await admin.messaging().send(message);
    console.log('Notification sent successfully');
  } catch (error) {
    console.error('Error sending notification:', error);
  }
}

Any idea why this is happening?

Tech stack:

  1. SwiftUI app with Realm.
  2. Firebase Messaging on the client code.
  3. firebase-admin dependency on Atlas Function.

I tried:

  1. Printing admin, admin.messaging(), and admin.messaging.send - they’re all fine (not undefined).
  2. Printing message, message.notification, message.token - also fine (not undefined).
  3. Changing the message’s notification object name to “data” - didn’t help.

Upvotes: 0

Views: 89

Answers (1)

Jack
Jack

Reputation: 120

Are you sure your app is properly initialized ?

If not try this ,

const admin = require('firebase-admin');
const { initializeApp, cert, getApps } = require('firebase-admin/app');

if (!getApps().length) {
   initializeApp({
   credential: cert(serviceAccount)
 });
}

Upvotes: 0

Related Questions