Skip to main content

How to Enable Push Notifications in an App: A Complete Guide


Set Up Firebase Cloud Messaging (FCM)

Firebase Cloud Messaging (FCM) allows you to send notifications to users. To set it up:

  1. In the Firebase Console, go to Cloud Messaging.
  2. Get your Server Key and Sender ID from the Firebase Console. You will need the Server Key to send notifications from the backend and the Sender ID to send them from the frontend.
  3. Install the Firebase SDK for messaging:
  4.             npm install firebase
            
  5. In your React Native app, configure Firebase Cloud Messaging:

your-project/
├── app/
│   ├── _layout.tsx              ← initialize notifications
│   └── (tabs)/
│       └── index.tsx
├── components/
│   ├── firebase.tsx             ← Firebase Auth/config
│   └── notifications.ts         ← push notification code
├── assets/
│   └── notification-icon.png
├── app.json                     ← Expo notification configuration
└── package.json

React Native Example: Firebase Cloud Messaging (notifications.tsx)

        import * as Notifications from "expo-notifications";

import * as Device from "expo-device";

import Constants from "expo-constants";

import { Platform } from "react-native";



Notifications.setNotificationHandler({

  handleNotification: async () => ({

    shouldShowBanner: true,

    shouldShowList: true,

    shouldPlaySound: true,

    shouldSetBadge: false,

  }),

});



export async function registerForPushNotificationsAsync() {

  if (!Device.isDevice) {

    console.log("Push notifications require a physical device.");

    return null;

  }



  // Android notification channel

  if (Platform.OS === "android") {

    await Notifications.setNotificationChannelAsync("default", {

      name: "default",

      importance: Notifications.AndroidImportance.MAX,

      vibrationPattern: [0, 250, 250, 250],

      sound: "default",

    });

  }



  // Request permission

  const { status: existingStatus } =

    await Notifications.getPermissionsAsync();



  let finalStatus = existingStatus;



  if (existingStatus !== "granted") {

    const { status } =

      await Notifications.requestPermissionsAsync();



    finalStatus = status;

  }



  if (finalStatus !== "granted") {

    console.log("Notification permission was not granted.");

    return null;

  }



  // Get Expo push token

  const projectId =

    Constants.expoConfig?.extra?.eas?.projectId ??

    Constants.easConfig?.projectId;



  if (!projectId) {

    console.log("EAS project ID not found.");

    return null;

  }



  const token = (

    await Notifications.getExpoPushTokenAsync({

      projectId,

    })

  ).data;



  console.log("Expo Push Token:", token);



  return token;

}


    

Backend Integration (Optional)

If you need to send notifications from the backend (e.g., to notify users when an order status changes), you can use Firebase Admin SDK to send push notifications:

Example: Send Notification from Backend (FastAPI Endpoint)

        @app.put("/orders/{order_id}/status")
async def update_order_status(
    order_id: int,
    status: str,
):
    # update database
    ...
You can do:

from notifications import send_push_notification


@app.put("/orders/{order_id}/status")
async def update_order_status(
    order_id: int,
    status: str,
):
    # 1. Find order
    order = get_order(order_id)

    if not order:
        return {"error": "Order not found"}

    # 2. Update status
    order.status = status

    # 3. Save to database
    save_order(order)

    # 4. Get customer's push token
    user = get_user(order.user_id)

    if user.expo_push_token:

        await send_push_notification(
            token=user.expo_push_token,
            title="Order Update",
            body=f"Your order #{order_id} is now {status}.",
            data={
                "type": "ORDER_STATUS",
                "orderId": str(order_id),
                "status": status,
            },
        )

    return {
        "success": True,
        "order_id": order_id,
        "status": status,
    }
    

              YOUR APP
                 │
                 │ token
                 ▼
             YOUR API
                 │
                 ▼
              DATABASE
                 │
                 │
        Order status changes
                 │
                 ▼
              BACKEND
                 │
                 ▼
       Expo Push Notification
            │          │
            ▼          ▼
           FCM        APNs
            │          │
            ▼          ▼
         Android      iPhone

Conclusion

Firebase offers a variety of powerful services for integrating user authentication, push notifications, real-time databases, and more into your app. By following these steps, you can set up Firebase Authentication to handle user login and Firebase Cloud Messaging (FCM) for push notifications in your React Native app.




inside layout.tsx

import { useEffect } from "react";
import { registerForPushNotificationsAsync } from "../components/notifications";


inside component layout.tsx
useEffect(() => {
  registerForPushNotificationsAsync().then((token) => {
    if (token) {
      console.log("User push token:", token);

      // TODO:
      // Send this token to your backend
    }
  });
}, []);


in app.json

{
  "expo": {
    "name": "Your App",
    "slug": "your-app",
    "plugins": [
      "expo-router",
      [
        "expo-notifications",
        {
          "icon": "./assets/notification-icon.png",
          "color": "#ffffff"
        }
      ]
    ]
  }
}










Contact Us

Name

Email *

Message *

Popular Posts

