skip to content

Firebase

Google's backend-as-a-service for mobile and web apps: Firestore, Authentication, Security Rules, Cloud Functions, Storage, Hosting and FCM. Asked where an app ships without its own server.

on this pageshow

explore

questions

page 1 of 2

In Firebase Cloud Messaging for Android, what is the difference between a notification message and a data message?

level: juniorimportance: must knowfreq 82%

answer

  1. who draws the tray entry
  2. notification block vs data block
  3. string keys, string values
  4. background: the SDK posts, no callback
  5. RemoteMessage.notification vs RemoteMessage.data

basics

~20 s

A notification message carries display fields (title, body, image) that the FCM SDK shows itself while the app is in the background; a data message carries only custom string pairs, handed to onMessageReceived for your code to act on.

solid answer

~40 s

An FCM message has a `notification` part, a `data` part, or both. A **notification message** carries display fields such as `title` and `body`; when the app is in the background the FCM SDK builds and posts the notification itself and never calls my code. In the foreground the SDK does not display it: it passes it to `onMessageReceived`, where `RemoteMessage.notification` holds the fields and the app decides what to show. A **data message** is a map of string keys to string values; it reaches `onMessageReceived` in the foreground and in the background, and nothing appears unless my code posts a notification. A message with both parts behaves like a notification in the background: the SDK shows the tray entry and the data rides in the extras of the intent the tap opens.

code

kotlin · 21 lines
kotlin
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage

class ParcelMessagingService : FirebaseMessagingService() {

    override fun onMessageReceived(message: RemoteMessage) {
        // Data pairs: present for data and combined messages, in any app state that calls us.
        if (message.data.isNotEmpty()) {
            Log.d(TAG, "data: ${message.data}")
        }
        // Notification fields: only seen here while the app is in the foreground.
        message.notification?.let { n ->
            Log.d(TAG, "notification: ${n.title} / ${n.body}")
        }
    }

    private companion object {
        const val TAG = "ParcelPush"
    }
}

go deeper

for a junior

Recall the two blocks and the table: a notification message is shown by the SDK in the background, a data message always goes to onMessageReceived, and data values are strings.

for a middle

Explain the foreground case too: the SDK does not draw a notification message then, it calls onMessageReceived, and a combined message's data lands in the tap intent's extras when backgrounded.

for a senior

Show you have debugged it: name the manifest defaults for icon, colour and channel, and why a team that only tests with the app open ships broken background alerts.

for a principal

Frame the payload type as a team contract: which messages the SDK may display unaided, which must run app code, and how the server and app agree on the data keys.

