Getting duplicate tokens for multiple users while utilizing Firebase messaging

When attempting to acquire a token from firebase, I employ the code snippet provided below:

const messaging = firebase.messaging();

messaging.requestPermission()
  .then(() =>{
    return firebase.messaging().getToken();
  }).then(token => {
     saveTokentoServer(user.uid, token);
  })

However, a recurring issue arises where I am receiving identical tokens for different users. Consequently, I am unable to send targeted messages.

Is there anyone who can provide guidance on obtaining distinct tokens for individual users?

After spending two days searching for solutions, I am perplexed as to why my web application is not generating unique tokens.

Answer №1

Unique identifiers called Firebase Cloud Messaging tokens are used to identify installations of a mobile app on specific devices, rather than individual users. This means that if multiple users access the same app in a single browser profile, they will receive the same token.

I have not personally tested this method, but it may be possible to remove the token (such as when a user signs out), then proceed to request permission and obtain a new token for the subsequent user.

Answer №2

I have a different way to address your issue,

You can utilize topics for receiving notifications,

1.) Sign up for a topic using your registration_token, ensuring each user has a unique topic name like their user id.

https://iid.googleapis.com/iid/v1/<REGISTRATION_TOKEN>/rel/topics/<TOPIC_NAME>

For instance:

https://iid.googleapis.com/iid/v1/nKctODamlM4:CKrh_PC8kIb7O...clJONHoA/rel/topics/movies
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

2.) Broadcast Notification to the specified topic

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
  "to" : "/topics/movies",
  "priority" : "high",
  "notification" : {
    "body" : "This is a message through Firebase Cloud Messaging Topic!",
    "title" : "FCM Message",
  }
}

3.) Eliminate the registration_id from the topic upon logging out

https://iid.googleapis.com/iid/v1:batchRemove
Content-Type:application/json
Authorization:key=API_KEY
{
   "to": "/topics/movies",
   "registration_tokens": ["nKctODamlM4:CKrh_PC8kIb7O..."],
}

Substitute the topic name "movies" with the user's unique identifier such as their user id or email.

Answer №3

An alternative approach to addressing this issue is by introducing a new attribute named userId within the notification data being transmitted. On the recipient side, notifications should only be displayed if the userId matches the FirebaseAuth.user.id or an equivalent condition if a different authentication mechanism is in use.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Differences between angular.isDefined() and obj.hasOwnProperty()

