Sub topic 7
Sending your first message
This chapter covers the two ways to send a first FCM message: the Firebase console and the HTTP v1 API. It assumes you have a working Flutter app with firebase_messaging installed, notification permission granted, and a registration token printed in the debug console. Chapters on setup, permissions, and tokens cover those steps.
What you need before sending
A message needs a destination. Without one, FCM rejects it. For a first test you need one of these:
- A registration token copied from your app's debug output. This targets a single app instance.
- A topic name the app has subscribed to. This targets every subscribed instance. Topics get their own chapter later.
You also need the app in a state where you can observe the result. For your first test, put the app in the background by pressing the home button. The system tray shows a notification only when the app is not in the foreground.
Sending from the Firebase console
The console is the fastest route and needs no code.
- Open your project in the Firebase console and go to Run > Messaging.
- Choose Create your first campaign (or New campaign) and select Firebase Notification messages.
- Enter a title and body.
- Click Send test message.
- Paste the registration token, click the plus icon to add it, select it, and click Test.
The device should show the notification within a few seconds. If the app is in the foreground, nothing appears in the tray. Your onMessage listener receives the message instead, as the foreground chapter explains.
To add a data payload from the console, open Additional options and enter custom data as key-value pairs. The console always creates a notification message. To send a data-only message, use the API.
Sending with the HTTP v1 API
Production systems send messages from a server. The current endpoint is the HTTP v1 API. The older legacy API, which used a server key, is deprecated and has been shut down, so do not follow tutorials that use it.
The request looks like this:
POST https://fcm.googleapis.com/v1/projects/PROJECT_ID/messages:send
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/jsonPROJECT_ID is your Firebase project ID, found in project settings. ACCESS_TOKEN is a short-lived OAuth 2.0 token, not a static key. You get it from a service account that has permission to send messages.
The request body
This body combines a display notification with a data payload:
{
"message": {
"token": "DEVICE_REGISTRATION_TOKEN",
"notification": {
"title": "Order shipped",
"body": "Your order #42 is on its way."
},
"data": {
"route": "/orders/42"
}
}
}The message object has these parts:
| Field | Purpose |
|---|---|
| `token` | Targets one device. Replace it with `topic` or `condition` to target groups. |
| `notification` | Title and body the system displays when the app is not in the foreground. |
| `data` | Custom key-value pairs your app reads in code. |
Exactly one target field (token, topic, or condition) is allowed per message. All values in data must be strings. A number or boolean causes the request to fail with an INVALID_ARGUMENT error, so write "count": "3", not "count": 3.
Getting an access token
For a quick manual test, use the Google Cloud CLI. Sign in with an account that has access to the project, then request a token:
gcloud auth login
gcloud auth print-access-tokenSend the request with curl, using the token you just printed:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
-d @message.json \
https://fcm.googleapis.com/v1/projects/YOUR_PROJECT_ID/messages:sendSave the JSON body above as message.json first. A successful call returns the generated message name:
{
"name": "projects/YOUR_PROJECT_ID/messages/0:1700000000000000%abcdef"
}Access tokens expire after about an hour. A server should not shell out to gcloud. It should use a Google auth library or the Firebase Admin SDK, which fetch and refresh tokens from a service account key or from the runtime's default credentials.
Sending with the Admin SDK
The Firebase Admin SDK hides the token handling. This Node.js example sends the same message:
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.applicationDefault(),
});
admin
.messaging()
.send({
token: "DEVICE_REGISTRATION_TOKEN",
notification: {
title: "Order shipped",
body: "Your order #42 is on its way.",
},
data: { route: "/orders/42" },
})
.then((name) => console.log("Sent:", name))
.catch((error) => console.error("Failed:", error.code));Set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a service account key file, or run on Google Cloud where default credentials exist. Never ship a service account key inside the Flutter app. Anyone who extracts it can send messages as your project.
How the message type changes the result
The same request behaves differently depending on its contents and the app state.
| Payload | App in foreground | App in background | App terminated |
|---|---|---|---|
| `notification` only | `onMessage` fires, no tray entry | System tray entry, no Dart code runs | System tray entry |
| `notification` + `data` | `onMessage` fires with both | System tray entry, data delivered on tap | System tray entry, data delivered on tap |
| `data` only | `onMessage` fires | Background handler runs, no tray entry | Background handler may run, subject to platform limits |
A data-only message never displays anything by itself. If your app needs to show something, it must create the notification in code. Later chapters cover this.
Choosing a target
Pick the target by who should receive the message:
- Use
tokenfor one user's device, such as an order update. - Use
topicfor broad groups, such asnews, where the sender does not track individual tokens. - Use
conditionto combine topics with boolean logic, such as'news' in topics && 'sports' in topics.
Targeting a user with several devices means sending to each of that user's stored tokens, or using the SDK's multicast call, which accepts up to 500 tokens per batch.
Reading the response and errors
The API reports problems with an HTTP status and an error code. The ones you will meet first:
| Code | Meaning | What to do |
|---|---|---|
| `INVALID_ARGUMENT` | The body is malformed, for example a non-string `data` value | Fix the payload |
| `UNREGISTERED` | The token is no longer valid, because the app was uninstalled or the token rotated | Delete the token from your database |
| `SENDER_ID_MISMATCH` | The token belongs to a different Firebase project | Check that the app and server use the same project |
| `THIRD_PARTY_AUTH_ERROR` | APNs credentials are missing or wrong (iOS) | Upload a valid APNs key in project settings |
| `QUOTA_EXCEEDED` | Sending rate limit reached | Retry with exponential backoff |
A success response only means FCM accepted the message. It does not mean the device displayed it. Delivery can still fail because of device state, battery restrictions, or revoked permission.
A first-send checklist
Work through this list in order when your first message does not show up:
- Confirm the token is current. Copy it again from a fresh app run.
- Confirm the app is in the background, not the foreground, if you sent a notification message.
- Confirm notification permission is granted in the device settings.
- On Android 13 or later, confirm
POST_NOTIFICATIONSis declared and granted. - On iOS, test on a physical device. Simulators have limited push support, and a missing APNs key is the most common cause of silent failure.
- Check the response body for an error code from the table above.
Exercise
You send this HTTP v1 request body to a device that is running your app in the background, and the call fails with INVALID_ARGUMENT. What is wrong, and how do you fix it? Body: {"message": {"token": "abc", "data": {"unread": 3, "route": "/inbox"}}}
Show answer
The value of "unread" is a number, and every value in "data" must be a string. Change it to "unread": "3". Note also that this is a data-only message, so even after the fix it will not display a tray notification. Add a "notification" object with a title and body if the user should see something, or create the notification in code from a background handler.
Exercise
You send a message containing both "notification" and "data" while the app is in the foreground. Nothing appears in the system tray. Is something broken? Where do you find the message?
Show answer
Nothing is broken. FCM does not display notification messages automatically while the app is in the foreground. The message arrives on the FirebaseMessaging.onMessage stream, where you can read message.notification and message.data and decide what to show, for example with a local notifications plugin.