About Firebase Cloud Messaging Server

The server side of Firebase Cloud Messaging consists of two components:

The app server or trusted server environment sends message requests to the FCM servers, which then sends messages to client apps running on users' devices.

For more information about implementing the client side, see the client guide for your platform: iOS, Android, or Chrome.

Role of the trusted server environment

Before you can write client apps that use Firebase Cloud Messaging, you must have a server environment that meets the following criteria:

  • Able to communicate with your client.
  • Able to send properly formatted message requests to the FCM server.
  • Able to handle requests and resend them using exponential back-off.
  • Able to securely store the Server key and client registration tokens. Note: never include the Server key in any client code.
  • For XMPP, the server must be able to generate message IDs to uniquely identify each message it sends (FCM HTTP connection server generates message IDs and returns them in the response). XMPP message IDs should be unique per sender ID.

You'll need to decide on a way to interact with FCM servers: either using the Admin SDK or the raw HTTP and XMPP server protocols. Note that if you want to use upstream messaging from your client applications, you must use XMPP. For a more detailed discussion of this, see FCM Server Protocols.

FCM Server Protocols

Currently FCM provides two server protocols: HTTP and XMPP. Your app server can use them separately or in tandem. XMPP messaging differs from HTTP messaging in the following ways:

  • Upstream/Downstream messages
    • HTTP: Downstream only, cloud-to-device.
    • XMPP: Upstream and downstream (device-to-cloud, cloud-to-device).
  • Messaging (synchronous or asynchronous)
    • HTTP: Synchronous. App servers send messages as HTTP POST requests and wait for a response. This mechanism is synchronous and blocks the sender from sending another message until the response is received.
    • XMPP: Asynchronous. App servers send/receive messages to/from all their devices at full line speed over persistent XMPP connections. The XMPP connection server sends acknowledgment or failure notifications (in the form of special ACK and NACK JSON-encoded XMPP messages) asynchronously.
  • JSON
    • HTTP: JSON messages sent as HTTP POST.
    • XMPP: JSON messages encapsulated in XMPP messages.
  • Plain Text
    • HTTP: Plain Text messages sent as HTTP POST.
    • XMPP: Not supported.
  • Multicast downstream send to multiple registration tokens.
    • HTTP: Supported in JSON message format.
    • XMPP: Not supported.

Implementing the HTTP server protocol

This section describes how to authenticate and create message requests with the FCM HTTP server protocol. See the Server Reference for a list of all the message parameters and which protocol(s) supports them.

Authentication

To send a message, the app server issues a POST request. For example:

https://fcm.googleapis.com/fcm/send

A message request consists of two parts: the HTTP header and the HTTP body.

The HTTP header must contain the following headers:

  • Authorization: key=YOUR_SERVER_KEY
    Make sure this is the server key, whose value is available in the Cloud Messaging tab of the Firebase console Settings pane. Android, iOS, and browser keys are rejected by FCM.
  • Content-Type: application/json for JSON; application/x-www-form-urlencoded;charset=UTF-8 for plain text.
    If Content-Type is omitted, the format is assumed to be plain text.

For example:

Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
  "data" : {
    ...
  },
}

The HTTP body content depends on whether you're using JSON or plain text. See the Server Reference for a list of all the parameters your JSON or plain text message can contain.

Checking the validity of a server key

If you receive authentication errors when sending messages, check the validity of your Server key. For example, on Android, run the following command:

# api_key=YOUR_SERVER_KEY

# curl --header "Authorization: key=$api_key" \
       --header Content-Type:"application/json" \
       https://fcm.googleapis.com/fcm/send \
       -d "{\"registration_ids\":[\"ABC\"]}"

If you receive a 401 HTTP status code, your Server key is not valid. Otherwise you should see something like this:

