Sending Push Notifications from NodeJS backend App to Flutter Android App

Zoran Šaško
Webtips
Published in
6 min readAug 27, 2020

Notifications about new articles, price changes, product offers are expanding interactivity scope of mobile applications.

A notification is a message that pops up on the user’s device. Notifications can be triggered locally by an open application, or they can be “pushed” from the server to the user even when the app is not running. They allow your users to opt-in to timely updates and allow you to effectively re-engage users with customized content.¹

Push notifications are great marketing tools because they help to increase user-to-app interactivity level.

In this article we are going to explore how we can send push notifications from NodeJS backend application to Flutter Android application, using FCM messages. Device tokens will be stored in MySQL database and in the NodeJS, we are going to validate input.

At the bottom of this article, you can see sample applications and feel free to check them out.

Creating NodeJS backend App

In this section, we are going to build NodeJS backend application that will be responsible for storing push device tokens and sending push notifications.

Backend app will have the following dependencies in ‘package.json’:

and by executing:

npm install

we are going to install these dependencies.

Next point is to create ‘App.js’, which will be the starting point of our NodeJS app:

In the ‘App.js’ we can see that we are going to create few routes for handling requests for displaying homepage, sending messages, and storing device token.

It’s also very important to set up ‘.env’ file with appropriate configuration values:

In order to send FCM push notifications from our NodeJS app, we need to make new Firebase Project and generate ‘serverKey’:

1. Create a new Firebase Project (via https://console.firebase.google.com/).

2. Click on ‘Project Overview > Project Settings’ page.

3. In the ‘Settings’ page, click on ‘Cloud Messaging’ tab. Copy ‘Server key’ value and paste it as a value of ‘FCM_SERVER_KEY’ key, inside of ‘.env’ file.

The next step in creating our NodeJS backend app is to create data models.

npx sequelize init

By executing the command from above, we have initialized folder where model files will be stored and initial database configuration. The next step is to adjust the database configuration.

The first step in the configuration of the way how data will be stored and retrieved, using ‘sequelize’ library is to specify ‘.sequelizerc’ file with the following content:

The above lines ensures that MySQL configuration is fetched from ‘config/config.js’ file with the following content:

So, in ‘config.js’ we have specified that we are going to use MySQL database with connection data loaded from ‘.env’ file.

The last step of database configuration is to replace the following line from ‘models/index.js’:

const config = require(__dirname + "/../config/config.json")[env];

to:

const config = require(__dirname + "/../config/config")[env];

By now we have successfully implemented all the configuration steps from above and we are confident to invoke a command that will generate data model ‘PushDevice’ with appropriate attributes.

npx sequelize-cli model:generate --name PushDevice --attributes uuid:string,token:String,platform:enum:'{android,ios}'

in ‘models/pushdevice.js’ and appropriate migration in ‘migrations’ folder.

We need to migrate our ‘PushDevice’ into MySQL database, by execute the following command:

npx sequelize db:migrate

Very nice, so far we have made models and we have prepared everything for storing ‘PushDevice’ data in MySQL database.

Next step is to create our main layout (in ‘views/index.ejs’):

In order to send a message, we are going to use JQuery POST method, which will be created in a separate JS file (stored in ‘public/js/index.js’ file):

In the script above we can see that in ‘sendMessage’ method we are creating POST request to NodeJS backend URL for handling of send push notification messages.

In the next step we are going to create ‘routes/index.js’ file with methods that will handle different route options:

Method ‘sendMessage’ checks if ‘message’ parameter is valid, fetches android devices token and sending ‘gcm.Message’ message via ‘gcm.Sender’ object.

In ‘sendToken’ method we are validating if all parameters are valid and created a new ‘PushDevice’ object in MySQL database.

Very nice!

We have implemented NodeJS Push notification server and we can start the NodeJS app by executing:

nodemon App.js

In the next step, we are going to create a Flutter Android app.

Creating Flutter Android App

In this step, we are going to create a Flutter Android application that will be able to receive push notifications. In order to our app to be able to receive push notification, we need to make a Firebase App setup:

1. In project level ‘build.gradle’ add the following dependencies:

classpath 'com.android.tools.build:gradle:3.5.3'
classpath 'com.google.gms:google-services:4.3.2'

2. In app-level ‘build.gradle’ add the following dependency to the bottom of file:

apply plugin: 'com.google.gms.google-services'

3. In app-level ‘build.gradle’ make sure that ‘applicationId’ is set to the same package name that we have specified in Firebase Android setup process.

applicationId "com.zsasko.flutterpushsample"

We need to configure Firebase for Android in order to get push notifications in our Flutter Android app.

4. In Firebase console click on ‘Project Overview > Project Settings’ and on the bottom of ‘General’ tab, you can find ‘Your Apps’ section. In this section click on ‘Android’ icon in order to start wizard for adding Firebase into Flutter Android project.

5. In the ‘Add Firebase to Android app’ dialog, put the package name that will be used in the Flutter app and proceed with wizard.

6. In the next step, click ‘Download google-services.json’ and put his file in ‘app’ folder:

4. We are going to create custom ‘Application’ class with the following content:

and assign it to ‘android:name’ property of ‘application’ manifest tag:

<application
android:label="push_notification_flutter_sample"
android:name=".Application"
android:icon="@mipmap/ic_launcher">

5. In manifest, inside of ‘MainActivity’ add the following intent filter:

<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>

6. In ‘dependencies’ section of app ‘build.gradle’ add the following dependencies:

implementation 'com.google.firebase:firebase-messaging:20.2.4'
implementation 'com.google.firebase:firebase-analytics:17.5.0'

Very nice, so far we have specified all the required initial setup required for receiving push notifications in Flutter Android apps.

Dependencies that will be used in the Flutter app are the following:

firebase_messaging: ^7.0.0
http: ^0.12.2
intl: ^0.16.1

and by executing the following command, we are going to install these dependencies:

flutter pub get

The next step is to create Flutter Android app layout and appropriate methods for subscribing and handling push notification response.

Method ‘sendTokenToServer’ sends push device token to our NodeJS backend application so when the user sends a message from the backend app, it will be sent to our exact device.

Object ‘_firebaseMessaging’ is responsible for receiving push notifications.

Class ‘MessageItem’ (stored in ‘model/message_item.dart’) will be used for generating list view items:

Data model for parsing notification data (file named ‘model/notification_data.dart’):

Folder ‘test’ we can delete since we don’t need to make any Unit tests.

DEVELOPER TIP: If you want to access NodeJS backend that’s running on ‘localhost’ from your physical device, you can download an app called ‘ngrok’.

Start the app by executing the following command:

ngrok http 5000

which will create ‘Forwarding’ URL that we can reuse in ‘sendTokenToServer’ method and we’ll be able to use our physical device instead of emulator for receiving push messages.

We can now start our Flutter Android app in an emulator/physical device and send push notification from the NodeJS app.

Congratulations!

You have implemented NodeJS backend app for sending push notifications and simple Flutter Android app for receiving push notifications :)

Source code of sample applications created in this article:

[1]: “Introduction to Push Notifications”, Google Developers, https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications. Accessed 26 Aug. 2020.

--

--