Send Messages

The Firebase Admin Node.js SDK provides an API for sending Firebase Cloud Messaging (FCM) messages to end user devices. The Admin FCM API gives you the ability to programmatically send messages to individual devices, device groups, topics, and conditions.

Before you begin

To use the Admin FCM API, you must first follow the steps in Add the Firebase Admin SDK to your Server to initialize the SDK.

Send to individual devices

The Admin FCM API allows you to send messages to individual devices by providing a registration token for the device to which to send the message. Registration tokens are strings generated by the client FCM SDKs for each end-user client app instance.

Each of the Firebase client SDKs are able to generate these registration tokens: iOS, Android, Web, C++, and Unity.

You can pass one of these registration tokens to the sendToDevice() method to send a message to that device:

Node.js

// This registration token comes from the client FCM SDKs.
var registrationToken = "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...";

// See the "Defining the message payload" section below for details
// on how to define a message payload.
var payload = {
  data: {
    score: "850",
    time: "2:45"
  }
};

// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().sendToDevice(registrationToken, payload)
  .then(function(response) {
    // See the MessagingDevicesResponse reference documentation for
    // the contents of response.
    console.log("Successfully sent message:", response);
  })
  .catch(function(error) {
    console.log("Error sending message:", error);
  });

The sendToDevice() method can also send a multicast message (that is, a message to multiple devices) by passing an array of registration tokens instead of just a single registration token:

Node.js

// These registration tokens come from the client FCM SDKs.
var registrationTokens = [
  "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  // ...
  "ecupwIfBy1w:APA91bFtuMY7MktgxA3Au_Qx7cKqnf..."
];

// See the "Defining the message payload" section below for details
// on how to define a message payload.
var payload = {
  data: {
    score: "850",
    time: "2:45"
  }
};

// Send a message to the devices corresponding to the provided
// registration tokens.
admin.messaging().sendToDevice(registrationTokens, payload)
  .then(function(response) {
    // See the MessagingDevicesResponse reference documentation for
    // the contents of response.
    console.log("Successfully sent message:", response);
  })
  .catch(function(error) {
    console.log("Error sending message:", error);
  });

The sendToDevice() method returns a promise that is resolved with a MessagingDevicesResponse object containing the response from FCM. The return type has the same format when passing a single registration token or an array of registration tokens.

Some cases such as an authentication error or rate limiting cause the entirety of the message to fail to process. In these cases, the promise returned by sendToDevice() is rejected with an error. For a full list of error codes, including descriptions and resolution steps, see Admin FCM API Errors.

Send to a device group

With device group messaging, you can send a single message to multiple instances of an app running on devices belonging to a group. Typically, "group" refers a set of different devices that belong to a single user. All devices in a group share a common notification key, which is the token that FCM uses to fan out messages to all devices in the group.

The limit on data payload is 2KB when sending to iOS devices, and 4KB for other platforms. The maximum number of members allowed for a notification key is 20.

You can create device groups and generate notification keys via an app server or an Android client. See Managing device groups for details.

The sendToDeviceGroup() method allows you to send a message to a device group by specifying the notification key for that device group:

Node.js

// See the "Managing device groups" link above on how to generate a
// notification key.
var notificationKey = "some-notification-key";

// See the "Defining the message payload" section below for details
// on how to define a message payload.
var payload = {
  data: {
    score: "850",
    time: "2:45"
  }
};

// Send a message to the device group corresponding to the provided
// notification key.
admin.messaging().sendToDeviceGroup(notificationKey, payload)
  .then(function(response) {
    // See the MessagingDeviceGroupResponse reference documentation for
    // the contents of response.
    console.log("Successfully sent message:", response);
  })
  .catch(function(error) {
    console.log("Error sending message:", error);
  });

The sendToDeviceGroup() method returns a promise that is resolved with a MessagingDeviceGroupResponse object containing the response from FCM.

Some cases such as an authentication error or rate limiting cause the entirety of the message to fail to process. In these cases, the promise returned by sendToDeviceGroup() is rejected with an error. For a full list of error codes, including descriptions and resolution steps, see Admin FCM API Errors.

Send to a topic

Based on the publish/subscribe model, FCM topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. You compose topic messages as needed, and FCM handles routing and delivering the message reliably to the right devices.

For example, users of a local weather forecasting app could opt in to a "severe weather alerts" topic and receive notifications of storms threatening specified areas. Users of a sports app could subscribe to automatic updates in live game scores for their favorite teams.

