> ## Documentation Index
> Fetch the complete documentation index at: https://v0.x-docs.novu.co/llms.txt
> Use this file to discover all available pages before exploring further.

# Firebase Cloud Messaging (FCM)

> Learn how to use the Firebase Cloud Messaging (FCM) provider to send push notifications using Novu

[Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging) is a free notification delivery service provided by Google Firebase.

To enable the FCM integration, you need to get your service account key from the [Firebase Console](https://console.firebase.google.com/).

## Generating a Service Account Key JSON

To acquire the account key JSON file for your service account

1. Select your project, and click the gear icon on the top of the sidebar.
2. Head to project settings.
3. Navigate to the service account tab.
4. Click **Generate New Private Key,** then confirm by clicking **Generate Key.**
5. Clicking **Generate Key** downloads the JSON file.

After that, paste the entire JSON file content in the Service Account field of the FCM provider in the integration store on Novu’s web dashboard.

Make sure your service account json content contains these fields

```json theme={null}
{
  "type": "service_account",
  "project_id": "PROJECT_ID",
  "private_key_id": "PRIVATE_KEY_ID",
  "private_key": "PRIVATE_KEY",
  "client_email": "FIREBASE_ADMIN_SDK_EMAIL",
  "client_id": "CLIENT_ID",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "CLIENT_X509_CERT_URL"
}
```

## FCM Overrides

The overrides field supports apns, android, webpush and fcmOptions overrides

| Override Field | Type / Interface | Link                                                                                                                                                                                         |
| -------------- | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| android        | AndroidConfig    | [https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.androidconfig](https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.androidconfig) |
| apns           | ApnsConfig       | [https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.apnsconfig](https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.apnsconfig)       |
| webPush        | WebpushConfig    | [https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.webpushconfig](https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.webpushconfig) |
| fcmOptions     | FcmOptions       | [https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.fcmoptions](https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.fcmoptions)       |

## Setting Device Token

Before triggering the notification to a subscriber(user) with push as a step in the workflow, make sure you have added the subscriber's device token as follows:

<Tabs>
  <Tab title="Node.js">
    ```javaScript theme={null}
    import {
      Novu,
      PushProviderIdEnum
    } from '@novu/node';

    const novu = new Novu("<NOVU_API_KEY>");

    await novu.subscribers.setCredentials(
      'subscriberId', 
      PushProviderIdEnum.FCM, 
      { deviceTokens: ['token1', 'token2'] }, 
      'fcm-MnGLxp8uy'
    );
    ```
  </Tab>

  <Tab title="cURL">
    ```bash theme={null}
    curl -L -X PUT 'https://api.novu.co/v1/subscribers/<SUBSCRIBER_ID>/credentials' \
    -H 'Content-Type: application/json' \
    -H 'Accept: application/json' \
    -H 'Authorization: ApiKey <NOVU_API_KEY>' \
    -d '{
      "providerId": "fcm",
      "credentials": {
        "deviceTokens" : [
          "token1", 
          "token2"
        ]
      },
      "integrationIdentifier": "fcm-MnGLxp8uy"
    }'
    ```
  </Tab>
</Tabs>

Checkout the [API reference](/api-reference/subscribers/update-subscriber-credentials) for more details.

## SDK Trigger Example

```jsx theme={null}
import { Novu } from "@novu/node";

const novu = new Novu("<NOVU_API_KEY>");

novu.trigger("<WORKFLOW_TRIGGER_IDENTIFIER>", {
  to: {
    subscriberId: "<SUBSCRIBER_ID>",
  },
  payload: {
    abc: "def", // If the notification is a data notification, the payload will be sent as the data
  },
  overrides: {
    fcm: {
      // type: 'data' => will turn this into an FCM data notification, where the payload is sent as a data notification. If the type is not set, you can use the "data" override to send notification messages with optional data payload
      type: "data",

      // URL of an image to be displayed in the notification.
      imageUrl: "https://domain.com/image.png",

      // If type is not set, you can use the "data" override to send notification messages with optional data payload
      data: {
        key: "value",
      },

      // Check FCM Overrides section above for these types
      android: {},
      apns: {},
      webPush: {},
      fcmOptions: {},
    },
  },
});
```

Device/notification identifiers can be set by using [setCredentials](#set-device-token) or by using the `deviceIdentifiers` field in overrides.

<Info> Novu uses FCM version V1</Info>

## Relative Link in Webpush

Suppose you’re using the Firebase (FCM) provider to send push notifications to web browsers via Novu and want users to be returned to the website after clicking the notification.

In that case, you must use the `link` property with a relative URL.

<Tabs>
  <Tab title="Node.js">
    ```javascript theme={null}
    import { Novu } from "@novu/node";

    const novu = new Novu("<NOVU_API_KEY>");

    novu.trigger("<WORKFLOW_TRIGGER_IDENTIFIER>", {
      to: {
        subscriberId: "<SUBSCRIBER_ID>",
      },
      payload: {
        abc: "def", // If the notification is a data notification, the payload will be sent as the data
      },
      overrides: {
        fcm: {
          webPush: {
            fcmOptions: {
              link: "/foo",
            },
          },
        },
      },
    });
    ```
  </Tab>

  <Tab title="Curl">
    ```bash theme={null}
    curl --location --request POST 'https://url.to.our.selfhosted.novu' \
        --header 'Authorization: ApiKey KEY' \
        --header 'Content-Type: application/json' \
        --data-raw '{
            "name": "workflow-name",
            "to": {
                ...
            },
            "overrides": {
              "fcm": {
                "webPush": {
                  "fcm_options": {
                    "link": "/foo"
                  }
                }
              }
            }
          }'
    ```
  </Tab>
</Tabs>

## FCM Cost

As per Firebase [pricing](https://firebase.google.com/pricing), **Cloud Messaging** product is free of cost to use. If other Firebase products are used, the cost will be charged as per the product.

## FAQs

<AccordionGroup>
  <Accordion title="The registration token is not a valid FCM registration token">
    You may come across an error like so:

    ""Sending message failed due to "The registration token is not a valid FCM registration token""".

    This error happens because of invalid or stale token. The fix for this is to remove old tokens, generate a new token and save it into user subscribers.
  </Accordion>

  <Accordion title="FCM notifications sent successfully with no error but push notification is not received in device">
    Try to generate a new token after clearing device cache and retry with this fresh token.
  </Accordion>

  <Accordion title="Sending message failed due to 'Requested entity was not found'">
    This error occurs when your token is no longer valid. To fix this, generate a new token and use it.
  </Accordion>

  <Accordion title="Subscriber does not have a configured channel error">
    This error occurs if the fcm integration is active but subscriber is missing from the fcm credentials (deviceTokens). The credentials (deviceTokens) for the subscriber needs to be set.
  </Accordion>
</AccordionGroup>
