Web SDK

Web SDK

Add push notifications to any website in minutes. The SDK handles subscription prompts, service worker registration, and token management automatically.

Installation

1. Create two small loader files in the root of your site. The SDK and the service worker themselves are loaded from Notirix — these files only point to them.

push-loader.js

js
export { NotirixSDK, initNotirix } from "https://push.notirix.com/sdk/index.js";

push-sw.js

js
var MAIN_SW_URL = "https://push.notirix.com/worker/main-sw.js";
try { importScripts(MAIN_SW_URL); } catch(e) {
  self.addEventListener("push", function(){});
  self.addEventListener("notificationclick", function(e){ e.notification.close(); });
}
ℹ️
Both files must be served from the root of your domain (e.g. https://example.com/push-sw.js) — a service worker only controls pages inside its own folder. Your site must use HTTPS.

2. Initialize the SDK on every page where push should work:

html
<script type="module">
  import { initNotirix } from "/push-loader.js";

  const notirix = initNotirix({
    apiBaseUrl:     "https://push.notirix.com",
    appId:          "YOUR_APP_ID",
    vapidPublicKey: "YOUR_VAPID_PUBLIC_KEY",
  });

  // Show the prompt configured in Admin → Configuration
  const result = await notirix.subscribeWithPrompt();
  console.log(result.status); // 'subscribed'
</script>
💡
The App ID and vapidPublicKey are in Admin → Settings. You don't need to call any separate init method: the SDK registers the service worker and loads the prompt configuration on the first call.
ℹ️
Moving from another push service? Browsers that are still subscribed with its key are moved over automatically on their next visit: the SDK replaces the old subscription without asking for permission again, and the subscriber keeps their profile, tags and history (SDK 1.7.1+).

Prompt types

Notirix supports five prompt styles. Configure the default in Admin → Configuration, or override per-call in subscribeWithPrompt().

🪟
modal

Centered overlay with branded header. Default style.

📌
slide

Full-width bar that slides from top or bottom.

🔔
bell

Floating FAB bell button + popover card.

💬
native

Browser's built-in permission dialog. No custom UI.

⚙️
custom

No Notirix UI on page load — you decide when to ask. Calling subscribeWithPrompt() with branding options shows the modal.

js
// Override type and branding per-call
const result = await notirix.subscribeWithPrompt({
  type:         'modal',
  brandName:    'My Store',
  accentColor:  '#FF6B35',
  title:        'Get sale alerts',
  description:  'Be first to know about flash deals.',
  allowLabel:   'Yes, notify me',
  laterLabel:   'Maybe later',
})

iOS PWA support

Web Push on iOS requires the user to install the site as a PWA (iOS 16.4+). The SDK detects iOS Safari and shows an "Add to Home Screen" banner automatically.

js
const result = await notirix.subscribeWithPrompt()

if (result.status === 'ios-pwa-required') {
  // SDK already showed the "Add to Home Screen" banner.
  // You can also show your own message:
  console.log('User needs to install the PWA first')
}
ℹ️
subscribeWithPrompt() returns "ios-pwa-required" when the user is on iOS Safari outside standalone mode. The banner is shown automatically — no extra code needed.

Customization

Pass options to subscribeWithPrompt() to override the server config:

js
await notirix.subscribeWithPrompt({
  type:             'slide',
  slidePosition:    'bottom',   // 'top' | 'bottom'
  accentColor:      '#2ECFB1',
  borderRadius:     '12px',
  allowButtonColor: '#2ECFB1',
  laterButtonColor: 'transparent',
  forceShow:        true,       // ignore a recent "Later" click
})
💡
After the visitor clicks "Later", the prompt is hidden for a while and subscribeWithPrompt() returns "snoozed". Pass forceShow: true when the visitor asks for the prompt explicitly, e.g. by clicking your own "Subscribe" button.

Show the prompt from the N-th page

To let visitors look around first, set Settings → Configuration → Show Prompt From in Admin to the page view of the visit (2–20) on which the prompt should first appear. On earlier pages subscribeWithPrompt() shows nothing and returns "waiting-page-views", so keep calling it on every page — no other code changes are needed. Available since SDK 1.6.0.

  • Page views are counted per visit — per browser tab (sessionStorage), once per page where the SDK is initialized. A new tab or a new visit starts from 1.
  • Visitors who are already subscribed are not affected: their subscription is still re-synced on every page.
  • forceShow: true skips the wait; showAfterPageViews in the options overrides the Admin value for a single call.
  • The 1C-Bitrix module calls subscribeWithPrompt() on every page, so it picks the setting up automatically.

Methods

All methods are available on the object returned by initNotirix(). Methods that take a callback also return a Promise, so you can use either style.

initNotirix(options)

Creates the SDK instance. Options: apiBaseUrl, appId, vapidPublicKey, and optionally externalId, externalIdHash (the signature of externalId from your server, see Identity verification; SDK 1.8.0+), debug, serviceWorkerPath (default "/push-sw.js"). Calling it again with the same appId returns the same instance.

subscribeWithPrompt(options?, callback?)

Shows the permission prompt configured in Admin and subscribes the user. Resolves with { status } — see the table below.

js
const result = await notirix.subscribeWithPrompt()
if (result.status === 'subscribed' || result.status === 'already-subscribed') {
  // the user can receive notifications
}
subscribe(callback?)

Requests permission with the browser's dialog and subscribes, without any Notirix UI. Throws if permission is not granted.

setExternalId(externalId, externalIdHash?)

Links the subscription to your own user ID. Set it before subscribing (or pass externalId to initNotirix), and again right after sign-in: the anonymous profile of this browser (tags, events, journeys) moves to the user, and later tag / event calls are sent on their behalf (SDK 1.5.0+). Pages without an externalId (guest pages, an expired session) keep the subscription with the user it belongs to — personal pushes such as order updates keep arriving. externalIdHash is the signature from your server (SDK 1.8.0+, see Identity verification); when it is omitted, a previously set hash is dropped.

js
// After sign-in, with the hash returned by your server
notirix.setExternalId('user-42', hashFromServer)

// or through the command queue
window.Notirix.push(['setExternalId', 'user-42', hashFromServer])
logout(callback?)

Call it when the visitor signs out: the browser's subscription goes back to an anonymous user, so the signed-out account stops getting pushes in this browser, and the SDK forgets the externalId, its hash and its token. Rejects if the server could not be reached — the subscription then still belongs to the user, call it again later. Without logout() the subscription stays with the last signed-in user until another account signs in on this browser (SDK 1.7.0+).

js
await notirix.logout()

// or through the command queue
window.Notirix.push(['logout'])
sendTags(tags, callback?) / sendTag(key, value, callback?)

Sets one or several tags on the current user. Requires an active subscription.

getTags(callback?)

Returns the current user's tags: [{ key, value }, …].

sendEvent(name, callback?)

Records a custom event for the current user (SDK 1.4.0+). See Custom events below.

getUserId(callback?) / getUser(callback?)

Returns the Notirix user ID / the user profile from the server. null before the first subscription.

getUnreadCount(tag?)

Number of unread push messages of the current user, optionally only with the given message tag. Returns 0 when not subscribed.

isPushSupported()

true if the browser supports web push.

setDebug(enabled)

Turns verbose logging on or off. Logs go to the console and to Admin → SDK Debug Logs.

push([command, ...args])

The same methods in command form — handy in inline scripts where the notirix variable is not in scope.

js
window.Notirix.push(['sendEvent', 'purchase'])
window.Notirix.push(['sendTags', { plan: 'premium' }])

Subscription statuses

StatusMeaning
subscribedThe user allowed notifications and is now subscribed.
already-subscribedThe user was already subscribed.
cancelledThe user closed the prompt without allowing.
deniedNotifications are blocked in the browser.
snoozedThe user clicked "Later" recently — the prompt is hidden for now (see forceShow).
waiting-page-viewsFewer page views in this visit than "Show Prompt From" — the prompt appears on a later page (see forceShow).
unsupportedThe browser does not support web push.
ios-pwa-requirediOS Safari: the site must be added to the Home Screen first (banner shown automatically).
limit-reachedThe subscriber limit of your plan is reached — no prompt is shown.
app-disabledThe app is disabled — no prompt is shown.

Identity verification

The App ID is public, so without a check anyone could put someone else's externalId into their own browser and receive that user's personal pushes. Identity verification closes this: your server signs the externalId, and Notirix binds a subscription to it only when the signature matches. Available since SDK 1.8.0.

1. Copy the identity secret (notirix_idv_…) from Admin → Settings → Identity verification. It is not the API key. Keep it on your server only — never in page code or a mobile app.

2. On your server, compute externalIdHash — HMAC-SHA256 of the externalId with the whole secret string as the key, as 64 lowercase hex characters:

js
// Node.js
const crypto = require('crypto')
const externalIdHash = crypto
  .createHmac('sha256', process.env.NOTIRIX_IDENTITY_SECRET) // 'notirix_idv_…'
  .update(user.id)                                           // the same string you pass as externalId
  .digest('hex')

// PHP
$externalIdHash = hash_hmac('sha256', $externalId, NOTIRIX_IDENTITY_SECRET);

# Python
external_id_hash = hmac.new(secret.encode(), external_id.encode(), hashlib.sha256).hexdigest()

3. Render the hash into the page next to the externalId — on every page where you pass the externalId, not only on the first one:

html
<script type="module">
  import { initNotirix } from "/push-loader.js";

  const notirix = initNotirix({
    apiBaseUrl:     "https://push.notirix.com",
    appId:          "YOUR_APP_ID",
    vapidPublicKey: "YOUR_VAPID_PUBLIC_KEY",
    externalId:     "<?= $externalId ?>",      // signed-in user only
    externalIdHash: "<?= $externalIdHash ?>",  // computed on your server
  });

  notirix.subscribeWithPrompt();
</script>

Modes

ModeWhat happens to an externalId without a valid hash
offDefault. Nothing is checked — everything works as before.
warnAccepted as before, and written to the app's SDK Debug Logs (at most once per user per hour). Use it to find pages that still send unsigned IDs.
enforceRejected with HTTP 400 (errorCode IDENTITY_VERIFICATION_FAILED): nothing is bound to that externalId, no profile or token of that user is returned.
  • Only requests that carry an externalId are checked. Guest pages without an externalId and logout() need no hash.
  • An externalId starting with anon: or mobile: is ignored in every mode — these prefixes name anonymous users on the server. The request is handled as if no externalId came, and a warning is written to the SDK logs.
  • When the server rejects an externalId, the SDK prints a console warning and re-sends the subscription without it: the browser stays subscribed (a new subscription is anonymous, an existing one keeps its owner), and that externalId is not retried on the page.
  • Rotating the secret in Admin makes every old signature stop matching at once — update your servers right after rotating.
  • The 1C-Bitrix module (1.4.0+) signs the externalId of signed-in visitors itself once its Identity Secret option is filled in.
💡
Recommended rollout: deploy the hashes on your site → switch the mode to warn → check SDK Debug Logs and the counter of unverified requests on the Identity verification card → switch to enforce once nothing unsigned arrives.

User tags

Tags let you segment subscribers. Set them from the SDK, the REST API, or the Admin UI. Tags need an active subscription — call them after subscribeWithPrompt() has finished.

js
const result = await notirix.subscribeWithPrompt()

if (result.status === 'subscribed' || result.status === 'already-subscribed') {
  // Several tags at once
  await notirix.sendTags({ plan: 'premium', total_orders: 14, interests: ['sports', 'tech'] })

  // A single tag
  await notirix.sendTag('last_purchase_category', 'electronics')

  // Read them back
  const tags = await notirix.getTags() // [{ key: 'plan', value: 'premium' }, …]
}
💡
Tags are key-value pairs. Values can be strings, numbers, booleans or arrays. Existing keys are overwritten (upsert).

Custom events

Report something the user did — a purchase, a sign-up, a completed form. Journeys use these events in the exit rule "Custom event": the user leaves the journey as soon as the event arrives. Available since SDK 1.4.0.

js
// After a successful checkout
await notirix.sendEvent('purchase')

// Callback style
notirix.sendEvent('signup_completed', function () {
  console.log('event sent')
})
ℹ️
Event name: 1–100 characters — letters, digits, _ - .:. Like tags, events need an active subscription: for a visitor who is not subscribed the call is skipped with a console warning. Events are stored for 90 days. To send events from your server, use the REST API.