## Two payloads in one message format Every message an app server sends through **Firebase Cloud Messaging (FCM)** is a JSON object with exactly one target (a Firebase Installation ID, a legacy registration token, a topic or a topic condition) and up to two payloads: - **`notification`**: display fields that FCM defines, such as `title`, `body` and an image URL. The Android block of the message adds Android-only display fields such as `channel_id`, `icon`, `color` and `click_action`. - **`data`**: your own key-value pairs. Every key and every value is a **string**. The Firebase Admin SDK rejects a non-string value with "data must only contain string values", so numbers, booleans and nested objects have to be encoded as strings first, for example as JSON text inside one value. A message with only `notification` is a **notification message**, one with only `data` is a **data message**, and one with both is a **combined message**. The difference is not cosmetic: it decides **who runs code** when the message lands on the phone. ## Who handles each message on Android On the device, messages reach a class you write that extends `FirebaseMessagingService` and is declared in the manifest with the `com.google.firebase.MESSAGING_EVENT` intent filter. Its main callback is `onMessageReceived(message: RemoteMessage)`. Whether that callback runs depends on the payload and on the app's state: | App state | Notification message | Data message | Both payloads | |---|---|---|---| | Foreground | `onMessageReceived` | `onMessageReceived` | `onMessageReceived` | | Background | System tray, posted by the SDK | `onMessageReceived` | Tray entry; data in the tap intent's extras | Two consequences follow, and interviewers probe both: 1. In the **background**, the FCM SDK displays a notification message itself. Your service is not called, so logic you put in `onMessageReceived` does not run for that message. 2. In the **foreground**, the SDK does **not** display a notification message. It passes it to `onMessageReceived`, where `message.notification` exposes the title and body, and showing anything is up to your code. A data message never draws anything by itself. Whatever the app state, it arrives in `onMessageReceived` as `message.data`, and the user sees something only if your code posts a notification or updates the screen. ## What the SDK fills in for a notification message When the SDK displays a notification message for you, it completes what the payload leaves out: - **Icon and colour** come from the payload, or else from the manifest meta-data `com.google.firebase.messaging.default_notification_icon` and `com.google.firebase.messaging.default_notification_color`. With neither, Android shows the app icon rendered in white. - **Channel**: from Android 8.0 every notification belongs to a channel. The payload's `channel_id` wins; otherwise the SDK uses the manifest's `com.google.firebase.messaging.default_notification_channel_id`, and failing that a fallback channel it creates. - **Image**: if the payload names an image, the SDK downloads it with a short timeout and shows the notification without the picture when the download does not finish in time. - **Tap**: by default a tap opens the app's launcher activity. Messages composed in the Firebase console's Notifications composer are notification messages, so they follow the same background-tray rule. There is one variation on who draws the entry. On Android 10 and later, some high-priority notification messages sent through the HTTP v1 API are **proxied**: Google Play services displays them on the app's behalf without starting the app. For the question in this lesson nothing changes, because your `onMessageReceived` is still not called for a notification message in the background. ## Reading the payloads in code In `onMessageReceived`, check both parts, because a combined message delivered in the foreground carries both: - `message.data` is a `Map<String, String>`, empty for a pure notification message. - `message.notification` is null for a pure data message; otherwise it exposes `title`, `body`, `imageUrl`, `channelId` and `clickAction`. The service needs no main-thread care for this: the SDK calls `onMessageReceived` on a worker thread. ## Mistakes interviewers listen for - Saying `onMessageReceived` fires for every message. It does not fire for a notification message, or for a combined message, while the app is in the background. - Expecting a notification message to pop up while the user is inside the app. The SDK hands it to your code instead, and nothing appears unless you post it. - Putting numbers or nested objects in `data`. The Admin SDK refuses them; send strings. - Assuming a data message shows something on its own. It only runs your service. - Testing only with the app open. That path never exercises the SDK's own display, which is the one most users see.

  • Where does the data of a combined notification-and-data message go when the app is in the background?
    The FCM SDK posts the notification to the system tray and copies the data pairs into the extras of the intent the notification opens, by default the launcher activity. Your code reads them from that intent when the user taps. `onMessageReceived` is not called for that message.
  • How do you control the icon, colour and channel of notifications the SDK displays for you?
    Per message, set them in the Android notification options (`icon`, `color`, `channel_id`). App-wide, add manifest meta-data `com.google.firebase.messaging.default_notification_icon`, `default_notification_color` and `default_notification_channel_id`. Without an icon, Android shows the app icon rendered in white; without a channel, the SDK falls back to a channel of its own.

  • onMessageReceived is called for every message, whatever the app state
  • A notification message pops up on its own while the app is in the foreground
  • Data payload values can be numbers, booleans or nested JSON objects
  • A data message displays a notification without any app code
  • Testing with the app open proves that background notifications work
open as a page

In Cloud Firestore, how do documents, collections and subcollections fit together, and what happens to a subcollection when its parent document is deleted?

level: juniorimportance: must knowfreq 68%

basics

~20 s

Firestore keeps fields in documents of up to 1 MiB, documents in collections, and lets a document own subcollections, so paths alternate collection and document. Deleting a document leaves its subcollections in place; they must be deleted separately.

open as a page

In Firebase Security Rules for Firestore, how do you let each student in a classroom app read only their own grades?

level: juniorimportance: must knowfreq 72%

basics

~10 s

Match the grades path with a wildcard for the student ID and allow reads only when request.auth.uid equals that wildcard. Firestore denies anything no rule allows, and each subcollection needs its own match block.

open as a page

With the Cloud Storage for Firebase Android SDK, how do putBytes, putStream and putFile differ, and how do you get a download URL afterwards?

level: juniorimportance: must knowfreq 62%

basics

~20 s

All three upload to a StorageReference and return an UploadTask: putBytes needs the whole byte array in memory, putStream reads an InputStream, putFile reads a file or content Uri. Ask the reference for getDownloadUrl() once the task succeeds.

open as a page

In Firebase Authentication, how long does an ID token live, what ends its refresh token, and when should an Android app force a refresh?

level: middleimportance: must knowfreq 68%

basics

~20 s

A Firebase ID token lasts one hour; the long-lived refresh token mints new ones until the user is deleted, disabled, changes password or email, or is revoked. Call getIdToken(true) only when server-side state such as custom claims changed.

open as a page

How does a backend verify a Firebase ID token with the Admin SDK's verifyIdToken, and what does that call not check?

level: middleimportance: must knowfreq 70%

basics

~20 s

The Admin SDK's verifyIdToken checks the RS256 signature against Google's public keys, the expiry and issue times, and that aud and iss name your project, then returns the uid and claims. It skips revocation and disabled-user checks unless checkRevoked is true.

open as a page

In Cloud Functions for Firebase, how does a callable onCall function differ from an HTTPS onRequest function, and when should an Android app use each?

level: middleimportance: must knowfreq 62%

basics

~20 s