UGC NET Electronic Science Previous Year Question Papers with Solutions

Home / Engineering & Other Exams / UGC NET 2026 PYQ ⬇️ Download Papers and Solutions 📋 Exam Pattern 💡 Preparation Tips ❓ FAQs 📊 Exam Highlights: Electronic Science (88) Feature Details Junior Research Fellowship (JRF) ₹37,000 + HRA per month Eligibility M.Sc/M.Tech in Electronics (55%) Validity of Certificate JRF (3 Years) | Lectureship (Lifetime) 📥 Download UGC NET Electronics PDFs Complete collection of previous year question papers, answer keys and explanations for Subject Code 88. Start Downloading 📂 View All Question Papers June 2025 - Question Paper Download PDF June 2025 - Solved Paper + Explanation ...

Design of CMOS XOR/XNOR Gates

Design of CMOS XOR/XNOR Gates The semiconductor industry has experienced rapid integration of multimedia applications into mobile electronics, leading to very high integration density in CMOS VLSI. As operating frequencies increase, power consumption, speed, silicon area, and reliability become critical considerations. The XOR-XNOR circuits are fundamental building blocks in arithmetic circuits (Full Adders, Multipliers), compressors, comparators, parity checkers, code converters, error-detecting/correcting codes, and phase detectors. Their performance directly impacts the complex circuits they are used in. Design goals include full output voltage swing, low power consumption, reduced transistor count, minimal delay, and simultaneous non-skewed outputs. Static Logic (Static CMOS) Stat...

Online Simulator for ASK, FSK, and PSK Signal Generation

Interactive Digital Signal Processing (DSP) Tutorial and Simulator for ASK, FSK, and BPSK modulation techniques. Try our new Digital Signal Processing Simulator!   •   Interactive ASK, FSK, and BPSK tools updated for 2025. Start Now Digital Modulation Visualizer: ASK, FSK, & BPSK Simulator Learn and visualize binary modulation techniques (ASK, FSK, BPSK) in real-time with adjustable carrier and sampling parameters. Perfect for DSP students and engineers. 📡 ASK Simulator 📶 FSK Simulator 🎚️ BPSK Simulator 📚 More Topics ASK Modulator FSK Modulator BPSK Modulator More Topics 1. ASK (Amplitude Shift Keying) Simulat...

OFDM Symbols and Subcarriers Explained

This article explains how OFDM (Orthogonal Frequency Division Multiplexing) symbols and subcarriers work. It covers modulation, mapping symbols to subcarriers, subcarrier frequency spacing, IFFT synthesis, cyclic prefix, and transmission. Step 1: Modulation First, modulate the input bitstream. For example, with 16-QAM , each group of 4 bits maps to one QAM symbol. Suppose we generate a sequence of QAM symbols: s0, s1, s2, s3, s4, s5, …, s63 Step 2: Mapping Symbols to Subcarriers Assume N sub = 8 subcarriers. Each OFDM symbol in the frequency domain contains 8 QAM symbols (one per subcarrier): Mapping (example) OFDM symbol 1 → s0, s1, s2, s3, s4, s5, s6, s7 OFDM symbol 2 → s8, s9, s10, s11, s12, s13, s14, s15 … OFDM sym...

UGC NET Electronic Science June 2025 Question Paper with Answer Key & Detailed Solutions

Home / UGC NET PYQ / June 2025 Solved UGC NET Electronic Science June 2025 Question Paper with Answer Key and Full Explanations 📥 Download Question Paper (PDF) 2025 2024 2023 2022 2021 2020 Explanations 1.  Answer: Option (3) For forming a p-type semiconductor, the dopant must be a trivalent impurity (three valence electrons) so that it creates acceptor levels and holes become the majority carriers. Among the given elements, boron (B) is a group-III element (trivalent). Arsenic (As) and phosphorus (P) are group-V (pentavalent) donors that produce n-type material, and germanium (Ge) is a group-IV element usually used as the semiconductor, not as an acceptor dopant. Hence, doping an intrinsic semiconductor with B produces a p-type semiconductor. 2.  Answer: Option (4) The ohmic resistance of a JFET at zero gate bias is given by the standard relation: R DS(on) = V P / I DSS ...

MIMO Channel Matrix | Rank and Condition Number

MIMO / Massive MIMO MIMO Channel Matrix | Rank and Condition...   The channel matrix in wireless communication is a matrix that describes the impact of the channel on the transmitted signal. The channel matrix can be used to model the effects of the atmospheric or underwater environment on the signal, such as the absorption, reflection or scattering of the signal by surrounding objects. When addressing multi-antenna communication, the term "channel matrix" is used. Let's assume that only one TX and one RX are in communication and there's no surrounding object. Here, in our case, we can apply the proper threshold condition to a received signal and get the original transmitted signal at the RX side. However, in real-world situations, we see signal path blockage, reflections, etc.,  (NLOS paths [↗]) more frequently. The obstruction is typically caused by building walls, etc. Multi-antenna communication was introduced to address this issue. It makes diversity app...