Some things to keep in mind about topics:

  • Topic messaging supports unlimited topics and subscriptions for each app.
  • Topic messaging is best suited for content such as news, weather, or other publicly available information.
  • Topic messages are optimized for throughput rather than latency. For fast, secure delivery to single devices or small groups of devices, target messages to registration tokens, not topics.
  • If you need to send messages to multiple devices per user, consider device group messaging for those use cases.

The sendToTopic() method allows you to send a message to a topic by specifying the topic name:

Node.js

// The topic name can be optionally prefixed with "/topics/".
var topic = "highScores";

// See the "Defining the message payload" section below for details
// on how to define a message payload.
var payload = {
  data: {
    score: "850",
    time: "2:45"
  }
};

// Send a message to devices subscribed to the provided topic.
admin.messaging().sendToTopic(topic, payload)
  .then(function(response) {
    // See the MessagingTopicResponse reference documentation for the
    // contents of response.
    console.log("Successfully sent message:", response);
  })
  .catch(function(error) {
    console.log("Error sending message:", error);
  });

The sendToTopic() method returns a promise that is resolved with a MessagingTopicResponse object containing the response from FCM.

Some cases such as an authentication error or rate limiting cause the entirety of the message to fail to process. In these cases, the promise returned by sendToTopic() is rejected with an error. For a full list of error codes, including descriptions and resolution steps, see Admin FCM API Errors.

Send to a condition

Sometimes you want to send a message to a combination of topics. This is done by specifying a condition, which is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to TopicA and either TopicB or TopicC:

"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"

FCM first evaluates any conditions in parentheses, and then evaluates the expression from left to right. In the above expression, a user subscribed to any single topic does not receive the message. Likewise, a user who does not subscribe to TopicA does not receive the message. These combinations do receive it:

  • TopicA and TopicB
  • TopicA and TopicC

The Admin FCM API allows you to provide a condition to the sendToCondition() method to target devices which are subscribed to a combination of topics:

Node.js

// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";

// See the "Defining the message payload" section below for details
// on how to define a message payload.
var payload = {
  notification: {
    title: "$GOOG up 1.43% on the day",
    body: "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day."
  }
};

// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
admin.messaging().sendToCondition(condition, payload)
  .then(function(response) {
    // See the MessagingConditionResponse reference documentation for
    // the contents of response.
    console.log("Successfully sent message:", response);
  })
  .catch(function(error) {
    console.log("Error sending message:", error);
  });

The sendToCondition() method returns a promise that is resolved with a MessagingConditionResponse object containing the response from FCM.

Some cases such as an authentication error or rate limiting cause the entirety of the message to fail to process. In these cases, the promise returned by sendToCondition() is rejected with an error. For a full list of error codes, including descriptions and resolution steps, see Admin FCM API Errors.

Defining the message payload

The above methods accept a message payload as their second argument and support both notification and data messages. You can specify one or both message types by creating an object with the data and / or notification keys. For example, here is how to define different types of message payloads:

Notification message

var payload = {
  notification: {
    title: "$GOOG up 1.43% on the day",
    body: "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day."
  }
};

Data message

var payload = {
  data: {
    score: "850",
    time: "2:45"
  }
};

Combined message

var payload = {
  notification: {
    title: "$GOOG up 1.43% on the day",
    body: "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day."
  },
  data: {
    stock: "GOOG",
    open: 829.62,
    close: "635.67"
  }
};

Notification message payloads have a predefined subset of valid properties and differ slightly depending on which mobile operating system you are targeting. See the reference docs for NotificationMessagePayload for a full list.

Data message payloads are composed of custom key-value pairs with a few restrictions, including the fact that all values must be strings. See the reference docs for DataMessagePayload for a full list of restrictions.

Defining the message options

The above methods accept an optional third argument specifying some options for the message. For example, the following example send a high priority message to a device which expires after 24 hours:

Node.js

// This registration token comes from the client FCM SDKs.
var registrationToken = "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...";

// See the "Defining the message payload" section above for details
// on how to define a message payload.
var payload = {
  notification: {
    title: "Urgent action needed!",
    body: "Urgent action is needed to prevent your account from being disabled!"
  }
};

// Set the message as high priority and have it expire after 24 hours.
var options = {
  priority: "high",
  timeToLive: 60 * 60 * 24
};

// Send a message to the device corresponding to the provided
// registration token with the provided options.
admin.messaging().sendToDevice(registrationToken, payload, options)
  .then(function(response) {
    console.log("Successfully sent message:", response);
  })
  .catch(function(error) {
    console.log("Error sending message:", error);
  });

See the reference docs for MessagingOptions for a full list of available options.

Send feedback about...

Need help? Visit our support page.