When working with angular.js, how should I handle objects that may or may not have a status? What are the pros and cons of using angular.isDefined() versus item.hasOwnProperty() in this scenario? var checkStatus = function(item){ if(angular.isDefine ...

What is the best way to manage horizontal scrolling using buttons?

I was hoping that when the button is clicked, the scroll would move in the direction of the click while holding down the button. Initially, it worked flawlessly, but suddenly it stopped functioning. export default function initCarousel() { const carous ...

Object Literal vs Object-Oriented Javascript: Comparing the Two

When it comes to using Object-Oriented Programming (OOP) in JavaScript, I often find myself not utilizing it much. For instance, instead of defining a constructor function and setting up prototypes like this: function Person(name){ return this.name = name ...

Creating a Python server for an Angularjs application and capturing user input

Can you offer me some assistance, whether it's just a hint or a useful tip that could improve my current approach? I have created a series of forms using HTML and AngularJS. Each form collects input data from users, which is then stored in a JSON str ...

Tips for showcasing a drop-down menu using Jquery

I am currently utilizing jQuery to showcase a drop-down menu. It is successfully working for a single menu and displaying the appropriate drop-down. However, when I attempt to use more than one menu, it displays all of the drop-down menus simultaneously. I ...

Transform a global JavaScript function into a global Vue.js function, compatible with the Vue Laravel framework

My JavaScript function displays a color border when required and changes the color if anything is inputted. It works fine in plain JavaScript but not in Vue. I need to use this function in Vue, on any place or component. app.js $('.req' ).on(&a ...

Shuffle letters in a word when hovered over, then unscramble them back to their original order

I have noticed a fascinating effect on several websites. To give you an idea, here are two websites that showcase this effect: Locomotive and TUX. Locomotive is particularly interesting to look at as the desired effect can be seen immediately when hovering ...

What is preventing the click event on this dynamically generated checkbox using jQuery?

Check out the jsFiddle Currently, I am utilizing a jQuery plugin that enables users to draw boxes within a designated area. Using jQuery, I have incorporated a checkbox (alongside a dropdown list) into the box that appears when the user releases the mouse ...

Encountering a hydration issue in Next.js when attempting to refresh the page after switching languages (excluding English) with next-translate/useTranslation

I've encountered an issue with the useTranslation hook from the next-translate package in my Next.js project. Although all languages are being recognized, I'm facing a hydration error whenever I change the language and refresh the page. Below is ...

I am looking to create a PHP script that restricts access to individuals under the age of 18 based on the current

I'm looking for a way to use Php, javascript, or ajax to restrict access for individuals under 18 years old based on the current date. Any suggestions on how I can achieve this? Could someone please review my code for calculating age onblur or onSubm ...

I am having trouble getting text to display properly in a jQuery Mobile dialog

I am attempting to dynamically set the header and button texts using JavaScript, but unfortunately it's not working as expected. To demonstrate the issue, I have added my code on jsfiddle: http://jsfiddle.net/tMKD3/8/. Here is the HTML code: <bod ...

Show picture during the process of loading an external webpage

Utilizing a script to load an external page (external meaning a page within my website) inside a div. Loading the page takes time, so I want to display an image until the page is fully loaded. JAVASCRIPT function HideLoader() { $('#loader' ...

Tips for displaying or concealing data in table cells in Google Charts

Using a Google charts table to display server exceptions, but the errors are too long for cells. How can I show only an excerpt of error messages in each cell with a + expansion sign for full details in a modal box on click? I have successfully implement ...

Encountered an issue with reading null properties when trying to access 'defaultPrevented' in bootstrap 5 toast

Implementing a custom hook to display and hide toast messages is working perfectly fine when invoking showToast in the button component of the Toast, but encountering an error when using this hook outside, for example in the button component of the App. Ty ...

Selecting default values from the Vuex store in Vue-Multiselect

Picture a Vuejs-Application equipped with Vuex. I am aiming to incorporate a mulitselect-dropdown. Here's a basic example inside the Vue-component: <template> <div> <multiselect v-model="values" :options="options"> ...

Issues with sending data using ajax

Trying to get weinre working through Ajax by calling this on dom ready: $.ajax({ url: 'http://debug.build.phonegap.com/target/target-script-min.js#hutber', dataType: "script", crossDomain: true, error: function(data){ c( ...

Is it possible for me to create a nested component without having to make a new file

What I desire: Home.vue <template> <div> <p>{{message}}</p> <ChildComponent/> </div> </template> <script setup> import { ref, defineComponent } from 'vue'; let message = r ...

What is the best way to transform this PHP Object into an array?

I am working with a Javascript array that needs to be passed to a PHP script using Ajax. Inside file.js: var params = {}; params["apples"] = "five"; params["oranges"] = "six"; params["pears"] = "nine"; var ajaxData = {data : params}; fetchData(ajaxData); ...

Having issues with opening an exported Excel file using ExcelJS

While working on my JS project, I utilized the ExcelJS library. Everything was functioning smoothly with English characters. However, when I switched the language of my application to French and attempted to export the content as an Excel sheet, I encounte ...

PHP captures the checkbox value through the $_POST method, whereas jQuery removes the checked class from it

I currently have a form with 2 checkboxes: Registered and Not Registered. If the Registered checkbox is ticked, then 2 additional options should appear: Active and Not Active. If the Registered checkbox is unticked, both the Active and Not Active options ...