Platform
Docs
Solutions
ContactLog In

Get started sending notifications with Courier in minutes, not days!

We have SDKs in Ruby, Go, Python, Javascript, Node.js, and React.

Sign up

Thumbnail for the Send & Automate Mobile Push Notifications with Courier article
TUTORIAL

Send and Automate Push Notifications Using Flutter, Firebase, and Node.js

Adam Searle

June 29, 2023

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.

Step 1 — Creating a Firebase project

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.

push-notifications-flutter-firebase-image1

push-notifications-flutter-firebase-image2

Step 2 — Adding Firebase to your Flutter project

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.

push-notifications-flutter-firebase-image3

Then, follow the instructions to learn how to add Firebase to your Flutter app.

push-notifications-flutter-firebase-image4

Once you’ve added Firebase to your Flutter app, your main.dart file should look similar to this:

1
import 'package:courier_flutter/courier_flutter.dart';
2
import 'package:courier_flutter/courier_provider.dart';
3
import 'package:courier_flutter/ios_foreground_notification_presentation_options.dart';
4
import 'package:firebase_core/firebase_core.dart';
5
import 'package:firebase_messaging/firebase_messaging.dart';
6
import 'package:flutter/material.dart';
7
import 'package:flutter_decode/firebase_options.dart';
8
9
Future<void> main() async {
10
11
WidgetsFlutterBinding.ensureInitialized();
12
13
await Firebase.initializeApp(
14
options: DefaultFirebaseOptions.currentPlatform,
15
);
16
17
runApp(const MyApp());
18
}

Step 3 — Implementing push notifications in the Flutter app

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.

iOS setup

  • Run the command flutter pub add courier_flutter to add the SDK to your project.
  • Open the ios folder and run Runner.xcworkspace from Xcode to access the iOS side of the Flutter project.
  • Go to Runner Target and set the minimum deployment to iOS 13.0.
  • Return to the Flutter project and navigate to the ios folder in the terminal. Then, run cd ios && pod update.
  • Now, open the AppDelegate file in Xcode, navigate to Runner > AppDelegate, and extend the file with CourierFlutterDelegate.
  • Don't forget to add import courier_flutter at the top of your AppDelegate file. Your file should look like this:
1
import UIKit
2
import Flutter
3
import courier_flutter
4
5
@UIApplicationMain
6
@objc class AppDelegate: CourierFlutterDelegate {
7
override func application(
8
_application: UIApplication,
9
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
10
) -> Bool {
11
GeneratedPluginRegistrant.register(with: self)
12
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
13
}
14
}
  • To enable push notifications, navigate to Runner Target > Signing and Capabilities > Capabilities_ and click on Push Notifications.
  • In addition, you need to add a Notification Service Extension to track when a notification is delivered to the device. You can download the Courier Notification Service Extension here.
  • Unzip it, open it in the terminal, and run sh make_template.sh.
  • Add a new target in Xcode and select the Courier Notification Service.
  • Once you've added the extension, you can monitor notifications even when the app is completely closed. To do this, go to the General tab and change the development info to iOS 13.0.
  • Finally, add the below code snippet to podfile and run pod install in your Flutter project's iOS directory.
1
target 'CourierService' do
2
use_frameworks!
3
pod 'Courier-iOS'
4
end

Now that we have completed the setup for iOS, let's proceed with the setup for Android.

Android setup

First, open the Android folder of your Flutter project using Android Studio.

Then add support for Jitpack by updating android/build.gradle.

1
allprojects {
2
repositories {
3
google()
4
mavenCentral()
5
maven { url 'https://jitpack.io' } // Add this line
6
}
7
}
  • In app/build.gradle, change the minimum Android Flutter version to 21 and the compilation SDK version to 33.
  • Run Gradle sync.
  • Update MainActivity to extend the CourierFlutterActivity to ensure that Courier can handle incoming push notifications properly.
  • Next, you need to create a new Notification Service by adding a new file to your project. This code will allow your app to receive and process push notifications reliably and efficiently.
1
import android.annotation.SuppressLint
2
import com.courier.android.notifications.presentNotification
3
import com.courier.android.service.CourierService
4
import com.google.firebase.messaging.RemoteMessage
5
6
// It's OK to do SuppressLint because CourierService will handle token refreshes automatically .
7
@SuppressLint("MissingFirebaseInstanceTokenRefresh")
8
class YourNotificationService: CourierService() {
9
10
override fun showNotification(message: RemoteMessage) {
11
super.showNotification(message)
12
13
// TODO: This is where you will customize the notification that is shown to your users
14
// For Flutter, there is usually no need to change the handlingClass
15
// See
16
// https://developer.android.com/develop/ui/views/notifications/build-notification
17
// for more details on customizing an Android notification.
18
19
message.presentNotification(
20
context = this,
21
handlingClass = MainActivity::class.java,
22
icon = android.R.drawable.ic_dialog_info
23
)
24
}
25
}

Next, add the Notification Service entry in your AndroidManifest.xml file.

1
<manifest>
2
<application>
3
4
<activity>
5
..
6
</activity>
7
8
<service
9
android:name=".YourNotificationService"
10
android:exported="false">
11
<intent-filter>
12
<action android:name="com.google.firebase.MESSAGING_EVENT" />
13
</intent-filter>
14
</service>
15
16
..
17
18
</application>
19
</manifest>
  • Finally, run the project to make sure that there are no build issues.

