<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Munna Khandakar on Medium]]></title>
        <description><![CDATA[Stories by Munna Khandakar on Medium]]></description>
        <link>https://medium.com/@munnashisad?source=rss-1216effab283------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*gTF-fv6uPBuMu35F</url>
            <title>Stories by Munna Khandakar on Medium</title>
            <link>https://medium.com/@munnashisad?source=rss-1216effab283------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:19:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@munnashisad/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Pointer Event Vs Mouse Event]]></title>
            <link>https://medium.com/@munnashisad/pointer-event-vs-mouse-event-266a8a85a602?source=rss-1216effab283------2</link>
            <guid isPermaLink="false">https://medium.com/p/266a8a85a602</guid>
            <category><![CDATA[events]]></category>
            <category><![CDATA[mouse]]></category>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[interaction]]></category>
            <dc:creator><![CDATA[Munna Khandakar]]></dc:creator>
            <pubDate>Thu, 04 Apr 2024 01:27:51 GMT</pubDate>
            <atom:updated>2024-04-04T01:27:51.602Z</atom:updated>
            <content:encoded><![CDATA[<p>Having a strong understanding of events is essential for frontend engineers. In our day-to-day work, we frequently use event listeners, particularly onclick and ondblclick, to create interactive web experiences. But the distinction between onclick and ondblclick events can sometimes be confusing, especially when considering pointer events versus mouse events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/0*Vtmc0dZs-SIr_qt5.png" /><figcaption>pointer event vs mouse event</figcaption></figure><p>Mouse events and pointer events are both used to detect user interaction with a computer interface, but they have some key differences:</p><p><strong>Mouse Events:</strong></p><ul><li>Designed specifically for mice</li><li>Limited to single pointer input (one mouse at a time)</li><li>Don’t provide information about the type of pointer (pen, stylus, etc.)</li><li>Less suitable for touchscreens</li><li>Example: onclick, ondblclick, onmousedown</li></ul><p><strong>Pointer Events:</strong></p><ul><li>More general purpose, can handle mouse, touch, pen, and other pointer types</li><li>Can track multiple pointers simultaneously (useful for multi-touch gestures)</li><li>Include additional properties like pointerId (unique identifier for each touch) and pointerType (type of pointer)</li><li>Built on top of mouse events (inherits most properties)</li><li>Example: pointerdown, pointerup, pointermove</li></ul><p>In summary, pointer events offer a more unified and future-proof way to handle user interaction across different devices and input methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=266a8a85a602" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wired: Can (a==1 && a==2 && a==3) ever evaluate to true in JavaScript?]]></title>
            <link>https://medium.com/@munnashisad/wired-can-a-1-a-2-a-3-ever-evaluate-to-true-in-javascript-5b31c7a1893?source=rss-1216effab283------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b31c7a1893</guid>
            <dc:creator><![CDATA[Munna Khandakar]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 05:08:01 GMT</pubDate>
            <atom:updated>2023-09-27T05:08:01.800Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*0MqxmcS-j9JdO-35YkvJGg.png" /></figure><p>Certainly! This code snippet demonstrates a JavaScript quirk known as the “loose equality” (==) operator and how it can be manipulated to produce unexpected results. Let’s break down the code step by step:</p><p>We start by declaring a constant a and initialising it as an object with a property i set to 1:</p><pre>const a = {<br>  i: 1,<br>  toString: function () {<br>    return a.i++;<br>  }<br>};</pre><p>In this object, there’s also a toString method defined. The toString method is automatically called when you try to convert an object to a string, such as when you use it in a string context (e.g., when using it in a comparison or concatenation with a string)</p><pre>if (a == 1 &amp;&amp; a == 2 &amp;&amp; a == 3) {<br>  console.log(&#39;Hello World!&#39;);<br>}</pre><p>Here’s where the interesting part happens. In this if statement, we&#39;re comparing a to 1, 2, and 3 using the loose equality (==) operator. The == operator compares two values after converting them to the same type if they are of different types. In this case, it will call the toString method of a to convert it to a string before comparison.</p><p>Now, let’s understand how the toString method works:</p><pre>toString: function () {<br>  return a.i++;<br>}</pre><p>The toString method does two things: a. It increments the value of a.i by 1 (a.i++). So, a.i starts at 1 and gets incremented each time toString is called. b. It returns the current value of a.i as a string.</p><p>Since the loose equality operator (==) tries to convert both operands to the same type for comparison, JavaScript will call the toString method on a each time it compares a to a number.</p><p>Here’s what happens during the comparison:</p><ul><li>The first comparison a == 1 calls toString and returns the string representation of a.i, which is &quot;1&quot;. So, it&#39;s effectively comparing &quot;1&quot; to 1, which is true (loose equality).</li><li>The second comparison a == 2 again calls toString and returns the string representation of the updated a.i, which is now &quot;2&quot;. So, it&#39;s comparing &quot;2&quot; to 2, which is also true.</li><li>The third comparison a == 3 calls toString one more time, returning &quot;3&quot;, and comparing &quot;3&quot; to 3, which is true.</li></ul><p>Since all three comparisons are true, the code inside the if block gets executed, and &quot;Hello World!&quot; is logged to the console.</p><p>So, this code demonstrates how JavaScript’s loose equality operator, combined with the custom toString method, can be used to make an object appear as if it&#39;s equal to multiple different values. However, it&#39;s important to note that this is a clever trick and not recommended for writing readable or maintainable code, as it can confuse other developers who read your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b31c7a1893" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Payment Processing: A Practical Guide to Implementing a Payment Gateway]]></title>
            <link>https://medium.com/@munnashisad/simplifying-payment-processing-a-practical-guide-to-implementing-a-payment-gateway-d91f97fb156d?source=rss-1216effab283------2</link>
            <guid isPermaLink="false">https://medium.com/p/d91f97fb156d</guid>
            <category><![CDATA[bkash]]></category>
            <category><![CDATA[payment-gateway]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[sslcommerz]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Munna Khandakar]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 05:56:45 GMT</pubDate>
            <atom:updated>2023-07-07T05:56:45.885Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*c7HA6710Y_o9o6azPEbFKA.jpeg" /></figure><p>The payment gateway has become an essential feature for modern applications. Almost every client demands this feature in their apps. But most of the time, we get stuck in implementing an efficient payment gateway in our application. So, we target to show an easy and efficient way to achieve it in this note. Please follow the following steps carefully.</p><h4>Prerequisite</h4><p>Javascript, NodeJS, ReactJs, NextJs, ExpressJs etc…</p><h4>Frontend</h4><p>We are using the NextJs framework for this tutorial. As per the prerequisite, we confirmed that you are well-known and can install NextJs in your system. If still gets any confusion, then visit <a href="https://nextjs.org/docs/getting-started/installation">here</a>.</p><p>Now make some directories like the following inside the <strong>page</strong> directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*qnoX_UH5dhz5aXlVFbu9ow.png" /></figure><p>Here we have just added two new routes. Those are /payment/success/transection_id and /payment/fail/transection_id`<br>which will be responsible for handling the payment&#39;s success and failure respectfully.</p><p>Now inside /payment/success/transection_id/index.tsx add the following codes:</p><pre>import { useRouter } from &quot;next/router&quot;;<br>import React, { useEffect } from &quot;react&quot;;<br><br>const PaymentSuccessPage = () =&gt; {<br>  const router = useRouter();<br>  useEffect(() =&gt; {<br>    // fetch necessary info using the transection_id<br>    console.log(router?.query?.transection_id);<br>  }, [router]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Payment Successful...!&lt;/p&gt;<br>      &lt;p&gt;Payment Id: {router?.query?.transection_id || &quot;---&quot;}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default PaymentSuccessPage;</pre><p>A preview of this page looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G5UH122vsmmSpiAhWN7x5w.png" /></figure><p>and inside /payment/fail/transection_id/index.tsx add the following codes:</p><pre>import { useRouter } from &quot;next/router&quot;;<br>import React, { useEffect } from &quot;react&quot;;<br><br>const PaymentFailPage = () =&gt; {<br>  const router = useRouter();<br>  useEffect(() =&gt; {<br>    // fetch necessary info using the transection_id<br>    console.log(router?.query?.transection_id);<br>  }, [router]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Payment Unsuccessful...!&lt;/p&gt;<br>      &lt;p&gt;Payment Id: {router?.query?.transection_id || &quot;---&quot;}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default PaymentFailPage;</pre><p>A preview of this page looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P6DLpKfhIsXIT8rLh20duQ.png" /></figure><p>Now, we are writing the code from where we want to trigger the payment process. For me, I’ve just used a button and made dummy data in a component named &lt;Payment/&gt;. I have just sent the data using the post request to the server like the following.</p><pre>import React from &quot;react&quot;;<br>import axios from &quot;axios&quot;;<br>import { useRouter } from &quot;next/router&quot;;<br><br>const Payment = () =&gt; {<br>  const router = useRouter();<br>  // used dummy data<br>  // You can generate your own using the form<br>  const formData = {<br>    name: &quot;Mr. Khandakar&quot;,<br>    price: 200,<br>    address: &quot;Mirpur, Dhaka&quot;,<br>  };<br><br>  const onClickHandler = async () =&gt; {<br>    try {<br>      // backend API end-point<br>      const res = await axios.post(&quot;http://localhost:3030/payment&quot;, formData);<br>      // redirect to the payment page<br>      router.push(res?.data?.url);<br>    } catch (error) {<br>      console.log(error);<br>    }<br>  };<br>  return (<br>    &lt;div className=&quot;flex flex-col items-center justify-center  p-10&quot;&gt;<br>      &lt;p&gt;Name:{formData?.name}&lt;/p&gt;<br>      &lt;p&gt;Price:{formData?.price}&lt;/p&gt;<br>      &lt;p&gt;Address:{formData?.address}&lt;/p&gt;<br>      &lt;div<br>        className=&quot; rounded bg-slate-400 px-2 py-1 text-white&quot;<br>        onClick={onClickHandler}<br>      &gt;<br>        Pay<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Payment;</pre><p>The preview of this page looks like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bg1h2W1Fyo7Z-9v-wPnkSw.png" /></figure><h4>Payment Gateway</h4><p>A payment gateway is a merchant service provided by an e-commerce application service provider that authorizes credit card or direct payment processing for e-businesses, online retailers, bricks and clicks, or traditional brick and mortar. <a href="https://en.wikipedia.org/wiki/Payment_gateway">Wikipedia</a></p><p>In this tutorial we are using SSLCOMMERZ Payment Gateway You can create account other stuffs from <a href="https://sslcommerz.com/">here</a>. After creating account in SSLCOMMERZ we need to create an sandbox account from <a href="https://developer.sslcommerz.com/registration/">here</a>. But make sure to provide the valid email address in that form, because you will get a storeId and storePassword in that email. Store that email in a safe place. You will also get an url to login to the sandbox in that email.</p><h4>Backend</h4><p>Now we will use ExpressJs to create api end points and handle other business requirements. Please follow the official <a href="https://expressjs.com/en/starter/installing.html">website</a> to install if you are not familiar with.</p><p>After installing the project, we have just added one routes directory and added one file paymentRoutes.js there. The folder structure looks like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*bNPKACWt2iwdT-jCGL5zdA.png" /></figure><p>Now in index.js file add the following code:</p><pre>// necessary pacakges<br>const express = require(&quot;express&quot;);<br>const app = express();<br>const cors = require(&quot;cors&quot;);<br>const bodyParser = require(&quot;body-parser&quot;);<br>require(&quot;dotenv&quot;).config();<br><br>// middlewares<br>app.use(cors());<br>app.use(bodyParser.urlencoded({ extended: false }));<br>app.use(bodyParser.json());<br>const port = 3030;<br><br>// forwarding the request to the payment routes<br>app.use(&quot;/api/payment&quot;, require(&quot;./routes/paymentRoutes&quot;));<br><br>app.listen(port, () =&gt; {<br>  console.log(`Payment app listening at http://localhost:${port}`);<br>});</pre><p>If are getting error with packages, then install the required packages. Here the code is almost self explanatory. So now we are heading towards the paymentRoutes.js file. Paste the following code there:</p><pre>const router = require(&quot;express&quot;).Router();<br>const SSLCommerzPayment = require(&quot;sslcommerz-lts&quot;);<br><br>// configuration<br>const store_id = &quot;&lt;your_store_id&gt;&quot;;<br>const store_passwd = &quot;&lt;your_store_password&gt;&quot;;<br>const is_live = false; //true for live, false for sandbox<br><br>function generateTransactionId() {<br>  const timestamp = new Date().getTime().toString(); // Get current timestamp<br>  const randomString = Math.random().toString(36).substring(2, 8); // Generate random string<br>  return timestamp + &quot;-&quot; + randomString; // Concatenate timestamp and random string<br>}<br><br>/*<br> *<br> * method: POST<br> * endPoint: http://localhost:3030/api/payment/<br> * Description: this route will accept the request body and prepare the<br> * data for initailize the SSLCommerzPayment.<br> * Can modify the object&#39;s property according the request body<br> * If the initailization is SUCCESS, then it will again make a POST request to the success_url<br> * If the initailization is FAILED, then it will again make a POST request to the success_url<br> *<br> */<br>router.post(&quot;/&quot;, async (req, res) =&gt; {<br>  const tran_id = generateTransactionId();<br>  const data = {<br>    total_amount: req?.body?.price,<br>    currency: &quot;BDT&quot;,<br>    tran_id: tran_id, // use unique tran_id for each api call<br>    success_url: `http://localhost:3030/api/payment/success/${tran_id}`,<br>    fail_url: `http://localhost:3030/api/payment/fail/${tran_id}`,<br>    cancel_url: `http://localhost:3030/api/payment/cancel/${tran_id}`,<br>    ipn_url: `http://localhost:3030/api/payment/ipn/${tran_id}`,<br>    shipping_method: &quot;Courier&quot;,<br>    product_name: &quot;Computer.&quot;,<br>    product_category: &quot;Electronic&quot;,<br>    product_profile: &quot;general&quot;,<br>    cus_name: req?.body?.name,<br>    cus_add1: req?.body?.address,<br>    cus_email: &quot;customer@example.com&quot;,<br>    cus_add1: req?.body?.address,<br>    cus_add2: &quot;Dhaka&quot;,<br>    cus_city: &quot;Dhaka&quot;,<br>    cus_state: &quot;Dhaka&quot;,<br>    cus_postcode: &quot;1000&quot;,<br>    cus_country: &quot;Bangladesh&quot;,<br>    cus_phone: &quot;01711111111&quot;,<br>    cus_fax: &quot;01711111111&quot;,<br>    ship_name: &quot;Customer Name&quot;,<br>    ship_add1: &quot;Dhaka&quot;,<br>    ship_add2: &quot;Dhaka&quot;,<br>    ship_city: &quot;Dhaka&quot;,<br>    ship_state: &quot;Dhaka&quot;,<br>    ship_postcode: 1000,<br>    ship_country: &quot;Bangladesh&quot;,<br>  };<br>  //sslcommerz init<br>  const sslcz = new SSLCommerzPayment(store_id, store_passwd, is_live);<br>  sslcz.init(data).then((apiResponse) =&gt; {<br>    // Redirect the user to payment gateway<br>    console.log(apiResponse);<br>    console.log(&quot;STATUS: &quot;, apiResponse?.status);<br>    let GatewayPageURL = apiResponse.GatewayPageURL;<br>    res.send({ error: false, url: GatewayPageURL, message: &quot;Success&quot; });<br>    console.log(&quot;Redirecting to: &quot;, GatewayPageURL);<br>  });<br>});<br><br>/*<br> *<br> * method: POST<br> * endPoint: http://localhost:3030/api/payment/success/:transectionId<br> * Description: this route will only trigger if the payment is successfull.<br> * so, in this route we can modify DB or handle other bussiness logic.<br> * After that, we will redirect to the success page in the frontend-app(http://localhost:3300)<br> *<br> */<br>router.post(&quot;/success/:transectionId&quot;, async (req, res) =&gt; {<br>  //update DB using transectionId<br>  console.log(&quot;Payment Successfull ID: &quot;, req.params.transectionId);<br>  res.redirect(<br>    `http://localhost:3300/payment/success/${req.params.transectionId}`<br>  );<br>});<br><br>/*<br> *<br> * method: POST<br> * endPoint: http://localhost:3030/api/payment/fail/:transectionId<br> * Description: this route will only trigger if the payment is failed.<br> * so, in this route we can modify DB or handle other bussiness logic.<br> * After that, we will redirect to the fail page in the frontend-app(http://localhost:3300)<br> *<br> */<br>router.post(&quot;/fail/:transectionId&quot;, async (req, res) =&gt; {<br>  //update DB using transectionId<br>  console.log(&quot;Payment Failed ID: &quot;, req.params.transectionId);<br>  res.redirect(<br>    `http://localhost:3300/payment/fail/${req.params.transectionId}`<br>  );<br>});<br><br>module.exports = router;</pre><p>In this way, you can add SSLCOMMERZ Payment Gateway in your Nextjs Expressjs project. A complete video of this project is given below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X06IeyK9hR331dASUUu_1w.gif" /></figure><p>The video here looks a bit slow, but it is not that much i real life. Hope it will be helpful for you. The Github link is given <a href="https://github.com/Munna-Khandakar/SSLCommerzPayment-react-node-">here</a>. You can check and give star. Thanks ❤</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d91f97fb156d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FCM Push Notification in Next.Js App using custom hook]]></title>
            <link>https://medium.com/@munnashisad/fcm-push-notification-in-next-js-app-using-custom-hook-d78494cb9e4f?source=rss-1216effab283------2</link>
            <guid isPermaLink="false">https://medium.com/p/d78494cb9e4f</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[fcm-push-notification]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[nextjs-13]]></category>
            <category><![CDATA[firebasecloudmessaging]]></category>
            <dc:creator><![CDATA[Munna Khandakar]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 10:55:20 GMT</pubDate>
            <atom:updated>2023-06-05T10:55:20.227Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*z4yZG8-fyV20VItjpNHyLw.jpeg" /></figure><p>Push notification is an essential features for almost all apps. In earlier days people don’t love web applications because of some limitations which includes Push Notifications.</p><p>I have read many articles to implement FCM push notifications including the Firebase Docs but failed. Then after some few attempt I discover a way to implement FCM Push Notification in Next App properly. In this article I will share those steps.</p><h3>Prerequisites</h3><p>I believe that the reader already has a basic understanding of the following things:-</p><ul><li>To create apps with the Next.js framework.</li><li>The basic working of push notification</li><li>Setting up a Firebase account, firebase project config and Web configuration key</li><li>Working with the Postman tool</li><li>installation of firebase</li></ul><h3>Ready To Go</h3><p>Push notification can be received both in foreground and background. Foreground means when the you are using the app and background means when you are not using the site but somehow the browser is connected to internet.</p><p>So, to receive the push notification in background we need to add a service worker in the app. for this reason, add a file named firebase-messaging-sw.js in the public folder. paste the following code in that file</p><pre>// eslint-disable-next-line no-undef<br>importScripts(&#39;https://www.gstatic.com/firebasejs/8.8.0/firebase-app.js&#39;);<br>// eslint-disable-next-line no-undef<br>importScripts(&#39;https://www.gstatic.com/firebasejs/8.8.0/firebase-messaging.js&#39;);<br><br>const firebaseConfig = {<br>  apiKey: &#39;your_keys&#39;,<br>  authDomain: &#39;your_keys&#39;,<br>  projectId: &#39;your_keys&#39;,<br>  storageBucket: &#39;your_keys&#39;,<br>  messagingSenderId: &#39;your_keys&#39;,<br>  appId: &#39;your_keys&#39;,<br>  measurementId: &#39;your_keys&#39;,<br>};<br>// eslint-disable-next-line no-undef<br>firebase.initializeApp(firebaseConfig);<br>// eslint-disable-next-line no-undef<br>const messaging = firebase.messaging();<br><br>messaging.onBackgroundMessage((payload) =&gt; {<br>  console.log(<br>    &#39;[firebase-messaging-sw.js] Received background message &#39;,<br>    payload<br>  );<br>  const notificationTitle = payload.notification.title;<br>  const notificationOptions = {<br>    body: payload.notification.body,<br>    icon: &#39;./logo.png&#39;,<br>  };<br>  self.registration.showNotification(notificationTitle, notificationOptions);<br>});</pre><p>here we have disabled the eslint warnings and errors. Now we will build a custom hook which will be responsible to grand notification permission and a token. We will use that token to send the push notification.</p><p>Now we will config our app in a file. We named that file firebase and it is located under utils/firebase/firebase.ts Now add the following code there.</p><pre>// Import the functions you need from the SDKs you need<br>import { initializeApp } from &#39;firebase/app&#39;;<br><br>const firebaseConfig = {<br>  apiKey: &#39;your_keys&#39;,<br>  authDomain: &#39;your_keys&#39;,<br>  projectId: &#39;your_keys&#39;,<br>  storageBucket: &#39;your_keys&#39;,<br>  messagingSenderId: &#39;your_keys&#39;,<br>  appId: &#39;your_keys&#39;,<br>  measurementId: &#39;your_keys&#39;,<br>};<br><br>// Initialize Firebase<br>const firebaseApp = initializeApp(firebaseConfig);<br>export default firebaseApp;</pre><p>Now, lets make out custom hook useFcmToken which will give us the token and request permission status. We place that hook under the utils directory like utils/hooks/useFcmToken.tsx</p><pre>import { useEffect, useState } from &#39;react&#39;;<br>import { getMessaging, getToken } from &#39;firebase/messaging&#39;;<br>import firebaseApp from &#39;../firebase/firebase&#39;;<br><br>const useFcmToken = () =&gt; {<br>  const [token, setToken] = useState(&#39;&#39;);<br>  const [notificationPermissionStatus, setNotificationPermissionStatus] =<br>    useState(&#39;&#39;);<br><br>  useEffect(() =&gt; {<br>    const retrieveToken = async () =&gt; {<br>      try {<br>        if (typeof window !== &#39;undefined&#39; &amp;&amp; &#39;serviceWorker&#39; in navigator) {<br>          const messaging = getMessaging(firebaseApp);<br><br>          // Retrieve the notification permission status<br>          const permission = await Notification.requestPermission();<br>          setNotificationPermissionStatus(permission);<br><br>          // Check if permission is granted before retrieving the token<br>          if (permission === &#39;granted&#39;) {<br>            const currentToken = await getToken(messaging, {<br>              vapidKey:<br>                &#39;your_vapid_key&#39;,<br>            });<br>            if (currentToken) {<br>              setToken(currentToken);<br>            } else {<br>              console.log(<br>                &#39;No registration token available. Request permission to generate one.&#39;<br>              );<br>            }<br>          }<br>        }<br>      } catch (error) {<br>        console.log(&#39;An error occurred while retrieving token:&#39;, error);<br>      }<br>    };<br><br>    retrieveToken();<br>  }, []);<br><br>  return { fcmToken: token, notificationPermissionStatus };<br>};<br><br>export default useFcmToken;</pre><p>Remember that, there are some certain conditions under which the token get be changed. So, if that token is changed then you will not be able to send the push notification and you will get error NotRegistered</p><p>Now, we are ready to go. messaging.onBackgroundMessage will handle the background push notification and now we will see how to handle foreground push notification. Now in our main page, index.tsx write the following code.</p><pre>import React, { useEffect } from &#39;react&#39;;<br>import { getMessaging, onMessage } from &#39;firebase/messaging&#39;;<br>import firebaseApp from &#39;@utills/firebase/firebase&#39;;<br><br>export default function page() {<br>  const { fcmToken,notificationPermissionStatus } = useFcmToken();<br>  // Use the token as needed<br>  fcmToken &amp;&amp; console.log(&#39;FCM token:&#39;, fcmToken);<br><br><br>  // eslint-disable-next-line react-hooks/rules-of-hooks<br>  useEffect(() =&gt; {<br>    if (typeof window !== &#39;undefined&#39; &amp;&amp; &#39;serviceWorker&#39; in navigator) {<br>      const messaging = getMessaging(firebaseApp);<br>      const unsubscribe = onMessage(messaging, (payload) =&gt; {<br>        console.log(&#39;Foreground push notification received:&#39;, payload);<br>        // Handle the received push notification while the app is in the foreground<br>        // You can display a notification or update the UI based on the payload<br>      });<br>      return () =&gt; {<br>        unsubscribe(); // Unsubscribe from the onMessage event<br>      };<br>    }<br>  }, []);<br><br>  return &lt;div&gt; home &lt;/div&gt;;<br>}</pre><p>Now we can send push notification to our app. we can store the tokens in DB or as per your wish. Get your fcmToken and open postman.</p><p>It will be a post request to <a href="https://fcm.googleapis.com/fcm/send">https://fcm.googleapis.com/fcm/send</a></p><h4>Request Headers:</h4><blockquote>“Content-Type”: “application/json”</blockquote><blockquote>“Authorization” : key=your_server_key</blockquote><p>to get your_server_id , go to your project settings from firebase console and click the cloud messaging tab.Then enable Cloud Messaging API (Legacy) Enabling it and getting the key requires a little time. So, wait for it.</p><h4>Body:</h4><pre>{<br>  &quot;to&quot;: &quot;receiver_fcmToken&quot;,<br>  &quot;notification&quot;: {<br>    &quot;title&quot;: &quot;your title&quot;,<br>    &quot;body&quot;: &quot;some message in your body&quot;<br>  }<br>}</pre><p>This is it. If you find any mistake or better version of it, then don’t forget to update me.<br>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d78494cb9e4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>