<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Kleekit</title>
    <description>The latest articles on DEV Community by Kleekit (@kleekit).</description>
    <link>https://dev.to/kleekit</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F940998%2Fe61fe7b7-f560-4ea7-950d-38ba3af0a922.jpg</url>
      <title>DEV Community: Kleekit</title>
      <link>https://dev.to/kleekit</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/kleekit"/>
    <language>en</language>
    <item>
      <title>Remote Work — This is The Future! Right?</title>
      <dc:creator>Kleekit</dc:creator>
      <pubDate>Tue, 10 Oct 2023 19:29:58 +0000</pubDate>
      <link>https://dev.to/kleekit/remote-work-this-is-the-future-right-30bk</link>
      <guid>https://dev.to/kleekit/remote-work-this-is-the-future-right-30bk</guid>
      <description>&lt;p&gt;Remote work… What comes to your mind when you hear that word? For most people the first thought they have about working remotely is usually tech related. Most people imagine developers or designers working on a tech product from the comfort of their homes. Working remotely is however broader than its application in the tech industry.&lt;/p&gt;

&lt;p&gt;This article will not try to define remote work nor will it list various remote opportunities. This article will only try to provide a broad view of remote work as well as the challenges one might anticipate as a remote staff within the tech ecosystem.&lt;/p&gt;

&lt;p&gt;In the peak of the COVID-19 pandemic in 2020, a lot of institutions and businesses collapsed. Most people lost their Jobs and those running their businesses ran out of a source of livelihood for a while during the lockdown. During this same period however, a lot of tech companies had a huge break-through. Some were doing crazy numbers in sales, others were launching a new product and some others were venturing into previously untapped markets — and they seem to be doing it at scale. Aside from the fact that the Coronavirus exposed deficiencies and market gaps in institutions which can be bridged by some tech, it helped to trigger a mindset shift in the way people work professionally. This shift in mindset helped a greater number of people conclude that work outside a professional office can be both possible and productive. This has been a “silent debate” that has gone on for a while.&lt;/p&gt;

&lt;p&gt;People who have experienced the cruel effect of the coronavirus now see their peers in the tech industry “living the dream”. They have continued their work — and have done so from the comfort of their homes, they had better Job security, and most were earning good money when the entire world seem to be collapsing. “Obviously this is the future!” they must have thought. Are they wrong? No! Tech is definitely the future and will continue to undergo massive innovation in every aspect of global human development. In recent times we have had innovations in the Web3 and blockchain space (with major hikes and “all time highs” of most digital assets) — especially just after the lockdown. Also we are in a period some consider to be an “AI Boom”. So they are right! This is the future! Right? Well stick with me a little longer.&lt;/p&gt;

&lt;p&gt;You see, while most people were able to keep their jobs in tech during the lockdown, not many kept it a lot longer afterwards. Most (if not all) major global tech companies drastically laid off their staff — even those that announced massive revenues during the peak of the virus. So if the tech companies are financially profitable and the staff seem to be productive why the layoffs? Are they just being greedy? Were they only delaying the layoffs until after COVID and it all seemed to happen at the same time? Are there some regulations and policies that made it difficult to end most employees’ contracts during the pandemic? Well, I’d like this to be discussed further as I would even love to hear your opinions. But one thing is for sure — these companies would not make a decision that would negatively impact the business. Whatever decision they made was to favor the business in one way or the other — either financially or in terms of productivity. Even if some companies might have made a bad decision out of greed or other negative factors, all these companies would not exactly be making the same decision based on those negative factors.&lt;/p&gt;

&lt;p&gt;One “COVID-19 work culture exposé” was that some companies have more staff than they actually needed. With most people working remotely, It’s easy to now see those that are actually working and those that “hide behind their desk” while other people work. Some roles also became irrelevant, or the realization of their irrelevance became more evident. Take Twitter (now X) as an example. After Elon Musk took over the company, one of his major decisions was laying off thousands of staff. Some people thought it was a rash decision which resulted from the messy acquisition of the company, others thought him merely clueless. But he repeatedly mentioned that the decision was motivated by productivity and cost related reasons. Some people speculated the collapse of the social platform due to these “rash” decisions. This is a speculation that seems to have been dismissed by recent successes of the company though.&lt;/p&gt;

