Saltar al contenido

Documentación

1. Genera un token en tu backend

Tu aplicación tiene una clave de firma. Tu backend ya sabe quién ha iniciado sesión, así que firma un token de corta duración que identifica a ese usuario. La clave nunca llega al navegador.

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. Coloca la campana en la página

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

Es un elemento personalizado, así que funciona igual en React, Vue, Svelte, Rails o una página sin más. Vuelve a asignar el atributo token cuando lo renueves y el elemento se reconectará por su cuenta.

3. Publica desde tu 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"
  }'

El suscriptor se crea en la primera publicación, así que no hay ningún paso de sincronización de usuarios. Pasa un dedupeKey y, si tu gestor de tareas reintenta el envío, la campana no sonará dos veces.

SDK de servidor y React

¿Prefieres un cliente tipado a HTTP sin más? @notifybell/node publica, difunde y genera tokens de suscriptor, con reintentos ante 429 y 5xx. @notifybell/react muestra la campana como componente y renueva su token antes de que caduque. Ambos tienen licencia MIT y están en 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} />

Darle estilo

El elemento se renderiza dentro de un shadow root, así que tu CSS no puede cambiarle el estilo por accidente ni sus estilos pueden filtrarse a tu página. Hay tres partes expuestas a propósito:

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

Idioma, tema y eventos

Atributos: app-id, token, api-url, lang. La propiedad strings traduce cada palabra (title, markAll, all, unread, archived, archive, restore, markRead, markUnread, empty, more, required…) y strings.categories nombra las categorías. Eventos: notify-bell:click y notify-bell:action se pueden cancelar; llama a preventDefault() para navegar dentro de la aplicación en lugar de abrir una pestaña; notify-bell:token-expired pide un token nuevo. El tema viene del panel; tus propiedades CSS en el elemento (--nb-accent, --nb-badge, --nb-radius) y ::part(bell | badge | panel | toast) siguen mandando.

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

Añade un endpoint por aplicación en la página Webhooks y NotifyBell le enviará eventos por POST: notification.created, notification.read, notification.seen, notification.clicked, notification.archived, notification.retracted, subscriber.erased. Cada petición lleva NotifyBell-Signature (t=marca de tiempo,v1=HMAC-SHA256 de "marca.cuerpo" con el secreto del endpoint); rechaza lo que no se verifique o tenga más de cinco minutos. Una respuesta que no sea 2xx se reintenta tras 1 minuto, 5 minutos, 30 minutos, 2 horas y 12 horas, y después se marca como fallida y se guarda para reintentar a mano. Entrega al menos una vez: deduplica por el 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)
}

Referencia de la API

Los endpoints de backend requieren una clave de API (Authorization: Bearer nb_…). Los de la bandeja requieren un token de Suscriptor, como cabecera bearer o ?token=.

Límites, con franqueza