Skip to main content

Server SDKs (Back-end)

The server-side SDKs allow you to trigger sending notifications, setting user preferences and more. Supported environments:

  • Node.js official
  • Python official
  • PHP official
  • Laravel official
  • Go official
  • C# official
  • Ruby documented
  • Any environment that supports HTTP calls

If you don't see your language/framework documented here, just ping us on support and we will provide samples and docs.

Setup & Initialization

  1. Install using one of the following package managers:
npm install notificationapi-node-server-sdk
yarn add notificationapi-node-server-sdk
pnpm add notificationapi-node-server-sdk
  1. Import:
import notificationapi from 'notificationapi-node-server-sdk';
// or using require:
// const notificationapi = require('notificationapi-node-server-sdk').default;
  1. Initialize:
notificationapi.init('CLIENT_ID', 'CLIENT_SECRET');
NameTypeDescription
CLIENT_ID*stringYour NotificationAPI account clientId. You can get it from here.
CLIENT_SECRET*stringYour NotificationAPI account client secret. You can get it from here.
optionsobjectAdditional initialization
options.baseUrlstringTo choose a different region than default (US). Use https://api.ca.notificationapi.com to access the Canada region.

* required

send

Used to send a notification to the specified user.

notificationapi.send({
notificationId: 'order_tracking',
user: {
id: 'spongebob.squarepants',
email: 'spongebob@squarepants.com',
number: '+15005550006'
},
mergeTags: {
item: 'Krabby Patty Burger',
address: '124 Conch Street',
orderId: '1234567890'
}
});

Parameters

The send() method accepts an object with the following fields:

NameTypeDescription
notificationId*stringThe ID of the notification you wish to send. You can find this value from the dashboard.
user*objectThe user to send the notification to.
user.id*stringThe ID of the user in your system. Required. This is the only user field required for sending in-app, web push, and mobile push notifications.
user.emailstringRequired for sending email notifications, otherwise optional.
user.numberstringRequired for SMS/CALL notifications, otherwise optional. Valid format: +15005550006. Unformatted US/Canada numbers are also accepted, e.g., (415) 555-1212, 415-555-1212, or 4155551212.
user.timezonestringThe user's timezone. Timezone names correspond to the Zone and Link names of the IANA Time Zone Database, such as 'America/New_York', 'America/Denver', 'EST', and 'UTC'.
mergeTagsobjectUsed to pass in dynamic values into the notification design. Read more: Dynamic Parameters (Merge Tags)
schedulestringAn ISO 8601 datetime string to schedule the notification for. For example, 2024-02-20T14:38:03.509Z
replaceobject, string key/value pairSimilar to mergeTags, but more flexible. Like the programmatic string replace function, this parameter will replace any string in the notification templates with another string. This operation happens on the fly when sending the notification and does not actually modify the templates.
This operation is case-sensitive and happens after mergeTags are injected.
subNotificationIdstringTo break down your notification into multiple categories or groups. Read more: Sub Notifications
templateIdstringBy default, notifications are sent using the default template of each channel. You can permanently change the default template from the dashboard. However, you can also use this parameter to force using a specific template. This is useful in multiple situations:
- Design variation: using different wording and design, e.g. "You have new updates" vs. "You don't have any updates"
- White-labeling: using a specific template that you designed for a white-labeled customer
- Language: creating and using multiple templates for multiple languages
If the provided templateId does not exist for a channel, the default template will be used, and a warning message will be generated.
forceChannels (deprecated)string[]Used to override the channels which are used for the notification. This field only overrides the notification's channels configuration. It does not override the user preferences.
Values available for use are:
EMAIL, INAPP_WEB, SMS, CALL, PUSH, WEB_PUSH
E.g. forceChannels: ["EMAIL", "SMS"]
optionsobjectFor configuring additional options

Options Object