{"multicast_id":6782339717028231855,"success":0,"failure":1,
"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}

If you want to confirm the validity of a registration token, you can do so by replacing "ABC" with the registration token.

Request format

This section shows you how to format requests for both JSON and plain text. See the Server Reference for a complete list of the fields you can include in a request.

Send-to-sync

Here is the smallest possible request (a message without any parameters and just one recipient) using JSON:

{ "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..." }

And here the same example using plain text:

registration_id=42

Message with payload — notification message

Here is a notification message:

{ "notification": {
    "title": "Portugal vs. Denmark",
    "body": "5 to 1"
  },
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}

Message with payload — data message

Here is a message with a data payload:

{ "data": {
    "score": "5x1",
    "time": "15:10"
  },
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}

Here is a message with all optional fields set:

{ "collapse_key": "score_update",
  "time_to_live": 108,
  "data": {
    "score": "4x8",
    "time": "15:16.2342"
  },
  "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}

And here is the same message using plain-text format:

collapse_key=score_update&time_to_live=108&data.score=4x8&data.time=15:16.2342&registration_id=42
  

Response format

There are two possible outcomes when trying to send a message:

  • The message is processed successfully. The HTTP response has a 200 status, and the body contains more information about the status of the message.
  • The FCM server rejects the request. The HTTP response contains a non-200 status code (such as 400, 401 or 5xx).

When a JSON request is successful (HTTP status code 200), the JSON object returned contains the Downstream HTTP message response body. Log the message ID value for all messages, in case you need to troubleshoot the message with Google support.

If the value of failure and canonical_ids is 0, it's not necessary to parse the remainder of the response. Otherwise, we recommend that you iterate through the results field and do the following for each object in that list:

  • If message_id is set, check for registration_id:
    • If registration_id is set, replace the original ID with the new value (canonical ID) in your server database. Note that the original ID is not part of the result, so you need to obtain it from the list of registration_ids passed in the request (using the same index).
  • Otherwise, get the value of error:
    • If it is Unavailable, you could retry to send it in another request.
    • If it is NotRegistered, you should remove the registration ID from your server database because the application was uninstalled from the device, or the client app isn't configured to receive messages.
    • Otherwise, there is something wrong in the registration token passed in the request; it is probably a non-recoverable error that will also require removing the registration from the server database. See Downstream message error response codes for all possible error values.

When a plain-text request is successful (HTTP status code 200), the response body contains 1 or 2 lines in the form of key/value pairs. The first line is always available and its content is either id=ID of sent message or Error=GCM error code. The second line, if available, has the format of registration_id=canonical ID. The second line is optional, and it can only be sent if the first line is not an error. We recommend handling the plain-text response in a similar way as handling the JSON response:

  • If first line starts with id, check second line:
    • If second line starts with registration_id, gets its value and replace the registration tokens in your server database.
  • Otherwise, get the value of Error:
    • If it is NotRegistered, remove the registration token from your server database.
    • Otherwise, there is probably a non-recoverable error (Note : Plain-text requests will never return Unavailable as the error code, they would have returned a 500 HTTP status instead).

Example responses

This section shows a few examples of responses indicating messages that were processed successfully. See Request Format for the requests these responses are based on.

Here is a simple case of a JSON message successfully sent to one recipient without canonical IDs in the response:

{ "multicast_id": 108,
  "success": 1,
  "failure": 0,
  "canonical_ids": 0,
  "results": [
    { "message_id": "1:08" }
  ]
}

Or if the request was in plain-text format:

id=1:08

Here are JSON results for 6 recipients (IDs 4, 8, 15, 16, 23, and 42 respectively) with 3 messages successfully processed, 1 canonical registration token returned, and 3 errors:

{ "multicast_id": 216,
  "success": 3,
  "failure": 3,
  "canonical_ids": 1,
  "results": [
    { "message_id": "1:0408" },
    { "error": "Unavailable" },
    { "error": "InvalidRegistration" },
    { "message_id": "1:1516" },
    { "message_id": "1:2342", "registration_id": "32" },
    { "error": "NotRegistered"}
  ]
}

In this example:

  • First message: success, not required.
  • Second message: should be resent (to registration token 8).
  • Third message: had an unrecoverable error (maybe the value got corrupted in the database).
  • Fourth message: success, nothing required.
  • Fifth message: success, but the registration token should be updated in the server database (from 23 to 32).
  • Sixth message: registration token (42) should be removed from the server database because the application was uninstalled from the device.

Or if just the third message above was sent using plain-text format:

Error=InvalidRegistration

If the fifth message above was also sent using plain-text format:

id=1:2342
registration_id=32

Implementing the XMPP server protocol

With XMPP, you can maintain a persistent, asynchronous, bidirectional connection to FCM servers. The connection can be used to send and receive messages between your server and your users' FCM-connected devices.

You can continue to use the HTTP request mechanism to send messages to Firebase Cloud Messaging servers, side-by-side with XMPP. Some of the benefits of XMPP include:

  • The asynchronous nature of XMPP allows you to send more messages with fewer resources.
  • Communication is bidirectional—not only can your server send messages to the device, but the device can send messages back to your server.
  • The device can send messages back using the same connection used for receiving, thereby improving battery life.

See the Server Reference for a list of all the message parameters and which protocol(s) supports them.

Establishing a connection

You can use most XMPP libraries to manage a long-lived connection to FCM. XMPP endpoint runs at fcm-xmpp.googleapis.com:5235. When testing functionality with non-production users, you should instead connect to the pre-production server at fcm-xmpp.googleapis.com:5236 (note the different port).

Regular testing on pre-production (a smaller environment where the latest FCM builds run) is beneficial for isolating real users from test code. Test devices and test code connecting to fcm-xmpp.googleapis.com:5236 should use a different FCM sender ID to avoid any risks of sending test messages to production users or sending upstream messages from production traffic over test connections.

The connection has two important requirements:

  • You must initiate a Transport Layer Security (TLS) connection. Note that FCM doesn't currently support the STARTTLS extension.
  • FCM requires a SASL PLAIN authentication mechanism using <your_FCM_Sender_Id>@gcm.googleapis.com (FCM sender ID) and the Server key as the password. These values are available in the Cloud Messaging tab of the Firebase console Settings pane.

If at any point the connection fails, you should immediately reconnect. There is no need to back off after a disconnect that happens after authentication.

For each sender ID, FCM allows 1000 connections in parallel.

Authentication

The following snippets illustrate how to perform authentication.

Client

<stream:stream to="gcm.googleapis.com"
        version="1.0" xmlns="jabber:client"
        xmlns:stream="http://etherx.jabber.org/streams">

Server

<stream:features>
  <mechanisms xmlns="urn:ietf:params:xml:ns:xmpp-sasl">
    <mechanism>X-OAUTH2</mechanism>
    <mechanism>X-GOOGLE-TOKEN</mechanism>
    <mechanism>PLAIN</mechanism>
  </mechanisms>
</stream:features>

Client

<auth mechanism="PLAIN"
xmlns="urn:ietf:params:xml:ns:xmpp-sasl">MTI2MjAwMzQ3OTMzQHByb2plY3RzLmdjbS5hb
mFTeUIzcmNaTmtmbnFLZEZiOW1oekNCaVlwT1JEQTJKV1d0dw==</auth>

Server

<success xmlns="urn:ietf:params:xml:ns:xmpp-sasl"/>

Client

<stream:stream to="gcm.googleapis.com"
        version="1.0" xmlns="jabber:client"
        xmlns:stream="http://etherx.jabber.org/streams">

Server

<stream:features>
  <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"/>
  <session xmlns="urn:ietf:params:xml:ns:xmpp-session"/>
</stream:features>

Client

<iq type="set">
  <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind"></bind>
</iq>

Server

<iq type="result">
  <bind xmlns="urn:ietf:params:xml:ns:xmpp-bind">
    <jid>SENDER_ID@gcm.googleapis.com/RESOURCE</jid>
  </bind>
</iq>

Note: FCM does not use the bound resource while routing messages.

Downstream messages

Once the XMPP connection is established, FCM and your server use normal XMPP <message> stanzas to send JSON-encoded messages back and forth. The body of the <message> must be:

<gcm xmlns:google:mobile:data>
    JSON payload
</gcm>

The JSON payload for regular FCM messages is similar to what the FCM http endpoint uses, with these exceptions:

  • There is no support for multiple recipients.
  • to is used instead of registration_ids.
  • FCM adds the field message_id, which is required. This ID uniquely identifies the message in an XMPP connection. The ACK or NACK from FCM uses the message_id to identify a message sent from app servers to FCM. Therefore, it's important that this message_id not only be unique (per sender ID), but always present.

In addition to regular FCM messages, control messages are sent, indicated by the message_type field in the JSON object. The value can be either 'ack' or 'nack', or 'control' (see formats below). Any FCM message with an unknown message_type can be ignored by your server.

For each device message your app server receives from FCM, it needs to send an ACK message. It never needs to send a NACK message. If you don't send an ACK for a message, FCM resends it the next time a new XMPP connection is established, unless the message expires first.

FCM also sends an ACK or NACK for each server-to-device message. If you do not receive either, it means that the TCP connection was closed in the middle of the operation and your server needs to resend the messages. See Flow Control for details.

See the Server Reference for a list of all the message parameters and which connection server(s) supports them.

Request format

Send-to-sync

Here is a simple XMPP stanza for a send-to-sync message:

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "to":"REGISTRATION_ID",  // "to" replaces "registration_ids"
  }
  </gcm>
</message>

Message with payload — notification message

Here is an XMPP stanza for a notification message:

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "to":"REGISTRATION_ID",  // "to" replaces "registration_ids"
     "notification": {
        "title": "Portugal vs. Denmark”,
        "body”: "5 to 1”
      },
      "time_to_live":"600"
}

  }
  </gcm>
