Most Popular
We have SDKs in Ruby, Go, Python, Javascript, Node.js, and React.
Sign up
In mobile development, push notifications are vital to support the full UX of the app and to sustain user engagement. However, integrating push notifications into your app can be a complex chore, involving a multitude of tools, APIs, token management, and more. This is precisely the puzzle that Courier, a notification platform and API, can help you solve.
Courier allows developers to easily connect their app to Firebase to send and automate push notifications. With Courier, you can trigger push notifications at just the right time and personalize them to fit your users’ interests and preferences. And because Courier supports multiple notification methods, you build automated sequences that extend across email, SMS, chat and more.
Courier empowers you, as a developer, to manage these steps independently. This can streamline your workflow, bypassing the typical back-and-forth between front end, back end, and project management.
In this article, we'll explore how to use Courier to send and automate push notifications using Flutter, Firebase, and Node.js. In this case we’ll be looking at push notifications for a mobile app but Courier also supports push “toast” notifications for web applications and can even sync delivery and read status across the two.
You can find the detailed video guide to the steps found in this article on YouTube and complete code examples on GitHub.
To begin with, you will need to create a Firebase project. If you do not have a Firebase account yet, visit the Firebase website and click on the Get started button.
Once you’ve created your project, you will be redirected to a UI like the one below. Click on the Flutter icon to add Firebase to your Flutter app.
Then, follow the instructions to learn how to add Firebase to your Flutter app.
Once you’ve added Firebase to your Flutter app, your main.dart
file should look similar to this:
1import 'package:courier_flutter/courier_flutter.dart';2import 'package:courier_flutter/courier_provider.dart';3import 'package:courier_flutter/ios_foreground_notification_presentation_options.dart';4import 'package:firebase_core/firebase_core.dart';5import 'package:firebase_messaging/firebase_messaging.dart';6import 'package:flutter/material.dart';7import 'package:flutter_decode/firebase_options.dart';89Future<void> main() async {1011WidgetsFlutterBinding.ensureInitialized();1213await Firebase.initializeApp(14options: DefaultFirebaseOptions.currentPlatform,15);1617runApp(const MyApp());18}
Setting up push notifications in a Flutter app involves configuring settings for both iOS and Android platforms separately. This is because each platform has unique requirements and APIs for notifications.
Let's start with the setup for iOS.
flutter pub add courier_flutter
to add the SDK to your project.ios
folder and run Runner.xcworkspace
from Xcode to access the iOS side of the Flutter project.ios
folder in the terminal. Then, run cd ios && pod update
.CourierFlutterDelegate
.import courier_flutter
at the top of your AppDelegate file. Your file should look like this:1import UIKit2import Flutter3import courier_flutter45@UIApplicationMain6@objc class AppDelegate: CourierFlutterDelegate {7override func application(8_application: UIApplication,9didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?10) -> Bool {11GeneratedPluginRegistrant.register(with: self)12return super.application(application, didFinishLaunchingWithOptions: launchOptions)13}14}
sh make_template.sh
.podfile
and run pod install
in your Flutter project's iOS directory.1target 'CourierService' do2use_frameworks!3pod 'Courier-iOS'4end
Now that we have completed the setup for iOS, let's proceed with the setup for Android.
First, open the Android folder of your Flutter project using Android Studio.
Then add support for Jitpack by updating android/build.gradle
.
1allprojects {2repositories {3google()4mavenCentral()5maven { url 'https://jitpack.io' } // Add this line6}7}
app/build.gradle
, change the minimum Android Flutter version to 21 and the compilation SDK version to 33.MainActivity
to extend the CourierFlutterActivity
to ensure that Courier can handle incoming push notifications properly.1import android.annotation.SuppressLint2import com.courier.android.notifications.presentNotification3import com.courier.android.service.CourierService4import com.google.firebase.messaging.RemoteMessage56// It's OK to do SuppressLint because CourierService will handle token refreshes automatically .7@SuppressLint("MissingFirebaseInstanceTokenRefresh")8class YourNotificationService: CourierService() {910override fun showNotification(message: RemoteMessage) {11super.showNotification(message)1213// TODO: This is where you will customize the notification that is shown to your users14// For Flutter, there is usually no need to change the handlingClass15// See16// https://developer.android.com/develop/ui/views/notifications/build-notification17// for more details on customizing an Android notification.1819message.presentNotification(20context = this,21handlingClass = MainActivity::class.java,22icon = android.R.drawable.ic_dialog_info23)24}25}
Next, add the Notification Service entry in your AndroidManifest.xml
file.
1<manifest>2<application>34<activity>5..6</activity>78<service9android:name=".YourNotificationService"10android:exported="false">11<intent-filter>12<action android:name="com.google.firebase.MESSAGING_EVENT" />13</intent-filter>14</service>1516..1718</application>19</manifest>
To configure the push provider, first, you need to connect the Apple push notification key to Firebase and then link the Firebase project to Courier. Here's how to do it:
You can use the code snippets below to manage your application's user states on both iOS and Android. This is a Flutter-wide operation and isn't specific to either platform.
The following saves accessToken
and userId
to native local storage, allowing them to persist between app sessions.
1await Courier.shared.signIn(2accessToken: accessToken, // You can use Courier Auth Key3userId: userId,4);56await Courier.shared.signOut();
For the iOS application, you need to sync the FCM tokens manually. For that, use the below code:
1// Notification permissions must be authorized on iOS to receive pushes2final requestedNotificationPermission = await Courier.shared.requestNotificationPermission();3print(requestedNotificationPermission);45final fcmToken = await FirebaseMessaging.instance.getToken();6if (fcmToken != null) {7await Courier.shared.setFcmToken(token: fcmToken);8}910// Handle FCM token refreshes11FirebaseMessaging.instance.onTokenRefresh.listen((fcmToken) {12Courier.shared.setFcmToken(token: fcmToken);13});
Courier allows you to send a push notification to a user ID directly from the SDK.
1final notificationPermission = await Courier.shared.getNotificationPermissionStatus();2print(notificationPermission);34// Notification permissions need to be 'authorized' on iOS in order to receive pushes5final requestedNotificationPermission = await Courier.shared.requestNotificationPermission();6print(requestedNotificationPermission);78// This configures how iOS will display the notification when the app is running in the foreground9// If you pass [] it won't present anything10// but Courier.shared.onPushNotificationDelivered will still be called11Courier.shared.iOSForegroundNotificationPresentationOptions = [12iOSNotificationPresentationOption.banner,13iOSNotificationPresentationOption.sound,14iOSNotificationPresentationOption.list,15iOSNotificationPresentationOption.badge,16];1718// This will be called if a push notification arrives19while the app is running in the foregroundCourier.shared.onPushNotificationDelivered = (push) {20...21};2223// This will be called if the user clicks on a push notification24Courier.shared.onPushNotificationClicked = (push) {25...26};2728// This will send a test push29final messageId = await Courier.shared.sendPush(30authKey: 'a_courier_auth_key_that_should_only_be_used_for_testing',31userId: 'example_user',32title: 'Summer Sale!',33body: 'Hundreds of hot summer offers',34isProduction: false, // false == sandbox / true == production35(only affects APNs pushes). providers: [CourierProvider.apns, CourierProvider.fcm],36);
Now you can run your Flutter project and send push notifications to both iOS and Android devices.
The Courier JavaScript SDK can be used to easily send push notifications to a selected user. For example, the code below sends a push notification to the specified user ID.
1const Courier = require('@trycourier/courier')23const courier = Courier.CourierClient({ authorizationToken: "AUTH_TOKEN" });45async function test() {67const userId = "courier_user"8const title = "Hello!"9const body = "This message was sent from Node.js"1011const { requestId } = await courier.send({12message: {13to: {14user_id: userId,15},16content: {17title: title,18body: body,19},20routing: {21method: "single",22channels: ["firebase-fcm"],23},24},25});2627console.log(requestId)28}
You can use the user state management code snippet given in step 5 to capture the user IDs. Courier will store each user's ID and push notifications token separately. You can find the user details from the Courier User tab.
Furthermore, you can use the Courier Designer tab to create notification templates without any code.
Once you publish the notification, Courier will provide an auto-generated code snippet for your favorite language with the template ID in the Send tab.
1// Install with: npm install @trycourier/courier2import { CourierClient } from "@trycourier/courier";34const courier = CourierClient({ authorizationToken: "AUTH_TOKEN" });56const { requestId } = await courier.send({7message: {8to: {9firebaseToken: "FIREBASE_TOKEN",10},11template: "4V0142YBX84G1WN1SK3W4S01QZNC",12data: {13},14},15});
In conclusion, as a developer, harnessing the combined power of Courier, Flutter, Firebase, and Node.js enables you to send and automate push notifications with greater efficiency.
A key advantage of this approach is the autonomy it gives you as a mobile engineer. You can manage all these steps from start to finish without the usual back-and-forth between front-end and back-end developers and project managers. This independence can drastically streamline the development process, saving you valuable time and resources.
Courier's notification platform allows for seamless integration of your app with Firebase, facilitating not only the easy setup of push notifications, but also token management and the automation of notifications, tailored to your users' individual preferences and activities.
Head to the docs to learn more or contact us if you have questions about your unique use case.
We have SDKs in Ruby, Go, Python, Javascript, Node.js, and React.
Sign up
How to Set Up Automatic Push Notifications Based on Segment Events
Push notifications have carved their own niche as a powerful tool for continuous user engagement. Regardless of whether an app is actively in use, they deliver your messages straight to your user's device. Two key players that can combine to enhance your push notification strategy are Segment and Courier. In this tutorial, we show you how to set up Courier to listen to your Segment events and then send push notifications to an Android device based on data from these events.
Sarah Barber
November 17, 2023
How to Send Firebase Notifications to iOS Devices Using Courier
This tutorial explains how to send push notifications to iOS devices from your iOS application code using Firebase FCM and Courier’s iOS SDK.
Martina Caccamo
November 01, 2023
Free Tools
Comparison Guides
Send up to 10,000 notifications every month, for free.
Get started for free
Send up to 10,000 notifications every month, for free.
Get started for free
© 2024 Courier. All rights reserved.