NameTypeDescription
emailobjectEmail options features.
email.replyToAddressesstring[]An array of email addresses to be used in the reply-to field of emails notifications.
email.ccAddressesstring[]An array of emails to be CC'ed on the email notifications.
email.bccAddressesstring[]An array of emails to be BCC'ed on the email notifications.
email.fromNamestringA string to display as the "From" field in an email
email.fromAddressstringAn email address to send the email from
email.attachments{ filename: string; url: string }[]An array of publicly accessible URLs and filenames pointing to files that you wish to include as attachments. The URLs only need to be valid for a few minutes after calling the SDK method. After that, the public URLs can be disabled for privacy. The maximum email size (including the content and all attachments) is 25MB. File extensions in the filename property are necessary for the file to show up nicely in the recipient's device.
apnobjectAdditional Apple push notification
apn.expirynumberThe UNIX timestamp representing when the notification should expire. This does not contribute to the 2048 byte payload size limit. An expiry of 0 indicates that the notification expires immediately.
apn.prioritynumberThe priority of the notification. If you omit this header, APNs sets the notification priority to 10. Specify 10 to send the notification immediately. Specify 5 to send the notification based on power considerations on the user’s device. Specify 1 to prioritize the device’s power considerations over all other factors for delivery, and prevent awakening the device.
apn.collapseIdstringAn identifier you use to merge multiple notifications into a single notification for the user. Typically, each notification request displays a new notification on the user’s device. When sending the same notification more than once, use the same value in this header to merge the requests. The value of this key must not exceed 64 bytes.
apn.threadIdstringProvide this key with a string value that represents the app-specific identifier for grouping notifications. If you provide a Notification Content app extension, you can use this value to group your notifications together. For local notifications, this key corresponds to the threadIdentifier property of the UNNotificationContent object.
apn.badgenumberInclude this key when you want the system to modify the badge of your app icon. If this key is not included in the dictionary, the badge is not changed. To remove the badge, set the value of this key to 0.
apn.soundstringInclude this key when you want the system to play a sound. The value of this key is the name of a sound file in your app’s main bundle or in the Library/Sounds folder of your app’s data container. If the sound file cannot be found, or if you specify default for the value, the system plays the default alert sound. For details about providing sound files for notifications; see here
apn.contentAvailablebooleanInclude this key with a value of 1 to configure a background update notification. When this key is present, the system wakes up your app in the background and delivers the notification to its app delegate. For information about configuring and handling background update notifications, see here
fcmobjectAdditional Firebase Cloud Messaging push notification options
fcm.androidobjectAdditional Android push notification options
fcm.android.collapseKeystringThis parameter identifies a group of messages (e.g., with collapse_key: "Updates Available") that can be collapsed, so that only the last message gets sent when delivery can be resumed. This is intended to avoid sending too many of the same messages when the device comes back online or becomes active. Note that there is no guarantee of the order in which messages get sent. Note: A maximum of 4 different collapse keys is allowed at any given time. This means a FCM connection server can simultaneously store 4 different send-to-sync messages per client app. If you exceed this number, there is no guarantee which 4 collapse keys the FCM connection server will keep.
fcm.android.prioritystringSets the priority of the message. Valid values are "normal" and "high." On iOS, these correspond to APNs priorities 5 and 10. By default, notification messages are sent with high priority, and data messages are sent with normal priority. Normal priority optimizes the client app's battery consumption and should be used unless immediate delivery is required. For messages with normal priority, the app may receive the message with unspecified delay. When a message is sent with high priority, it is sent immediately, and the app can wake a sleeping device and open a network connection to your server.
fcm.android.ttlstringThis parameter specifies how long (in seconds) the message should be kept in FCM storage if the device is offline. The maximum time to live supported is 4 weeks, and the default value is 4 weeks. For more information, see Setting the lifespan of a message

Size Limitation

When using parameters (merge tags) in the body of your notifications, it is recommended that the size of the combined parameters not exceed 80 KB. Exceeding this limit may result in delivery failure, or an API error.

identifyUser

Stores the end-user information for a given user.

By using this function, you can omit the contact information when using send(). NotificationAPI will automatically lookup the user's stored email or phone number and use it for sending the notification.