</message>

Message with payload — data message

Here is an XMPP stanza containing the JSON message from an app server to FCM:

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "to":"REGISTRATION_ID",  // "to" replaces "registration_ids"
      "message_id":"m-1366082849205" // new required field
      "data":
      {
          "hello":"world",
      }
      "time_to_live":"600",
      "delivery_receipt_requested": true/false
  }
  </gcm>
</message>

Response format

An FCM response can have three possible forms. The first one is a regular 'ack' message. But when the response contains an error, there are 2 different forms the message can take, described below.

ACK message

Here is an XMPP stanza containing the ACK/NACK message from FCM to the app server:

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "from":"REGID",
      "message_id":"m-1366082849205"
      "message_type":"ack"
  }
  </gcm>
</message>

NACK message

A NACK error is a regular XMPP message in which the message_type status message is "nack". A NACK message contains:

  • A NACK error code.
  • A NACK error description.

Below are some examples.

Bad registration:

<message>
  <gcm xmlns="google:mobile:data">
  {
    "message_type":"nack",
    "message_id":"msgId1",
    "from":"SomeInvalidRegistrationId",
    "error":"BAD_REGISTRATION",
    "error_description":"Invalid token on 'to' field: SomeInvalidRegistrationId"
  }
  </gcm>
</message>

