Aller au contenu

Documentation

1. Générez un jeton depuis votre backend

Votre application dispose d'une clé de signature. Votre backend sait déjà qui est connecté : il signe donc un jeton de courte durée au nom de cet utilisateur. La clé n'arrive jamais jusqu'au navigateur.

import { createHmac } from 'node:crypto'

function mintToken(appId, userId, signingKey, ttlSeconds = 900) {
  const payload = {
    aid: appId,
    sub: userId,                                 // your own user id
    exp: Math.floor(Date.now() / 1000) + ttlSeconds,
    // tnt: workspaceId,                         // optional: one tenant's bell
  }
  const encoded = Buffer.from(JSON.stringify(payload)).toString('base64url')
  const signature = createHmac('sha256', signingKey).update(encoded).digest('base64url')
  return `${encoded}.${signature}`
}

2. Placez la cloche sur la page

<script src="https://notifybell.altixcode.com/embed/notify-bell.js" defer></script>

<notify-bell app-id="app_…" token="…" api-url="https://notifybell.altixcode.com"></notify-bell>

Il s'agit d'un élément personnalisé : il fonctionne donc de la même façon avec React, Vue, Svelte, Rails ou une simple page HTML. Redéfinissez l'attribut token lorsque vous le renouvelez et l'élément se reconnecte de lui-même.

3. Publiez depuis votre backend

curl -X POST https://notifybell.altixcode.com/api/v1/apps/APP_ID/notifications \
  -H "Authorization: Bearer nb_…" \
  -H "Content-Type: application/json" \
  -d '{
    "subscriberId": "usr_99812",
    "title": "Deployment completed",
    "body": "Your production build v1.4.2 was deployed.",
    "category": "system",
    "actionUrl": "https://app.example.com/deployments/123",
    "dedupeKey": "deploy-123"
  }'

L'abonné est créé dès la première publication : aucune étape de synchronisation des utilisateurs n'est nécessaire. Transmettez une dedupeKey et une nouvelle tentative de votre gestionnaire de tâches ne fera pas sonner la cloche deux fois.

SDK serveur et React

Vous préférez un client typé à du HTTP brut ? @notifybell/node publie, diffuse et génère les jetons d’abonné, avec nouvelles tentatives sur 429 et 5xx. @notifybell/react affiche la cloche comme composant et renouvelle son jeton avant son expiration. Les deux sont sous licence MIT et disponibles sur npm.

npm install @notifybell/node @notifybell/react

// server
import { NotifyBell, mintSubscriberToken } from '@notifybell/node'
const app = new NotifyBell({ apiKey: process.env.NOTIFYBELL_API_KEY }).app('app_123')
await app.publish({ subscriberId: user.id, title: 'Your export is ready' })
const token = mintSubscriberToken({ appId: 'app_123', subscriberId: user.id, signingKey })

// React
import { NotifyBell } from '@notifybell/react'
<NotifyBell appId="app_123" token={token} getToken={fetchFreshToken} />

Personnaliser le style

L'élément s'affiche dans un shadow root : votre CSS ne risque donc pas d'en modifier le style par accident, et ses styles ne peuvent pas se propager à votre page. Trois parties sont exposées délibérément :

notify-bell::part(bell)   { color: #64748b; }
notify-bell::part(badge)  { background: #2563eb; }
notify-bell::part(panel)  { border-radius: 4px; }

Langue, thème et événements

Attributs : app-id, token, api-url, lang. La propriété strings traduit chaque mot (title, markAll, all, unread, archived, archive, restore, markRead, markUnread, empty, more, required…) et strings.categories nomme les catégories. Événements : notify-bell:click et notify-bell:action sont annulables — appelez preventDefault() pour naviguer dans l’application au lieu d’ouvrir un onglet ; notify-bell:token-expired demande un nouveau jeton. Le thème vient du tableau de bord ; vos propriétés CSS sur l’élément (--nb-accent, --nb-badge, --nb-radius) et ::part(bell | badge | panel | toast) restent prioritaires.

const bell = document.querySelector('notify-bell')
bell.strings = {
  title: 'Benachrichtigungen',
  markAll: 'Alle gelesen',
  categories: { billing: 'Rechnungen' },
}
bell.addEventListener('notify-bell:click', (event) => {
  event.preventDefault()            // route in-app instead of opening a tab
  router.push(event.detail.data.path)
})
bell.addEventListener('notify-bell:token-expired', async () => {
  bell.setAttribute('token', await fetchFreshToken())
})

/* CSS */
notify-bell { --nb-accent: #0f766e; --nb-badge: #b91c1c; --nb-radius: 8px; }

Webhooks

Ajoutez un endpoint par application sur la page Webhooks et NotifyBell y envoie les événements en POST : notification.created, notification.read, notification.seen, notification.clicked, notification.archived, notification.retracted, subscriber.erased. Chaque requête porte NotifyBell-Signature (t=horodatage,v1=HMAC-SHA256 de "horodatage.corps" avec le secret de l’endpoint) ; rejetez tout ce qui ne se vérifie pas ou date de plus de cinq minutes. Une réponse hors 2xx est retentée après 1 minute, 5 minutes, 30 minutes, 2 heures et 12 heures, puis marquée en échec et conservée pour une relance manuelle. Livraison au moins une fois : dédupliquez sur l’id de la charge utile.

import { createHmac, timingSafeEqual } from 'node:crypto'

// rawBody: the request body exactly as received, before JSON parsing.
function verify(rawBody, header, secret) {
  const parts = Object.fromEntries(header.split(',').map((p) => p.split('=')))
  const age = Math.abs(Date.now() / 1000 - Number(parts.t))
  if (!parts.t || !parts.v1 || age > 300) return false
  const expected = createHmac('sha256', secret).update(`${parts.t}.${rawBody}`).digest()
  const given = Buffer.from(parts.v1, 'hex')
  return given.length === expected.length && timingSafeEqual(given, expected)
}

Référence de l’API

Les endpoints backend attendent une clé d'API (Authorization: Bearer nb_…). Les endpoints de boîte de réception attendent un jeton d'Abonné, en en-tête bearer ou en ?token=.

Les limites, en toute franchise