Step 4 — Configuring the push provider

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:

  • First, in your Apple developer account, go to Certificates, Identifiers & Profiles. Create a new Apple Push Notification service (APNs) key and download it.

push-notifications-flutter-firebase-image5

  • Next, open your Firebase project and go to Project Settings > Cloud Messaging > Apple App Configuration. Click on your app and upload the APN key to the APNs Authentication Key list.
  • Fill in the Key ID and Team ID from the Apple console.
  • Then, go to Project Settings > Service Accounts and generate a new private key. Copy the code that's provided.
  • Finally, in your Courier account, navigate to Channels > Firebase FCM. Paste the private key code you copied earlier and save it.

push-notifications-flutter-firebase-image6

Step 5 — Managing user state

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.

1
await Courier.shared.signIn(
2
accessToken: accessToken, // You can use Courier Auth Key
3
userId: userId,
4
);
5
6
await Courier.shared.signOut();

Step 6 — Manually syncing FCM tokens

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 pushes
2
final requestedNotificationPermission = await Courier.shared.requestNotificationPermission();
3
print(requestedNotificationPermission);
4
5
final fcmToken = await FirebaseMessaging.instance.getToken();
6
if (fcmToken != null) {
7
await Courier.shared.setFcmToken(token: fcmToken);
8
}
9
10
// Handle FCM token refreshes
11
FirebaseMessaging.instance.onTokenRefresh.listen((fcmToken) {
12
Courier.shared.setFcmToken(token: fcmToken);
13
});

Step 7 — Testing push notifications

Courier allows you to send a push notification to a user ID directly from the SDK.

1
final notificationPermission = await Courier.shared.getNotificationPermissionStatus();
2
print(notificationPermission);
3
4
// Notification permissions need to be 'authorized' on iOS in order to receive pushes
5
final requestedNotificationPermission = await Courier.shared.requestNotificationPermission();
6
print(requestedNotificationPermission);
7
8
// This configures how iOS will display the notification when the app is running in the foreground
9
// If you pass [] it won't present anything
10
// but Courier.shared.onPushNotificationDelivered will still be called
11
Courier.shared.iOSForegroundNotificationPresentationOptions = [
12
iOSNotificationPresentationOption.banner,
13
iOSNotificationPresentationOption.sound,
14
iOSNotificationPresentationOption.list,
15
iOSNotificationPresentationOption.badge,
16
];
17
18
// This will be called if a push notification arrives
19
while the app is running in the foregroundCourier.shared.onPushNotificationDelivered = (push) {
20
...
21
};
22
23
// This will be called if the user clicks on a push notification
24
Courier.shared.onPushNotificationClicked = (push) {
25
...
26
};
27
28
// This will send a test push
29
final messageId = await Courier.shared.sendPush(
30
authKey: 'a_courier_auth_key_that_should_only_be_used_for_testing',
31
userId: 'example_user',
32
title: 'Summer Sale!',
33
body: 'Hundreds of hot summer offers',
34
isProduction: false, // false == sandbox / true == production
35
(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.

push-notifications-flutter-firebase-image7

Step 8 — Sending the notification from the Node.js back end

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.

1
const Courier = require('@trycourier/courier')
2
3
const courier = Courier.CourierClient({ authorizationToken: "AUTH_TOKEN" });
4
5
async function test() {
6
7
const userId = "courier_user"
8
const title = "Hello!"
9
const body = "This message was sent from Node.js"
10
11
const { requestId } = await courier.send({
12
message: {
13
to: {
14
user_id: userId,
15
},
16
content: {
17
title: title,
18
body: body,
19
},
20
routing: {
21
method: "single",
22
channels: ["firebase-fcm"],
23
},
24
},
25
});
26
27
console.log(requestId)
28
}

push-notifications-flutter-firebase-image8

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.

push-notifications-flutter-firebase-image9

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.

push-notifications-flutter-firebase-image10

1
// Install with: npm install @trycourier/courier
2
import { CourierClient } from "@trycourier/courier";
3
4
const courier = CourierClient({ authorizationToken: "AUTH_TOKEN" });
5
6
const { requestId } = await courier.send({
7
message: {
8
to: {
9
firebaseToken: "FIREBASE_TOKEN",
10
},
11
template: "4V0142YBX84G1WN1SK3W4S01QZNC",
12
data: {
13
},
14
},
15
});

Conclusion

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.

Get started sending notifications with Courier in minutes, not days!

We have SDKs in Ruby, Go, Python, Javascript, Node.js, and React.

Sign up

More from Tutorial

How to set up automatic push notifications based on Segment events thumbnail
TUTORIAL

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

Sarah Barber

November 17, 2023

image14
TUTORIAL

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

Martina Caccamo

November 01, 2023

Build your first notification in minutes

Send up to 10,000 notifications every month, for free.

Get started for free

Email & push notification

Build your first notification in minutes

Send up to 10,000 notifications every month, for free.

Get started for free

Email & push notification

Platform

Users

Content

Channels

Sending

Workflows

Preferences

Inbox

Workspaces

Observability

API Status

Changelog

© 2024 Courier. All rights reserved.