Invalid JSON:

<message>
 <gcm xmlns="google:mobile:data">
 {
   "message_type":"nack",
   "message_id":"msgId1",
   "from":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
   "error":"INVALID_JSON",
   "error_description":"InvalidJson: JSON_TYPE_ERROR : Field \"time_to_live\" must be a JSON java.lang.Number: abc"
 }
 </gcm>
</message>

Device Message Rate Exceeded:

<message id="...">
  <gcm xmlns="google:mobile:data">
  {
    "message_type":"nack",
    "message_id":"msgId1",
    "from":"REGID",
    "error":"DEVICE_MESSAGE_RATE_EXCEEDED",
    "error_description":"Downstream message rate exceeded for this registration id"
  }
  </gcm>
</message>

See the Server Reference for a complete list of the NACK error codes. Unless otherwise indicated, a NACKed message should not be retried. Unexpected NACK error codes should be treated the same as INTERNAL_SERVER_ERROR.

Stanza error

You can also get a stanza error in certain cases. A stanza error contains:

  • Stanza error code.
  • Stanza error description (free text).

For example:

<message id="3" type="error" to="123456789@gcm.googleapis.com/ABC">
  <gcm xmlns="google:mobile:data">
     {"random": "text"}
  </gcm>
  <error code="400" type="modify">
    <bad-request xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"/>
    <text xmlns="urn:ietf:params:xml:ns:xmpp-stanzas">
      InvalidJson: JSON_PARSING_ERROR : Missing Required Field: message_id\n
    </text>
  </error>