notificationapi.identifyUser({
id: 'spongebob.squarepants',
email: 'spongebob@squarepants.com',
number: '+15005550006',
pushTokens: [
{
type: PushProviders.FCM,
token: 'samplePushToken',
device: {
app_id: 'com.example.app',
ad_id: '1234567890',
device_id: '1234567890',
platform: 'android',
manufacturer: 'Samsung',
model: 'SM-G930F'
}
}
],
webPushTokens: [
{
sub: {
endpoint:
'https://fcm.googleapis.com/fcm/send/fCs_4iba0Ao:APA91bGFdaU7I3****JMH_KeZwk1Xi',
keys: {
p256dh:
'zP2xFu3hMc2vNH5E2nuKkyjpZydvCk9llRUY2kP4****9aSlKcoadSV2UbvMRQ',
auth: 'CXEFun************tYe8g'
}
}
}
]
});

Parameters

NameTypeDescription
id*stringThe ID of the user in your system. Required.
emailstringRequired for sending email notifications, otherwise optional.
numberstringRequired for SMS/CALL notifications, otherwise optional. Valid format: +15005550006. Unformatted US/Canada numbers are also accepted, e.g., (415) 555-1212, 415-555-1212, or 4155551212.
timezonestringThe user's timezone. Timezone names correspond to the Zone and Link names of the IANA Time Zone Database, such as 'America/New_York', 'America/Denver', 'EST', and 'UTC'.
pushTokensobject[]Tokens which are required to send mobile push notifications, a user can have multiple devices and a push token is required for each device.
webPushTokensobject[]Tokens which are required to send web push notification, a user can have multiple devices and a web push token is required for each device.

pushTokens object

NameTypeDescription
type*string[apn,fcm] The provider token is to be associated with. Required.
token*stringThe full token string. Required.
device*objectInformation about the device the token is associated with. Required.
device object
NameTypeDescription
app_idstringId of the application the token is used for.
ad_idstringId of the advertising identifier.
device*stringId of the device the token is associated with. Required.
platformstringThe device platform i.e. android, ios.
manufacturerstringThe device manufacturer.
modelstringThe device model .

webPushTokens object

NameTypeDescription
sub*objectWeb push subscription. Required.
Web push subscription (sub) object
NameTypeDescription
endpoint*stringThe string value containing the endpoint associated with the push subscription. Required.
keys*objectThe keys associated with the push subscription. Required.
Web push subscription keys object
NameTypeDescription
p256dh*stringAn Elliptic curve Diffie–Hellman public key on the P-256 curve (that is, the NIST secp256r1 elliptic curve). The resulting key is an uncompressed point in ANSI X9.62 format. Required.
auth*stringAn authentication secret, as described in Message Encryption for Web Push. Required.

setUserPreferences

Used to set a user's notification preferences. This function will override the user's existing preferences.

notificationapi.setUserPreferences('userId', [
{
notificationId: 'new_order',
channel: 'INAPP_WEB',
delivery: 'weekly'
},
{
notificationId: 'order_tracking',
channel: 'SMS',
delivery: 'weekly'
}
]);

Parameters

NameTypeDescription
userId*stringThe ID of the user in your system. Required.
preferences*object[]An array of preference objects.

Preference Object

NameTypeDescription
notificationId*stringThe ID of the notification you wish to send. You can find this value from the dashboard.
channelstringThe channel you wish to set the preference for. Accepted values:
EMAIL, INAPP_WEB, SMS, CALL, PUSH, WEB_PUSH
deliverystringThe method for delivering the notification. Accepted values:
off, instant, hourly, daily, weekly, monthly

deleteUserPreferences

Used to delete any stored preferences for a user and notificationId or subNotificationId.

notificationapi.deleteUserPreferences(
'spongebob.squarepants',
'order_tracking'
);

Parameters

NameTypeDescription
userId*stringThe ID of the user in your system. Required.
notificationId*stringThe ID of the notification in NotificationAPI. Required.
subNotificationIdstringThe subNotificationId is used to specify further subcategories within a notification.

updateInAppNotification

Used to update the opened, archived, ... of an inapp notification.

notificationapi.deleteUserPreferences('spongebob.squarepants', {
trackingIds: ['sampleTrackingId'],
opened: '1970-01-01T00:00:00.000Z',
clicked: '1970-01-01T00:00:00.000Z',
archived: '1970-01-01T00:00:00.000Z',
actioned1: '1970-01-01T00:00:00.000Z',
actioned2: '1970-01-01T00:00:00.000Z',
reply: { date: '1970-01-01T00:00:00.000Z', message: 'nice!' }
});