&lt;p&gt;While it is obvious that the majority of companies would want their staff to work onsite, most staff prefer to work remotely (or so they often say). Some companies have opted for a hybrid work culture in order to balance the scale between an onsite work culture which the company prefers and a remote culture which the staff prefer. Here is a question: Do the majority of the staff actually prefer remote work, or that is what they just say? Why would company staff prefer remote work over onsite work? Is remote work truly the future of global work culture? As much as I would love these questions to be broadly discussed, I will also provide some insights here.&lt;/p&gt;

&lt;p&gt;It probably would be insane to think that there is a global association of company staff that decided on choosing remote work over onsite work and thus sent a memo to all of its members to always choose remote work over onsite work whenever they are asked by their employers. Hence just like we previously concluded that most companies deciding to lay off their staff after the lockdown was acting in the interest of the business, we might also want to conclude that most of the staff preferring to work remotely are also acting in the interest of the business. A lot have argued that working remotely affords them a higher measure of work-life balance. They do not exactly have to “bring work home”. They can attend to the needs of the home and as well be productive. Free times they would have ordinarily used for some chit-chat in the office can now be converted into more productive personal or domestic affairs. Others have argued that they tend to be more productive within their comfort zone. Their home being part of their personal space provides them with all the comfort they need to properly deliver on their job requirements. Thus, they do not have to redecorate their office or workstation to look homely or comfortable, they got all the comfort they need in their home. These reasons are all very valid and if they are individually considered, one can quickly conclude that remote work should define the future work culture. But not so fast. Think again, if these claims are true, why would companies still prefer onsite work?&lt;/p&gt;

&lt;p&gt;For one thing, we can claim that these corporations are “groomers”. They always preach about company culture, core values and a lot of those HR related jargon that people hardly pay attention to. So these companies want to keep their employees within their defined image, synchronizing the thoughts and actions of their employees. As a matter of fact, employees of an organization are known to use a similar set of words or jargon which eventually define their personalities. If this was the only reason why corporations would prefer onsite work, we could easily give a verdict vindicating remote work and proposing it to be the work culture of the future. But there is more!&lt;/p&gt;

&lt;p&gt;You see, most companies’ decisions are data driven and when we analyze the data, the odds do not favor remote work in most organizations. Most companies report less productivity with remote work. Why is that so? Productivity is not just a measure of rate of turnover of work. It also measures quality of work, as well as turn-around time. An optimum productivity performance of an employee will depend on the employee’s ability to utilize all available tools and resources — both tangible and intangible in completing an official assignment promptly. So why is there a drop in productivity when some employees work remotely? Let’s consider some possible reasons.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Limited Work Tools&lt;/strong&gt;: Some work tools required to complete some official tasks might not be readily available for all employees at the same time. If they were onsite, these tools could easily be shared amongst staff. But for remote work, extra effort will be put in place to acquire and use these tools when needed. The company cannot afford to provide all staff with all the tools they need for work individually at their homes. So the staff would have to make their own arrangements to use the required tools. This causes some delays sometimes.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Distractions&lt;/strong&gt;: “I thought we already concluded that there are more distractions onsite than when working from home?” you must have thought. Well we did. But that does not mean that there are no distractions at home. While the distractions in the office are mostly limited to visual or auditory distractions from other employees, the distractions at home are rather personal. Personal, but not an emergency. These are matters that would have been ordinarily ignored if they happened while in the office, or it would have been taken care of by someone else or even postponed to the next availability. Because of the personal nature of these distractions, the employee becomes too invested that they either lose their motivation for work or even completely abandon work for the day.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Decentralized Operating Expenses&lt;/strong&gt;: Ordinarily the employer shoulders all operating costs of a business. These operating costs include the cost of petty items such as stationeries, internet cost, power cost, e.t.c. This factor is not always considered because some employers take care of most of these costs while their employees work remotely, and in some cases, these costs are not always significant because it’s part of the basic amenities the employees enjoy irrespective of the employer’s provision. We are however considering this factor because while for some people in advanced regions these expenses are rather insignificant, or would not be hugely impacted whether or not they work from home, these expenses can be very costly for other remote staff in developing or underdeveloped regions. Let us take for example power. Power is a necessity which is made readily available for most people. Provided that the house is connected to a source of power, there is guarantee of constant power supply. The cost of keeping the power supply would not significantly change because someone in the house is working from home and would need to power a few electronic devices. For these people, there is only a little effect from the decentralized operating cost and they would gladly accept to take care of these small costs as an exchange for the cost of commuting to and from work. On the other hand, consider developing regions such as Africa. In order to maintain power, some African home will need to produce their own power source — either through backup generators or some other alternative power source. The cost of running these generators are mostly the responsibility of the employee in question. If the employee is not home or is not doing something really important, they would rather not have these generators running to produce their own power. They would rather save that cost. But now, they have to work and they have to power their device — they have to shoulder the huge operating cost of working from home. Overtime, these costs burdens the employee to the extent that they might want to alter their work schedule to favor when they are more likely to spend less on power or other huge cost factors. This alteration in schedule thus affects productivity as they may be working within undesirable hours of the day.&lt;/p&gt;

