Search code examples
javascriptnode.jspush-notificationamazon-sns

sending SNS push notifications to multiple devices


I need to send push notifications to multiple devices using aws-sns-javascript when I create createPlatformEndpoint I can just add one device token but I need to send notifications to multiple devices like an array token

Create Platform Application

var params = {
  Attributes: {
    'PlatformCredential': 'My API KEY'
  },
  Name: 'dist-ba-dist',
  Platform: 'GCM'
};
sns.createPlatformApplication(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

Create Platform Endpoint

var params = {
  PlatformApplicationArn:`data.PlatformApplicationArn` , 
  Token: 'My Device Token',
  CustomUserData: 'STRING_VALUE'
};
sns.createPlatformEndpoint(params, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

Sends a message to an Amazon SNS topic

var payload = {
    default: 'Hello World',
    GCM: {
        notification: {
            body: "Sample message",
            title: "Hello World"
        }
    }
};
console.log("endpointArn", data.EndpointArn)
payload.GCM = JSON.stringify(payload.GCM);
payload = JSON.stringify(payload);
console.log('payload', payload)

console.log('sending push');
sns.publish({
    Message: payload,
    MessageStructure: 'json',
    TargetArn: data.EndpointArn,
}, function (err, data) {
    if (err) {
        console.log(err.stack);
        return;
    }

    console.log('push sent');
    console.log(data);
});   


Solution

  • To deliver push notifications to multiple devices you can either

    1. Create a topic, subscribe each endpoint to the topic, and then publish to the topic. SNS will handle delivering the message to each of the topic subscribers. This solution works great if you are broadcasting notifications OR
    2. Create endpoints for each user, store the ARNs for these somewhere, and then do a direct publish to each of the endpoints you wish to deliver the notification to.