<?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: yash nerkar</title>
    <description>The latest articles on DEV Community by yash nerkar (@madmax).</description>
    <link>https://dev.to/madmax</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%2F723736%2F63e339e1-d8cc-45a9-b62b-3219a3c8f248.jpeg</url>
      <title>DEV Community: yash nerkar</title>
      <link>https://dev.to/madmax</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/madmax"/>
    <language>en</language>
    <item>
      <title>Web-Based Notifications with Firebase: A Comprehensive Guide</title>
      <dc:creator>yash nerkar</dc:creator>
      <pubDate>Sat, 03 Feb 2024 06:55:56 +0000</pubDate>
      <link>https://dev.to/madmax/web-based-notifications-with-firebase-a-comprehensive-guide-35pf</link>
      <guid>https://dev.to/madmax/web-based-notifications-with-firebase-a-comprehensive-guide-35pf</guid>
      <description>&lt;p&gt;In the era of web development, user engagement plays a crucial role. One effective way to enhance user experience in web-apps is through web-based notifications. Firebase, a mobile and web application development platform, provides a robust solution for implementing push notifications seamlessly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Overview&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Web-based notifications use the capabilities of service workers to deliver real-time updates to users, even when the application is not open. Firebase Cloud Messaging (FCM) is the go-to service for implementing push notifications.&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;Before implementation, make sure you have the following prerequisites:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Firebase Account: Create a Firebase account if you don’t have one already. Set up a new project in the Firebase Console.&lt;/li&gt;
&lt;li&gt;Node.js and npm: Ensure Node.js and npm are installed on your development machine.&lt;/li&gt;
&lt;li&gt;React App: Set up a React application using Create React App or any other preferred method.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Server-Side (Node.js)&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;1. Install Firebase Admin SDK&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;To enable server-side communication with FCM, you need to install the Firebase Admin SDK. Run the following command in your server-side project:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install firebase-admin&lt;/code&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;2. Initialize Firebase Admin&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;In your server-side code (e.g., &lt;code&gt;server.js&lt;/code&gt;), initialize Firebase Admin using your Firebase project credentials:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const admin = require('firebase-admin');