&lt;p&gt;Generally for a remote staff to be highly productive, strict discipline is required. This discipline must be self imposed. At home, you do not have a supervisor or manager breathing down your shoulder. You will take that responsibility to hold yourself accountable to deliver on your tasks with the best quality possible. You will also take the responsibility of depriving yourself of the desired “homely comfort” that your house ordinarily provides, possibly shutting yourself out of the entire house, behind closed doors in small rooms or makeshift offices. Not everyone can boast of such discipline, hence we can see why most companies are requesting for staff to return to office so that the company can continue to manage staff productivity in the best way possible.&lt;/p&gt;

&lt;p&gt;In recent times, some staff that prefer to work remotely are having a change of mind — not because of productivity or because of business considerations itself but for personal reasons. The office, despite being a place of business and professional conduct, is also a place of physical and social interactions. The dialog between team members, the silent competition between employees, the petty gossips, those boring training and HR organized events, all form part of an employee’s social development and interpersonal skills. These interactions keep the mind sharp and give you a reason to pull through the entire day on days you don’t feel much of yourself. If you are home, working remotely, all by yourself, you mostly find yourself accompanied by your furniture and your devices, and when your computer goes to sleep after a while of idleness, you stare at the screen and see a reflection of yourself — gloomy, withdrawn, tired, and your furniture wouldn’t even cheer you up!&lt;/p&gt;

</description>
    </item>
    <item>
      <title>Push Notification Using Firebase, Node.js, Flutter/Dart</title>
      <dc:creator>Kleekit</dc:creator>
      <pubDate>Tue, 26 Sep 2023 18:09:51 +0000</pubDate>
      <link>https://dev.to/kleekit/push-notification-using-firebase-nodejs-flutterdart-4be5</link>
      <guid>https://dev.to/kleekit/push-notification-using-firebase-nodejs-flutterdart-4be5</guid>
      <description>&lt;p&gt;If you are a junior developer or this is the first time exploring this concept, you must have asked the question “how can two or more devices communicate remotely in real time?”. If you are a very smart person, you might have thought of some solutions yourself. Your solutions might revolve around the following:&lt;/p&gt;

&lt;p&gt;Use a stream: If you are familiar with the concept of streaming in programming, you might think this will be a solution to your problem. All you need to do is store the data in the database and listen to the presence of such data at the recipient’s device.&lt;br&gt;
Use a web-socket: web sockets are employed in most real time communications such as text, audio and video messaging channels. So, maybe this can be a very reliable option for you.&lt;/p&gt;

&lt;p&gt;You may even come up with some crude technique that may involve doing a periodic query of an API within the app to expose any new data. While all of these are valid and industry standard methods of sharing data in real time, it depends on their individual use case within the application.&lt;/p&gt;

