Vai al contenuto

Documentazione

1. Genera un token nel tuo backend

La tua app ha una chiave di firma. Il tuo backend sa già chi ha effettuato l'accesso, quindi firma un token di breve durata che indica quell'utente. La chiave non raggiunge mai il browser.

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. Inserisci la campanella nella pagina

<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>

È un elemento personalizzato, quindi funziona allo stesso modo in React, Vue, Svelte, Rails o in una pagina HTML semplice. Imposta di nuovo l'attributo token quando lo rinnovi e l'elemento si riconnetterà da solo.

3. Pubblica dal tuo 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'iscritto viene creato alla prima pubblicazione, quindi non serve alcun passaggio di sincronizzazione degli utenti. Passa una dedupeKey e un nuovo tentativo del tuo job runner non farà suonare la campanella due volte.

SDK per server e React

Preferisci un client tipizzato all’HTTP grezzo? @notifybell/node pubblica, invia broadcast e genera i token degli iscritti, con nuovi tentativi su 429 e 5xx. @notifybell/react mostra la campanella come componente e rinnova il token prima che scada. Entrambi hanno licenza MIT e sono su 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} />

Personalizzare lo stile

L'elemento viene renderizzato in uno shadow root, così il tuo CSS non può modificarne lo stile per errore e i suoi stili non possono interferire con la tua pagina. Tre parti sono esposte intenzionalmente:

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

Lingua, tema ed eventi

Attributi: app-id, token, api-url, lang. La proprietà strings traduce ogni parola (title, markAll, all, unread, archived, archive, restore, markRead, markUnread, empty, more, required…) e strings.categories dà un nome alle categorie. Eventi: notify-bell:click e notify-bell:action sono annullabili: chiama preventDefault() per navigare nell’app invece di aprire una scheda; notify-bell:token-expired chiede un nuovo token. Il tema arriva dalla dashboard; le tue proprietà CSS sull’elemento (--nb-accent, --nb-badge, --nb-radius) e ::part(bell | badge | panel | toast) hanno la precedenza.

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; }

Webhook

Aggiungi un endpoint per app nella pagina Webhook e NotifyBell vi invia gli eventi in POST: notification.created, notification.read, notification.seen, notification.clicked, notification.archived, notification.retracted, subscriber.erased. Ogni richiesta include NotifyBell-Signature (t=timestamp,v1=HMAC-SHA256 di "timestamp.corpo" con il segreto dell’endpoint); rifiuta ciò che non si verifica o ha più di cinque minuti. Una risposta non 2xx viene ritentata dopo 1 minuto, 5 minuti, 30 minuti, 2 ore e 12 ore, poi segnata come fallita e conservata per un nuovo tentativo manuale. Consegna almeno una volta: deduplica sull’id del payload.

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)
}

Riferimento API

Gli endpoint di backend richiedono una chiave API (Authorization: Bearer nb_…). Quelli della inbox richiedono un token di Iscritto, come header bearer o ?token=.

Limiti dichiarati