javascriptvue.jsauthenticationpush-notificationonesignal

Onesignal login() function creates a seperate user record


I'm trying to use the OneSignal Web SDK to send push notifications and identify users across devices by an external id. When a user is successfully logged in, I call 'Onesignal.login(externalID)' to associate their external id with Onesignal. Instead of associating the current user_id (which is created the moment Onesignal loads) with the external id, Onesignal creates a seperate user record instead. As shown here: Onesignal User Records

So I have two records, one with the id but no push subscription, and another with the valid push:subscribed state but no externalId. Only when I log out and log back in does Onesignal associate the two records as one. This is my code which is called after the user has successfully logged in (I'm using Vue javascript)

    OneSignalDeferred.push(async function (OneSignal) {
          const id = await getUserId()
    
          console.log(id)
          console.log(OneSignal.User.onesignalId)
    
          await OneSignal.login(id).catch((error) => {
            console.error('OneSignal login error: ', error)
          })
        })

I checked that the user_id and OneSignal.User.onesignalId were all properly loaded in and accurate, which they were.

When logging out and then logging back in, the two records are associated correctly after the second login attempt, but not on the first login.

Expected Behavior: The user should be logged in only once, with the externalId correctly associated with the existing push subscription. There should not be multiple user records created in OneSignal.


Solution

  • Make sure OneSignal.login(externalID) is executed before the push subscription is fully registered. Otherwise, OneSignal will crecreate a new user and associate the subscription with that anonymous user.

    Try this:

    OneSignalDeferred.push(async function (OneSignal) {
      await OneSignal.init({
        appId: "YOUR_APP_ID",
        promptOptions: {
          slidedown: {
            enabled: true,
          },
        },
      });
    
      const id = await getUserId();
    
      if (id) {
        console.log("Logging in with ID:", id);
        await OneSignal.login(id).catch((error) => {
          console.error("OneSignal login error: ", error);
        });
      }
    });