</message>

Control messages

Periodically, FCM needs to close down a connection to perform load balancing. Before it closes the connection, FCM sends a CONNECTION_DRAINING message to indicate that the connection is being drained and will be closed soon. "Draining" refers to shutting off the flow of messages coming into a connection, but allowing whatever is already in the pipeline to continue. When you receive a CONNECTION_DRAINING message, you should immediately begin sending messages to another FCM connection, opening a new connection if necessary. You should, however, keep the original connection open and continue receiving messages that may come over the connection (and ACKing them)—FCM handles initiating a connection close when it is ready.

The CONNECTION_DRAINING message looks like this:

<message>
  <data:gcm xmlns:data="google:mobile:data">
  {
    "message_type":"control"
    "control_type":"CONNECTION_DRAINING"
  }
  </data:gcm>
</message>

CONNECTION_DRAINING is currently the only control_type supported.

Receive delivery receipts

For Android and Chrome client apps, you can get delivery receipts (sent from FCM to your app server) when a device confirms that it received a message sent by FCM.

To enable this feature, the message your app server sends to FCM must include the field delivery_receipt_requested. When this field is set to true, FCM sends a delivery receipt when a device confirms that it received a particular message.

Here is an XMPP stanza containing a JSON message with "delivery_receipt_requested" set to true:

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "to":"REGISTRATION_ID",
      "message_id":"m-1366082849205"
      "data":
      {
          "hello":"world",
      }
      "time_to_live":"600",
      "delivery_receipt_requested": true
  }
  </gcm>
</message>

Here is an example of the delivery receipt that FCM sends to tell your app server that a device received a message that FCM sent it:

<message id="">
  <gcm xmlns="google:mobile:data">
  {
      "category":"com.example.yourapp", // to know which app sent it
      "data":
      {
         “message_status":"MESSAGE_SENT_TO_DEVICE",
         “original_message_id”:”m-1366082849205”
         “device_registration_id”: “REGISTRATION_ID”
      },
      "message_id":"dr2:m-1366082849205",
      "message_type":"receipt",
      "from":"gcm.googleapis.com"
  }
  </gcm>
</message>

Note the following:

  • The "message_type" is set to "receipt".
  • The "message_status" is set to "MESSAGE_SENT_TO_DEVICE", indicating that the device received the message. Notice that in this case, "message_status" is not a field but rather part of the data payload.
  • The receipt message ID consists of the original message ID, but with a dr2: prefix. Your app server must use the same connection to send an ACK back with this ID, which in this example is dr2:m-1366082849205.
  • The original message ID, the device registration token, and the status are inside the "data" field.
  • If the connection between FCM and the device is poor, Firebase Cloud Messaging may send multiple, duplicate delivery receipts. You can safely ignore such duplicates.

Flow control

Every message sent to FCM receives either an ACK or a NACK response. Messages that haven't received one of these responses are considered pending. If the pending message count reaches 100, the app server should stop sending new messages and wait for FCM to acknowledge some of the existing pending messages as illustrated in figure 1:

Figure 1. Message/ack flow.

Conversely, to avoid overloading the app server, FCM stops sending if there are too many unacknowledged messages. Therefore, the app server should "ACK" upstream messages, received from the client application via FCM, as soon as possible to maintain a constant flow of incoming messages. The aforementioned pending message limit doesn't apply to these ACKs. Even if the pending message count reaches 100, the app server should continue sending ACKs for messages received from FCM to avoid blocking delivery of new upstream messages.

ACKs are only valid within the context of one connection. If the connection is closed before a message can be ACKed, the app server should wait for FCM to resend the upstream message before ACKing it again. Similarly, all pending messages for which an ACK/NACK was not received from FCM before the connection was closed should be sent again.

Send feedback about...

Need help? Visit our support page.