&lt;p&gt;If data can be shared across devices in the above mentioned manner, what then is push notification? Why is it a critical feature in modern applications? How can push notifications be implemented in an application? This article will provide very clear answers to these questions.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What is Push Notification?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Most mobile applications run on either the Android or the iOS operating system. Each of the devices that run on these operating systems have a unique identifier. This identifier is commonly referred to as device token. Each operating system has a service which can remotely communicate with each device running on the operating system. On iOS, the service is the Apple Push Notification service (APNs) while on Android it is the Firebase Cloud Messaging (FCM) service.&lt;/p&gt;

&lt;p&gt;Push notifications are enabled in an application when the application sends data (which will also include the device token of the targeted device) to the push notification service (APNs or FCM). The push notification service will in turn send the data to the specific device to trigger the device to display the notification irrespective of whether the application is actively running on the device or not.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--muWRYmjn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/syq5z7gqxjlgdnndbp0b.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--muWRYmjn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/syq5z7gqxjlgdnndbp0b.PNG" alt="Image description" width="800" height="150"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Note that push notifications can be implemented in other operating systems apart from Android and iOS, but in the context of this article, we will only focus on the use of push notification on Android and iOS.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Why Use Push Notification in Modern Applications?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Push notification has become a very critical feature for most mobile and web applications. Why is this so? Here are some reasons:&lt;/p&gt;

&lt;p&gt;Message Alert: Just like the name implies, push notification notifies or alerts a user of an application of an incoming or already received data.&lt;br&gt;
Marketing: Push notification is used as a marketing tool to inform users of an application of a service offering or some other promotional messages.&lt;br&gt;
User retention: Some users tend to forget about an app they rarely use. Strategic alerts from these apps help the user get back on the app.&lt;br&gt;
Engagement: Social media applications and other “engagement seeking” applications might utilize the power of push notification to help improve the engagement on the application and getting the user invested into the application.&lt;/p&gt;

&lt;p&gt;One of the fascinating things about push notifications is that the targeted user may or may not be a registered user of the application. As long as the application runs on the user’s device and the user has enabled push notification from that app, information can be shared to that device. In addition, an app does not need to be actively opened (or in use) to receive a push notification. This is one of the most powerful reasons for push notification. The various methods of sharing data remotely as highlighted previously would require an active usage of the application for it to be successful. For example, I would not know of having received a chat message from Whatsapp if i do not have whatsapp opened. But with push notification, I can be notified of having received a Whatsapp message (even when the phone is idle), before I proceed to opening Whatsapp to see the contents of the message or engage further with the sender. Thus, push notification can be used in conjunction with other data sharing methods in an application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;How to Implement Push Notification in an Application&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Push notification can be programmatically implemented in an application. The application would need to ping the push notification service to allow the push notification service to ping the targeted device. We are going to look at implementation of push notification both at the backend and at the frontend. Push notification can be implemented only at the frontend without any backend support, but this is not the best practice.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Prerequisite&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before we can fully get started with the programmatically implementing push notification, you need a firebase account setup. If you do not have a firebase account, you can create one &lt;a href="https://firebase.google.com/"&gt;here&lt;/a&gt;. Your firebase account is the same as your google account. So if you have a google account, you are good to go.&lt;/p&gt;