A callable (onCall) uses a Firebase protocol: the client SDK sends the user's ID token, the function verifies it into request.auth, and HttpsError codes reach the app typed. An onRequest function is a raw HTTP endpoint you secure yourself.

open as a page

With FCM on Android, why does a backgrounded app never see a notification-plus-data message in onMessageReceived, and where does the data go?

level: middleimportance: must knowfreq 66%

basics

~20 s

When the app is not in the foreground, the FCM SDK displays the notification part itself and stops, so onMessageReceived never runs; the data pairs are copied into the extras of the intent the notification opens when tapped.

open as a page

Since firebase-messaging 25.1.0, how does an Android app register with FCM by Installation ID, and what replaces getToken and onNewToken?

level: middleimportance: must knowfreq 58%

basics

~10 s

Set the firebase_messaging_installation_id_enabled manifest flag, override onRegistered(installationId) to upload the Firebase Installation ID, and call register() when auto-init is off. These replace getToken, onNewToken and deleteToken, deprecated in firebase-messaging 25.1.0.

open as a page

In Cloud Firestore on Android, why does whereEqualTo on assigneeId combined with orderBy on dueDate fail at runtime, and how do you fix it?

level: middleimportance: must knowfreq 75%

basics

~20 s

Firestore serves every query from an index, and automatic indexes cover single fields only. Equality on one field plus ordering by another needs a manual (composite) index. Until one exists the query fails with FAILED_PRECONDITION and a link to create it.

open as a page

In Cloud Firestore on Android, when do you use runTransaction instead of a WriteBatch, and what rules must a transaction function follow?

level: middleimportance: must knowfreq 66%

basics

~20 s

Use runTransaction when a write depends on data you read, such as claiming an unassigned task; use a WriteBatch for atomic writes that need no reads. A transaction function reads before writing, may rerun, must avoid side effects, and fails offline.

open as a page

In Firestore, why does a student's query over the grades collection fail with PERMISSION_DENIED when Security Rules let them read their own grades?

level: middleimportance: must knowfreq 68%

basics

~20 s

Security Rules are not filters. Firestore checks a query against every document it could possibly return, so an unconstrained query fails outright; the query must carry the same constraint as the rule, such as whereEqualTo on studentId.

open as a page

In Firebase Hosting's firebase.json, how does the SPA fallback rewrite to /index.html work, and what can a careless catch-all rewrite break?

level: middleimportance: must knowfreq 55%

basics

~20 s

A catch-all rewrite whose destination is /index.html serves the app shell for any path that has no deployed file. Careless catch-alls hide 404.html, shadow function rewrites listed after them, and answer missing script requests with HTML.

open as a page

An onDocumentCreated trigger in Cloud Functions for Firebase decrements stock for each new order, and stock sometimes drops twice for one order; why, and how do you fix it?

level: seniorimportance: must knowfreq 58%

basics

~20 s

Firestore events are delivered at least once, so one order can run the trigger twice, and retries replay failures. Make it idempotent: check and write a marker keyed by the order or event.id in the decrement's transaction.

open as a page

In Firebase Authentication on Android, what is an anonymous account, and how do you upgrade a guest to Google sign-in without losing their data?

level: juniorimportance: should knowfreq 55%

basics

~20 s

An anonymous account is a real Firebase user with a uid but no sign-in credential, created by signInAnonymously. To upgrade, pass the Google credential to the current user's linkWithCredential, which attaches it and keeps the same uid.

open as a page

In Cloud Functions for Firebase, what does a 2nd-gen Firestore trigger such as onDocumentCreated or onDocumentUpdated give your handler, and when does it fire?

level: juniorimportance: should knowfreq 50%

basics

~20 s

A Firestore trigger fires when a document matching its path is created, updated, deleted or written. The handler gets an event holding a snapshot, or a before and after pair for updates, plus the wildcard values in event.params.

open as a page

In Firebase Security Rules for Cloud Storage, how do you limit a student's assignment upload to their own folder, PDF files and a maximum size?

level: juniorimportance: should knowfreq 34%

basics

~10 s

In a service firebase.storage ruleset, match /submissions/{studentId}/{fileName} and allow create only when request.auth.uid equals studentId, request.resource.size is under the cap and request.resource.contentType is application/pdf.

open as a page

In Cloud Functions for Firebase, how do parameters from firebase-functions/params and secrets from defineSecret get their values, and what breaks when they are misused?

level: middleimportance: should knowfreq 38%

basics

~20 s

Parameters such as defineString and defineInt are typed values the CLI resolves at deploy time from .env files, defaults or a prompt. Secrets from defineSecret live in Cloud Secret Manager and reach only functions that list them in secrets.

open as a page

How is an FCM HTTP v1 send request addressed and authorized, and where do Android options like priority, TTL and collapse key go?