const serviceAccount = require('path/to/your/firebase-credentials.json');

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;3. Create a Function for Sending Notifications&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Now, create a function that sends notifications to the FCM token:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export async function sendPushNotification(deviceToken: string, title: string, body: string, data: { url: string }) {
  return new Promise((resolve, reject) =&amp;gt; {
    try {
      const message: admin.messaging.Message = {
        notification: {
          title: title,
          body: body,
        },
        token: deviceToken,
        data
      };

      admin.messaging().send(message)
        .then((response: any) =&amp;gt; {
          console.log("response send to", response);
          return resolve('Push notification sent');
        })
        .catch((error: any) =&amp;gt; {
          console.log("error from index push", error);
          return reject('Error sending push notification');
        });
    } catch (error) {
      console.error("error from index push catch", error);
      throw error;
    }
  })
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Client-Side (React)&lt;/strong&gt;
&lt;/h2&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;1. Set Up Firebase in React&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Install the Firebase package in your React project&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install firebase&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Initialize Firebase in your &lt;code&gt;firebase.js&lt;/code&gt; file or other appropriate file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { initializeApp } from "firebase/app";
import {
  FIREBASE_APP_ID,
  FIREBASE_MEASUREMENT_ID,
  FIREBASE_PROJECT_ID,
  FIREBASE_STORAGE_BUCKET,
  FIREBASE_MESSAGING_SENDER_ID,
  FIREBASE_AUTH_DOMAIN,
  FIREBASE_API_KEY,
} from "../config/environment";

// Your web app's Firebase configuration

export const firebaseConfig = {
  apiKey: FIREBASE_API_KEY,
  authDomain: FIREBASE_AUTH_DOMAIN,
  projectId: FIREBASE_PROJECT_ID,
  storageBucket: FIREBASE_STORAGE_BUCKET,
  messagingSenderId: FIREBASE_MESSAGING_SENDER_ID,
  appId: FIREBASE_APP_ID,
  measurementId: FIREBASE_MEASUREMENT_ID,
};

export const app = initializeApp(firebaseConfig);

// by exporting you can use your app anywhere in the react app..
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;2. Request Notification Permission&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;Request permission from the user to receive notifications:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const requestPermission = async () =&amp;gt; {
    const permission = await Notification.requestPermission();
    if (permission === "granted") {
      console.log("Notification permission granted.");
    } else if (permission === "denied") {
      console.log("Permission denied.");
    }
  };

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

&lt;/div&gt;



&lt;p&gt;To Get Device Token :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { getMessaging, getToken } from "firebase/messaging";
import { app } from "../../../src/utils/firebase/firebase";
import { VAPID_KEY } from "../../../src/utils/config/environment";

const [deviceToken, setDeviceToken] = React.useState("");

React.useEffect(() =&amp;gt; {
    if (
      "Notification" in window &amp;amp;&amp;amp;
      "serviceWorker" in navigator &amp;amp;&amp;amp;
      "PushManager" in window
    ) {
      requestPermission();
      const messaging = getMessaging(app);
      const getFCMToken = async () =&amp;gt; {
        try {
          const token = await getToken(messaging, {
            vapidKey: VAPID_KEY,
          });
          if (token) {
            console.log("token", token);
            setDeviceToken(token);
          } else {
            console.log("No FCM token received.");
          }
        } catch (error) {
          console.error("Error getting FCM token:", error);
        }
      };
      getFCMToken();
    } else {
      console.log("FCM not supported");
    }
  }, []);

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

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;getMessaging :&lt;/strong&gt; The &lt;code&gt;getMessaging&lt;/code&gt; sets up FCM and returns an object for managing notifications, subscriptions, incoming messages, and device tokens.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;getToken :&lt;/strong&gt; The &lt;code&gt;getToken&lt;/code&gt; method is used to retrieve the Firebase Cloud Messaging (FCM) token assigned to the current user.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;VAPID_KEY :&lt;/strong&gt; To retrive vapid_key :
&lt;/li&gt;
&lt;li&gt;Go to your Firebase project settings in the Firebase Console.&lt;/li&gt;
&lt;li&gt;Find and click on the &lt;strong&gt;"Cloud Messaging"&lt;/strong&gt; tab.&lt;/li&gt;
&lt;li&gt;Look for &lt;strong&gt;Web Push Certificates&lt;/strong&gt; or &lt;strong&gt;Web Configuration.&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;If a key is present, copy it. Otherwise, generate a new pair using the "Update Pair" or similar action.&lt;/li&gt;
&lt;li&gt;The generated device token send to the backend to store in a database.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;3. Setup Firebase-messaging-service worker&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//firebase-messaging-sw.js
import firebaseConfig from "./firebase";


importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js');

firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();

messaging.onBackgroundMessage((payload) =&amp;gt; {
  console.log(  
    "[firebase-messaging-sw.js] Received background message ",
    payload
  );
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: '/images/myna-logo.jpg',
  };

  self.registration.showNotification(notificationTitle, notificationOptions);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;_Note: This file should be stored in the public folder of your react or next js application, because Service workers are registered using a relative path , adding in public folder, the registration path would be simply&lt;code&gt;./firebase-messaging-sw.js.&lt;/code&gt;&lt;br&gt;
_&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;4. To Register firebase messaging service worker&lt;/strong&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;React.useEffect(() =&amp;gt; {
    if ("serviceWorker" in navigator) {
      navigator.serviceWorker
        .register("/firebase-messaging-sw.js")
        .then(function (registration) {
          console.log("Registration successful, scope is:", registration.scope);
        })
        .catch(function (err) {
          console.log("Service worker registration failed, error:", err);
        });
    }
  }, []);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After registering the service worker (to check the worker has registered or not, go to the service workers in the application inside the developer console). To test notifications, you can send them either from your server using the FCM token or directly from the Firebase console.&lt;/p&gt;

&lt;p&gt;Navigate to the Firebase Console, click on the &lt;strong&gt;‘Messaging’&lt;/strong&gt; tab on the left side, and then select &lt;strong&gt;‘Create your first campaign’&lt;/strong&gt; to send a push notification, then you have to check on the Firebase Notification Message, so the below window will open up.&lt;/p&gt;

&lt;p&gt;By clicking on &lt;code&gt;send test message&lt;/code&gt; you have to add your FCM token in the pop up and then you can receive notifications in the background mode.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fivuyd2piwii3f1bl4gvu.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fivuyd2piwii3f1bl4gvu.gif" alt="send test notification with firebase console" width="600" height="217"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
    </item>
    <item>
      <title>My GitHub Account got Banned!</title>
      <dc:creator>yash nerkar</dc:creator>
      <pubDate>Tue, 27 Sep 2022 10:14:10 +0000</pubDate>
      <link>https://dev.to/madmax/my-github-account-got-banned-2pak</link>
      <guid>https://dev.to/madmax/my-github-account-got-banned-2pak</guid>
      <description>&lt;p&gt;On September 15th, 2022, my GitHub account got banned. The reason was that I violated GitHub rules.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Behind The Scenes&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Our college had a technical event called “Technitude.” As I am the technical head of CSI(computer society of India)DMCE, I have to organize some technical events. We developed a website and deployed it on Heroku. In the event’s morning, I got word that the deployed site is down due to an internal server error. I had to log in to my GitHub account on my college PC to push the local changes to GitHub again. Unfortunately, even the GitHub site was down. That day, we had to postpone our event. In the evening, my GitHub account got banned without prior notice or any mail. And it was a disaster for me. My repos, projects, contributions, and deployed sites, everything was gone in a flash.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Solutions I tried&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;-There is reinstatement support at GitHub where you can appeal if your account gets hidden or disabled by GitHub.&lt;br&gt;
&lt;a href="https://support.github.com/contact/reinstatement" rel="noopener noreferrer"&gt;&lt;strong&gt;GitHub support.&lt;/strong&gt;&lt;/a&gt; I emailed GitHub and explained the issue in detail. GitHub’s response process is a bit slow as it has plenty of users. It’s saying that you don’t have to spam emails to GitHub as it results only in further delay. But my placements were coming and the account was necessary at that time, So I had sent more than one message. In fact, I was sending an email per day. Don’t repeat this mistake. because even if it's a slow process, it’s totally trustworthy. GitHub truly cares for its customers.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;I searched for GitHub’s official discord server but I didn’t find it, so I asked other open source communities, but most of them didn’t know that even GitHub accounts can be banned.&lt;br&gt;
p.s. (Even I had no idea how my GitHub account got banned).&lt;br&gt;
Someone suggested tweeting by tagging GitHub and communities. I tried that too. &lt;br&gt;
but nothing helps.&lt;br&gt;
[Tweet]!(&lt;a href="https://twitter.com/yashnerkar81/status/1570611519729332226" rel="noopener noreferrer"&gt;https://twitter.com/yashnerkar81/status/1570611519729332226&lt;/a&gt;)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;I also contacted the officials of GitHub on Twitter with zero expectations of getting a reply. And, I got a message from Juan Pa, who is the student program manager at GitHub Education, that he had reached out to the team for a review. And I was relieved by seeing his message.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;As my interviews were coming, I had to create a new account and upload the projects and portfolio which I had backed up on the local. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;GitHub released my account&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;After a week, GitHub finally responded to my first ever mail. &lt;br&gt;
The mail :-&lt;br&gt;
&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fca87voq3kwkck8sabmnp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fca87voq3kwkck8sabmnp.png" alt=" " width="800" height="335"&gt;&lt;/a&gt;&lt;br&gt;
I was shocked because I didn’t make any such comment through my account on GitHub discussions. I believe someone commented from my account from the college PC. I don’t know if the person who did this was doing a prank or if he knew this would be a violation of GitHub policy. But the damage was done. God knows what happened. But I got my account back! The only suggestion I can give is that you have to keep your patience. You have to wait until GitHub does not respond back. The GitHub team will surely get back to you. &lt;br&gt;
Thank you GitHub and the fellows who helped me through this difficult time!&lt;/p&gt;

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