&lt;p&gt;Now that you have a google account, you can proceed to the &lt;a href="https://console.firebase.google.com/u/0/"&gt;firebase console&lt;/a&gt;. On the firebase console, you will need to create a new project or use an existing project (if you already have one).&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--S9gUHKgG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e3itjd6cnxhtaf5zyw5s.PNG" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--S9gUHKgG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e3itjd6cnxhtaf5zyw5s.PNG" alt="Image description" width="800" height="423"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click on &lt;strong&gt;Add Project&lt;/strong&gt; and fill the form to create a new project. Ensure to enter all details accurately. After each form, click on continue until the end where you &lt;strong&gt;create project&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;After your project is created, you can download the service account json file. To do this, go to your firebase console, on your console click &lt;code&gt;your_project_name &amp;gt; project overview settings(icon) &amp;gt; project settings &amp;gt; service accounts &amp;gt; generate new private key &amp;gt; generate key&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Note that you are to download this key and keep it in a secured place. You cannot retrieve this key, if it is misplaced, you will need to generate another key. There is no major implication to generating multiple keys, your app would still work well.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Backend Implementation of Push Notification&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;We will consider the implementation of push notification at the backend using &lt;a href="https://nodejs.org/en"&gt;node.js&lt;/a&gt;. If you are familiar with JavaScript, this would be easy to follow through. We would be needing one major package added to this project:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.npmjs.com/package/firebase-admin"&gt;Firebase admin&lt;/a&gt;: Firebase admin is a firebase core package that helps us handle a lot of firebase services. One of the firebase services we need is the firebase messaging service. Note that we previously highlighted that Firebase Cloud messaging is the push notification service for Android devices, and you might want to ask: “What if I want to send push notification to an iOS device, do I need another package?” — No you do not! The firebase messaging package would help us with both Android and iOS push notification. It will ping the android and iOS push notification services and deliver the notification to the appropriate device. When firebase admin is installed, please configure it in your project. The configuration could look like this:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// in your main.js or app.js file
const admin = require('firebase-admin');
// download your service account credential from firebase
// and add it to a config folder in your project
const serviceAccount = require('../config/serviceAccountKey.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://yourFirebaseProjectName.firebaseio.com',
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By now, I want to assume that you have set up your node.js project and you are ready to integrate push notification. I would not go into the details of other project setup, I would only be focused on the push notification function. Now let’s get properly started with the following steps:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Write a send notification function&lt;/strong&gt;: This function would be asynchronous and would require parameters such as user id, image url (for notification with an image), title, body, resource id. The resource id is the database id of the information you want to send. For example if you are sending a message notification, the resource id would be the message id. The resource id is important because you may need to do some frontend query when the notification is opened. This query can be done using the resource id or some other parameter you use in querying data in your own backend. The body is the longer text to be shown to the user when the notification is expanded. Note that all of these parameters are optional parameters apart from the ‘title’.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//this is your service.js file or some file where you want to handle push notification
const admin = require('firebase-admin');

async sendPushNotification(title, body, userId, imageUrl, resourceId){}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Query the user id to get more user data for the notification&lt;/strong&gt;: We need additional information to be able to send push notification. The data we need is the device token and the badge count. The badge count is not a required parameter. It would only be vital for iOS devices. The badge is used to indicate the number of unread notifications for the user. The token is the device token. This can be gotten from the device itself and saved to the user collection on the database. When we discuss the frontend implementation of push notification, we will talk about how to get the device token. Note that for the purpose of this article the badge and device token is to be stored in the user collection. In some cases these data might need to be stored in its own collection with other information. The choice is completely up to you.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//this is your service.js file or some file where you want to handle push notification
const admin = require('firebase-admin');

async sendPushNotification(title, body, userId, imageUrl, resourceId){
  // the function below is a db call. replace with your respective db query
  const user = await findUserById(userId);

  const token = user.token;
  let badge = user.badge ?? 0; // if user.badge is null badge is assigned a 0 value

  if(token === null || token === undefined){
    throw new Error('this is an invalid token');
  }
  badge++; // increament the badge.
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Prepare the push notification message object&lt;/strong&gt;: If you check the &lt;a href="https://firebase.google.com/docs/reference/admin/node/firebase-admin.messaging.md#message"&gt;firebase messaging official docs&lt;/a&gt;, you will notice that the message object is of type &lt;code&gt;TokenMessage | TopicMessage | ConditionMessage&lt;/code&gt;. and all 3 types are extended from a &lt;code&gt;BaseMessage&lt;/code&gt; type. You can check the firebase official docs to see all the possible parameters of a firebase object. We will prepare a use case for our notification.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//this is your service.js file or some file where you want to handle push notification
const admin = require('firebase-admin');

async sendPushNotification(title, body, userId, imageUrl, resourceId){
  // the function below is a db call. replace with your respective db query
  const user = await findUserById(userId);

  const token = user.token;
  let badge = user.badge ?? 0; // if user.badge is null badge is assigned a 0 value

  if(token === null || token === undefined || token.length &amp;lt; 2){
    throw new Error('this is an invalid token');
  }
  badge++
  const message = {
          notification: {
            title,
            body,
          },
          android: {
            notification: {
              channel_id: 'MESSAGE_CHANNEL',// *
              icon: 'message_icon', // *
              tag: 'message', // *
              image: imageUrl,
            },
          },
          apns: {
            payload: {
              aps: {
                badge,
                sound: 'chime.caf',
              },
            },
          },
          data: {
            click_action: 'FLUTTER_NOTIFICATION_CLICK', // *
            type: 'MESSAGE', // *
            resourceId,
          },
          token,
       };
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note: All the parameters in the code snippet above with “*” can be edited to fit your app. Please read more about each parameter in the firebase docs.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Send the push notification&lt;/strong&gt;: Use the firebase admin package to send the push notification as shown below.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//this is your service.js file or some file where you want to handle push notification
const admin = require('firebase-admin');

async sendPushNotification(title, body, userId, imageUrl, resourceId){
  // the function below is a db call. replace with your respective db query
  const user = await findUserById(userId);

  const token = user.token;
  let badge = user.badge ?? 0; // if user.badge is null badge is assigned a 0 value

  if(token === null || token === undefined || token.length &amp;lt; 2){
    throw new Error('this is an invalid token');
  }
  badge++
  const message = {
          notification: {
            title,
            body,
          },
          android: {
            notification: {
              channel_id: 'MESSAGE_CHANNEL',// *
              icon: 'message_icon', // *
              tag: 'message', // *
              image: imageUrl,
            },
          },
          apns: {
            payload: {
              aps: {
                badge,
                sound: 'chime.caf',
              },
            },
          },
          data: {
            click_action: 'FLUTTER_NOTIFICATION_CLICK', // *
            type: 'MESSAGE', // *
            resourceId,
          },
          token,
       };

    await admin.messaging().send(message);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Final clean up&lt;/strong&gt;: Here you might want to update the badge count in your user collection and do some error handling.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//this is your service.js file or some file where you want to handle push notification
const admin = require('firebase-admin');

async sendPushNotification(title, body, userId, imageUrl, resourceId){
  // the function below is a db call. replace with your respective db query
  const user = await findUserById(userId);

  const token = user.token;
  let badge = user.badge ?? 0; // if user.badge is null badge is assigned a 0 value

  if(token === null || token === undefined || token.length &amp;lt; 2){
    throw new Error('this is an invalid token');
  }
  badge++
  const message = {
          notification: {
            title,
            body,
          },
          android: {
            notification: {
              channel_id: 'MESSAGE_CHANNEL',// *
              icon: 'message_icon', // *
              tag: 'message', // *
              image: imageUrl,
            },
          },
          apns: {
            payload: {
              aps: {
                badge,
                sound: 'chime.caf',
              },
            },
          },
          data: {
            click_action: 'FLUTTER_NOTIFICATION_CLICK', // *
            type: 'MESSAGE', // *
            resourceId,
          },
          token,
       };

    await admin.messaging().send(message);

  // update user badge count.
  // this is a db call. replace this method with your appropraite db update method
  await user.update({badge});
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It is important to use &lt;code&gt;try-catch&lt;/code&gt; within the function body. This will help you to handle errors properly without breaking the server. One error that can be handled is when the device token is invalid. it might be necessary to remove the token from your db storage. This would help you to query the frontend later to collect the accurate device token.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Write another function to reset the badge count&lt;/strong&gt;: After a notification is delivered, the user will click on the notification to view it. On the frontend we need to reset the badge count on the database so that we can have a zero value. This helps us manage viewed notifications. This badge count is mostly relevant for iOS apps.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;async resetBadgeCount(userId){
  // this is a db call, replace with appropriate query to fetch user from db
  const user = await findUserById(userId);

  // this is a db update method. update the badge property of the user to 0
  await user.update({badge: 0});
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These push notification functions we have written for the backend can be called within other service functions across the application, or it can be exposed to an API. If they are exposed to an API, it means that push notifications can be triggered via an API call.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;resetBadgeCount&lt;/code&gt; function can be exposed to an API since it will be called on the frontend when the user clicks a notification. You can set up the API yourself.&lt;/p&gt;

&lt;p&gt;Now that we have completed the backend implementation of the push notification feature, it is now time to focus on the frontend implementation in your app.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Frontend Implementation of Push Notification&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Since our discussion of push notification has been focused on mobile apps, we would need to consider various frontend approaches for push notifications. Either we will be using a native language such as Java or Swift or a hybrid language such as Flutter and React native. In this article, we will only focus on Flutter. If you notice our backend implementation, you will see &lt;code&gt;FLUTTER_NOTIFICATION_CLICK&lt;/code&gt; as one of the values of the push notification message object. This is because we are using Flutter for the front end. Please follow the &lt;a href="https://firebase.google.com/docs/cloud-messaging/flutter/client"&gt;firebase documentation&lt;/a&gt; on setting up your client. It is a very straightforward process.&lt;/p&gt;

&lt;p&gt;So here are the following steps for front end implementation in Flutter:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Install Flutter Packages&lt;/strong&gt;: You will need to install the following packages:&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://pub.dev/packages/firebase_core"&gt;Firebase core&lt;/a&gt;: Before using any firebase you need to have firebase core package in your application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://pub.dev/packages/firebase_messaging"&gt;Firebase Messaging&lt;/a&gt;: This is the main package we need for the push notification feature.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://pub.dev/packages/flutter_local_notifications"&gt;Flutter Local Notification&lt;/a&gt;: This package will help configure the front end to receive push notifications in the desired manner. It works in conjunction with the Firebase messaging package.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://pub.dev/packages/flutter_app_badger/install"&gt;Flutter App Badger&lt;/a&gt;: This package will be used to reset the notification badge for iOS apps.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Add a new firebase app&lt;/strong&gt;: On your firebase account, go to the project settings and add a new app. Select the iOS icon to add an iOS app&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Download info.plist file&lt;/strong&gt;: A GoogleService.info.plist file is automatically generated for you inside your project after creating the iOS app. Download this file. You will need it in your project.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Add info.plist file to project&lt;/strong&gt;: Open the ios folder of the project directory in Xcode. Drag and drop the file you downloaded into the Runner subfolder. When a dialog box appears, make sure the Copy items if needed of the Destination property is checked and Runner is selected in the Add to targets box. Then, click Finish.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Download google services.json file&lt;/strong&gt;: Download the google-services.json file, drag and drop it into &lt;code&gt;your_project_directory &amp;gt; android &amp;gt; app&lt;/code&gt; then, click Next, Then follow the instructions on the page. Ensure to complete each instruction.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create a Flutter Local Notification class and configure local notification: In one of your service files, you can create a class to setup and configure local notification.&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// import all relevant packages here

class LocalNotificationService {
  static final localNotification = FlutterLocalNotificationsPlugin();

  static Future&amp;lt;void&amp;gt; initialize()async{
    // configure android to use the app icon for notification
    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');

    // this function would be used for iOS apps when notification is received
    // it can be configured as needed.
    void onDidReceiveLocalNotification(
        int? id, String? title, String? body, String? payload) async {
      print('the notification arrived ');
    }

    // darwin settings is for iOS and MacOS
    final DarwinInitializationSettings initializationSettingsDarwin =
        DarwinInitializationSettings(
      requestSoundPermission: true,
      requestBadgePermission: true,
      requestAlertPermission: true,
      onDidReceiveLocalNotification: onDidReceiveLocalNotification,
    );

    // android and ios settings are thus embedded together
    final InitializationSettings settings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsDarwin,
    );

    // initialize the plugin with the configured settings.
    await localNotification.initialize(
      settings,
    );

  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Initialize the notification service&lt;/strong&gt;: On the main.dart file, initialize the flutter notification service.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Future&amp;lt;void&amp;gt; main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );

  // this is where the notification service was initialized
  await LocalNotificationService.initialize();

  runApp(MyApp());
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Create a firebase messaging class and configure firebase messaging&lt;/strong&gt;: Firebase messaging will need to be initialized for the various notification events.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// import all necessary packages

// this function was written out of the class intentionally.
// if written in a class, it might cause a null check bug within the app.
Future&amp;lt;void&amp;gt; _backgroundMsgHandler(RemoteMessage? message) async {
  // you can specify how you want to handle bugs in your app when messages...
  // are received and the app is in background mode.
}

class FirebaseMessagingService {
  static final firebaseInstance = FirebaseMessaging.instance;

  static Future&amp;lt;void&amp;gt; init() async {
    /**
     * When the app is completely closed (not in the background)
     * and opened directly from the push notification
     */
    FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? event) {
      // specify how you want to handle the notification
    });

    //Background
    FirebaseMessaging.onBackgroundMessage(_backgroundMsgHandler);

    /**
     * When the app is open and it receives a push notification
     */
    FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
      // specify how you want to handle the notification
    });

    /**
     * When the app is in the background and is opened directly
     * from the push notification.
     */
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      // specify how you want to handle the notification
    });

  }

  // this function handles app permissions 
  Future&amp;lt;void&amp;gt; grantAppPermission() async {
    NotificationSettings settings = await firebaseInstance.requestPermission(
      alert: true,
      announcement: true,
      badge: true,
      provisional: false,
      sound: true,
    );

    // handle final permission settings from user as appropriate
    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      print('User granted permission');
    } else if (settings.authorizationStatus ==
        AuthorizationStatus.provisional) {
      print('User granted provisional permission');
    } else {
      print('User declined or has not accepted permission');
    }

  }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For each message event, you might want to handle the messages differently. Some messages might need a redirection action, some might require a form of pop up dialog. Whatever your app preference, you can achieve it within your app.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Initialize the firebase messaging on the home page&lt;/strong&gt;: On the entry point of your application, initialize firebase messaging.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() =&amp;gt; _HomeState();
}

