Implement Firebase Push Notifications in React Native with Node.js Backend

Published: 23 November 2024
on channel: CodeCaty
101
2

In this tutorial, learn how to implement Firebase push notifications in a React Native app using the *React Native Firebase library* and a **Node.js backend**.
This step-by-step guide includes Firebase Admin SDK setup, backend configuration, and sending targeted push notifications. You'll also learn how to configure your React Native Android project for Firebase integration.

📌 *Key Topics Covered:*
Setting up Firebase Admin SDK for Node.js.
Sending push notifications using FCM.
Configuring `@react-native-firebase/messaging` in React Native.
Updating Android project files for Firebase integration.

📂 *Backend Code Examples:*

*Firebase Initialization:*
```javascript
const admin = require('firebase-admin');

// Load your Firebase service account key JSON file
const serviceAccount = require('./code-caty-firebase-adminsdk-lyq8m-38955fa402.json');

admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});

module.exports = admin;
```

*Send Notification Function:*
```javascript
const admin = require("./firebase");

async function sendNotificationToDevice(deviceToken, title, body) {
const message = {
notification: {
title: title,
body: body,
},
data: { name: "CODE_CATY" },
token: deviceToken, // FCM device token
};

try {
const response = await admin.messaging().send(message);
console.log("Notification sent successfully:", response);
} catch (error) {
console.error("Error sending notification:", error);
}
}

// Example usage
const deviceToken = "YOUR_DEVICE_FCM_TOKEN_HERE";
sendNotificationToDevice(
data.token,
"Code Caty",
"This is a test notification."
);
```

📂 *Android Configuration:*

Update *`android/app/build.gradle`:*
```gradle
// Add this line at the top of the file
apply plugin: 'com.google.gms.google-services'

dependencies {
// The version of react-native is set by the React Native Gradle Plugin
implementation("com.facebook.react:react-android")

// Add these lines for Firebase dependencies
implementation platform('com.google.firebase:firebase-bom:33.6.0')
implementation 'com.google.firebase:firebase-analytics'

if (hermesEnabled.toBoolean()) {
implementation("com.facebook.react:hermes-android")
} else {
implementation jscFlavor
}
}
```

Update *`android/build.gradle`:*
```gradle
dependencies {
classpath("com.android.tools.build:gradle")
classpath("com.facebook.react:react-native-gradle-plugin")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin")

// Add this line for Firebase services
classpath('com.google.gms:google-services:4.3.8')
}
```

🔗 *Resources Used:*
[React Native Firebase](https://rnfirebase.io/)
[Firebase Admin SDK Documentation](https://firebase.google.com/docs/admin)
[Node JS] (https://github.com/ashwani8090/fbNoti...)
🔥 Watch the video and enhance your app with real-time push notifications today!