level: middleimportance: should knowfreq 42%

basics

~10 s

POST a {"message": ...} body to https://fcm.googleapis.com/v1/projects/PROJECT_ID/messages:send with a short-lived OAuth2 bearer token for a service account. Android options sit in the message's android block: priority, ttl, collapse_key and notification fields.

open as a page

In Cloud Firestore on Android, how do snapshot listener metadata flags reveal unsynced writes and cached data, and how is offline persistence configured?

level: middleimportance: should knowfreq 55%

basics

~10 s

Android snapshot listeners fire at once for local writes, flagged by hasPendingWrites, and mark cache-served data with isFromCache; metadata-only changes need MetadataChanges.INCLUDE. Persistence is on by default and tuned with setLocalCacheSettings and PersistentCacheSettings.

open as a page

How does Firebase Realtime Database differ from Cloud Firestore in data model, queries, offline behaviour and scale, and when would you still choose it?

level: middleimportance: should knowfreq 48%

basics

~20 s

Realtime Database is one JSON tree with deep reads, single-property queries, native presence via onDisconnect and very low latency, sharded past one database's limits. Firestore has documents, indexed compound queries and automatic scaling. RTDB suits presence and frequent small state syncs.

open as a page

How do you unit-test Firestore Security Rules against the Firebase Local Emulator Suite before deploying them?

level: middleimportance: should knowfreq 30%

basics

~10 s

Run the Firestore emulator and test with @firebase/rules-unit-testing: initializeTestEnvironment loads the rules, authenticatedContext and unauthenticatedContext fake users and claims, withSecurityRulesDisabled seeds data, and assertSucceeds or assertFails check each request.

open as a page

In Firestore Security Rules, how do resource.data and request.resource.data differ, and how do you stop a grade update from changing protected fields?

level: middleimportance: should knowfreq 52%

basics

~10 s

resource.data is the document as stored before the write; request.resource.data is the whole document as it would be after it. Protect fields on update with request.resource.data.diff(resource.data).affectedKeys().hasOnly([...]) plus type and range checks.

open as a page

In Cloud Storage for Firebase, what does a URL from getDownloadUrl() grant, how do Storage Security Rules apply to it, and how is it revoked?

level: middleimportance: should knowfreq 45%

basics

~20 s

It is a long-lived HTTPS link with a token that lets anyone holding it read the file without signing in. Storage rules check the app's getDownloadUrl() call, not each fetch, and revoking the token in the Firebase console kills the URL.

open as a page

How do Firebase Hosting preview channels work, how long does one last, and how do you promote a tested preview to the live site?

level: middleimportance: should knowfreq 32%

basics

~20 s

firebase hosting:channel:deploy CHANNEL_ID publishes the Hosting content and config to a temporary public URL that expires after seven days by default, 30 at most. The preview uses the real backend; hosting:clone copies the tested version to live.

open as a page

After your backend sets a Firebase Authentication custom claim with setCustomUserClaims, why does the Android app not see it, and how do you fix it?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Custom claims travel inside the ID token, and the token on the phone was issued before the change. They appear only in the next token: at sign-in, at the hourly refresh, or when the app calls getIdToken(true) after the backend confirms.

open as a page

With the Firebase Admin SDK, how do you cut off a stolen phone's session in a notes app, and why might its calls still succeed?

level: seniorimportance: should knowfreq 40%

basics

~10 s

Call revokeRefreshTokens(uid) so no device can mint new ID tokens. ID tokens already issued stay valid for up to an hour, so endpoints that must refuse them at once verify with verifyIdToken(idToken, true).

open as a page

When you move a Cloud Functions for Firebase function from 1st gen to 2nd gen, what changes in how it runs, and what can break?

level: seniorimportance: should knowfreq 40%

basics

~20 s

2nd gen deploys each function as a Cloud Run service: an instance serves up to 80 concurrent requests by default, small functions get a full CPU, the default service account changes, and the event retry window drops to 24 hours.

open as a page

In an Android FirebaseMessagingService, why do some 'courier nearby' alerts never appear when onMessageReceived fetches courier details before posting the notification?

level: seniorimportance: should knowfreq 44%

basics

~20 s

onMessageReceived gets a short window, several seconds, before the process may lose its valid lifecycle; a network fetch first can be paused or killed by background limits. Post from the payload at once and hand slower work to WorkManager.

open as a page

A parcel-tracking backend sending through the FCM Admin SDK sees send failures pile up; which stored registrations should it delete, and on which errors must it keep them?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Delete a registration on UNREGISTERED (404), and on INVALID_ARGUMENT (400) only when the payload is known valid. Keep it on rate-limit, unavailable, internal or credential errors: retry or fix configuration. Also prune by upload timestamp.

open as a page

showing 1–30 of 36