class _HomeState extends State&amp;lt;Home&amp;gt; {
  Future&amp;lt;void&amp;gt; initFM() async {
    await FirebaseMessagingService.grantAppPermission();
    await FirebaseMessagingService.init();
  }

  @override
  void initState() {
    initFM();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Update the local notification service&lt;/strong&gt;: The Local Notification Service would need to be updated to add the function to reset badge count for iOS devices.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// import the flutter app badger package
// import http package

class LocalNotificationService {
  ..//all previously written codes 

  static Future&amp;lt;void&amp;gt; resetBadgeCountToZero(Store&amp;lt;AppState&amp;gt; store) async {
     // call the api to reset badge count on the db.
      http.get(Uri.parse('backend_url_to_reset_badge'));

    // this updates the UI badge for iOS
    FlutterAppBadger.removeBadge();
  }

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This &lt;code&gt;resetBadgeCountToZero&lt;/code&gt; function can be called in the firebase init method for each of the notification events as needed.&lt;/p&gt;

&lt;p&gt;Push notification is obviously a very interesting feature. The more you work with it, the more comfortable you are implementing it. Note that you can send push notifications directly from your firebase dashboard without interacting with your backend. This is mostly for development and testing purposes. It is also used during app operations to send broadcast notifications to multiple users. This article however focused on the use of a node.js backend because it meets the needs of most developers for their application.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Resources&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The following resources could help you further in setting up push notifications for your app:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://pub.dev/packages/firebase_core"&gt;Firebase core Package&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://pub.dev/packages/firebase_messaging"&gt;Firebase Messaging Package&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://console.firebase.google.com/u/0/"&gt;Firebase console&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://pub.dev/packages/flutter_app_badger"&gt;Flutter App Badger Package&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://pub.dev/packages/flutter_local_notifications"&gt;Flutter Local Notification Package&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://blog.logrocket.com/add-flutter-push-notifications-firebase-cloud-messaging/"&gt;Further reading on a log rocket article&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://twitter.com/Aghantikayone"&gt;Contact me on Twitter&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

</description>
    </item>
  </channel>
</rss>