Parameters

NameTypeDescription
userId*stringThe ID of the user in your system. Required.
params*stringThe inapp notification data you want to update. Required.

params

NameTypeDescription
trackingIds*string[]The Tracking IDs of the notifications you want to update. Required.
openedstringA string representing the time when the notification was opened. Optional.
clickedstringA string representing the time when the notification was clicked. Optional.
archivedstringA string representing the time when the notification was archived. Optional.
actioned1stringA string representing the time when the first action associated with the notification was taken. Optional.
actioned2stringA string representing the time when the second action associated with the notification was taken. Optional.
reply.datestringA string representing the time of the reply to the notification. Optional.
reply.messagestringA string representing the content of the reply message. Optional.

retract

Only applicable to in-app notifications. This function helps you delete all notifications of a certain type for a user.

notificationapi.retract({
notificationId: 'order_tracking',
userId: 'spongebob.squarepants'
});
NameTypeDescription
notificationId*stringThe ID of the notification you wish to retract. You can find this value from the dashboard.
userId*stringThe ID of the user in your system. Required.
secondaryIdstringFor when you want to delete a specific subNotificationId.

updateSchedule

This function enables you to update a scheduled notification by providing a trackingId.

notificationapi.updateSchedule('172cf2f4-18cd-4f1f-b2ac-e50c7d71891c', {
schedule: '2024-02-20T14:38:03.509Z'
});
NameTypeDescription
trackingId*stringThe tracking ID of the scheduled notification you wish to update. You can find this value from the dashboard.

deleteSchedule

This function allows you to delete a scheduled notification by providing a trackingId.

notificationapi.deleteSchedule('172cf2f4-18cd-4f1f-b2ac-e50c7d71891c');
NameTypeDescription
trackingId*stringThe tracking ID of the scheduled notification you wish to delete. You can find this value from the dashboard.

queryLogs

This function allows you to run queries on the logs of your send requests.

notificationapi.queryLogs({
dateRangeFilter: {
startTime: 1719600830559;
endTime: 1719600840559;
},
notificationFilter: ['order_tracking'],
channelFilter: ['EMAIL'];
userFilter: ['abcd-1234'],
statusFilter: ['SUCCESS'],
trackingIds: ['172cf2f4-18cd-4f1f-b2ac-e50c7d71891c'],
requestFilter: ['request.mergeTags.item="Krabby Patty Burger"'],
envIdFilter: ["6ok6imq9unr2budgiebjdaa6oi"]
});
NameTypeDescription
dateRangeFilterobjectFilters logs by a specific date range. Optional.
dateRangeFilter.startTimenumberThe start time of the date range filter as a Unix timestamp. Optional. Cannot be less than your log retention period.
dateRangeFilter.endTimenumberThe end time of the date range filter as a Unix timestamp. Optional.
notificationFilterstring[]Filters logs by specific notification IDs. Optional. This allows you to retrieve logs for particular notifications.
channelFilterChannels[]Filters logs by specific channels. Optional. This allows you to retrieve logs for certain channels like EMAIL, SMS, etc.
userFilterstring[]Filters logs by specific user IDs. Optional. This allows you to retrieve logs for particular users.
statusFilterstring[]Filters logs by specific statuses. Optional. This allows you to retrieve logs with particular statuses like sent, failed, etc.
trackingIdsstring[]Filters logs by specific tracking IDs. Optional. This allows you to retrieve logs for particular tracking events.
requestFilterstring[]Filters logs by specific body request of your send request. Optional. This allows you to retrieve logs for particular requests.
envIdFilterstring[]Filters logs by specific environment IDs. Optional. This allows you to retrieve logs for particular environments.
customFilterstringA custom filter for querying logs. Optional. This allows for more advanced and flexible querying of logs. Note: custom filter overwrites all the filters.

You can run more complex filters using customFilter. Note that customFilter overwrites all other filters in the request.

fields @message| filter request.user.email like /com/ and request.user.email not like /gmail.com/| sort @timestamp desc