In-App Inbox — Guia Completo
Adicione uma central de notificações ao seu app em minutos com o SDK React @notifica/react. Este guia cobre instalação, configuração de segurança (allowed origins), developer mode, e troubleshooting.
Visão Geral
O inbox in-app permite que seus usuários vejam, leiam e interajam com notificações diretamente no seu frontend — sem redirect, sem polling manual. O SDK cuida de tudo:
- Bell icon com badge de contagem de não lidas
- Popover ou inbox standalone com lista paginada
- Mark as read individual e em lote
- Polling automático (configurável)
- i18n (pt-BR e en)
- Theming via CSS custom properties (light/dark)
Pré-requisitos
| Requisito | Detalhe |
|---|---|
| Conta no Notifica | app.usenotifica.com.br |
Publishable key (pk_live_* ou pk_test_*) | Gerada no dashboard |
| Subscriber cadastrado | Via API ou SDK server-side |
| React 18+ | Peer dependency |
Publishable Key vs Secret API Key
O Notifica tem dois tipos de API key com propósitos distintos:
Publishable Key (pk_*) | Secret API Key (nk_*) | |
|---|---|---|
| Prefixo | pk_live_ / pk_test_ | nk_live_ / nk_test_ |
| Onde usar | Frontend (browser) | Backend (server-side) |
| Permissões | Somente leitura, scoped ao subscriber | Acesso total à API |
| Segurança | Exposta no client — protegida por origin allowlist | Secreta — nunca expor no client |
| Endpoints acessíveis | Notificações in-app do subscriber | Todos os endpoints /v1/* |
Nunca use uma secret key (nk_*) no frontend. Ela dá acesso total à sua conta. Use sempre a publishable key (pk_*) no @notifica/react.
Gerando uma Publishable Key
Via Dashboard:
- Acesse Configurações → API Keys
- Clique em Criar API Key
- Selecione tipo Public
- Copie a key (
pk_live_...) — ela é exibida apenas uma vez
Via API (usando sua secret key):
curl -X POST https://app.usenotifica.com.br/v1/api-keys \
-H "Authorization: Bearer $NOTIFICA_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"key_type": "public",
"label": "Frontend Inbox",
"environment": "production"
}'
Instalação
npm install @notifica/react
# ou
yarn add @notifica/react
# ou
pnpm add @notifica/react
Peer dependencies: react >= 18, react-dom >= 18.
Setup Básico
1. Provider no root do app
Envolva sua aplicação (ou a região que usa o inbox) com NotificaProvider:
import { NotificaProvider, NotificaBell } from '@notifica/react';
function App() {
return (
<NotificaProvider
apiKey="pk_live_sua_publishable_key"
subscriberId="user_123"
>
<Header />
<Main />
</NotificaProvider>
);
}
| Prop | Obrigatório | Descrição |
|---|---|---|
apiKey | Sim | Publishable key (pk_live_* ou pk_test_*) |
subscriberId | Sim | ID do subscriber (seu external_id) |
apiUrl | Não | Base URL da API (default: https://app.usenotifica.com.br) |
pollingInterval | Não | Intervalo de polling em ms (default: 30000) |
locale | Não | 'pt-BR' ou 'en' (default: 'pt-BR') |
labels | Não | Override parcial de labels i18n |
2. Bell com Popover (mais comum)
function Header() {
return (
<header style={{ display: 'flex', justifyContent: 'flex-end', padding: '1rem' }}>
<NotificaBell popoverPosition="bottom-right" />
</header>
);
}
3. Inbox Standalone (página dedicada)
import { NotificaInbox } from '@notifica/react';
function NotificacoesPage() {
return (
<NotificaInbox
maxHeight={500}
pageSize={15}
onNotificationClick={(notification) => {
if (notification.action_url) {
window.location.href = notification.action_url;
}
}}
/>
);
}
4. Hooks para UI 100% customizada
import { useNotifications, useUnreadCount } from '@notifica/react';
function MinhaInbox() {
const { notifications, markAsRead, markAllAsRead, loadMore, hasMore } = useNotifications();
const { count } = useUnreadCount();
return (
<div>
<p>{count} não lida(s)</p>
<button onClick={markAllAsRead}>Marcar todas como lidas</button>
{notifications.map((n) => (
<div key={n.id} onClick={() => markAsRead(n.id)}>
<strong>{n.title}</strong>
{n.body && <p>{n.body}</p>}
</div>
))}
{hasMore && <button onClick={loadMore}>Carregar mais</button>}
</div>
);
}
Allowed Origins — Proteção contra Uso Indevido
Publishable keys são expostas no código-fonte do seu frontend. Para evitar que terceiros usem sua key em domínios não autorizados, o Notifica valida o header Origin de toda request feita com uma pk_* key.
Como funciona
- O browser envia automaticamente o header
Originem toda request (ex:https://meuapp.com.br) - A API compara o origin com a lista de allowed origins configurada no seu tenant
- Se o origin não estiver na lista → 403 Forbidden (
origin_not_allowed) - Se estiver → request processada normalmente
Configurando Allowed Origins
Via Dashboard:
- Acesse Configurações → Inbox Embed
- Adicione os domínios onde seu frontend roda
- Salve
Via API:
# Listar origins permitidas
curl https://app.usenotifica.com.br/v1/inbox-embed/allowed-origins \
-H "Authorization: Bearer $NOTIFICA_API_KEY"
# Adicionar um origin
curl -X POST https://app.usenotifica.com.br/v1/inbox-embed/allowed-origins \
-H "Authorization: Bearer $NOTIFICA_API_KEY" \
-H "Content-Type: application/json" \
-d '{"origin": "https://meuapp.com.br"}'
# Remover um origin
curl -X DELETE "https://app.usenotifica.com.br/v1/inbox-embed/allowed-origins/ao_abc123" \
-H "Authorization: Bearer $NOTIFICA_API_KEY"
Formato do Origin
O origin deve incluir scheme e hostname. Port é necessário apenas quando não é a padrão (80/443):
| ✅ Válido | ❌ Inválido |
|---|---|
https://meuapp.com.br | meuapp.com.br (sem scheme) |
https://app.meudominio.com | https://meuapp.com.br/ (com trailing slash) |
https://staging.meuapp.com.br | *.meuapp.com.br (wildcards não suportados) |
http://localhost:3000 | localhost:3000 (sem scheme) |
Subdomínios são tratados como origins distintos. Se seu app roda em app.meudominio.com e admin.meudominio.com, adicione os dois.
Developer Mode — Localhost Automático
Para facilitar o desenvolvimento local, o Notifica oferece um developer mode que automaticamente aceita requests de localhost e 127.0.0.1 em qualquer porta — sem precisar configurar allowed origins manualmente.
Ativando Developer Mode
Via Dashboard:
- Acesse Configurações → Inbox Embed
- Ative o toggle Developer Mode
Via API:
# Ativar developer mode
curl -X PUT https://app.usenotifica.com.br/v1/inbox-embed/settings \
-H "Authorization: Bearer $NOTIFICA_API_KEY" \
-H "Content-Type: application/json" \
-d '{"developer_mode": true}'
# Consultar settings atuais
curl https://app.usenotifica.com.br/v1/inbox-embed/settings \
-H "Authorization: Bearer $NOTIFICA_API_KEY"
O que o Developer Mode faz
| Com Developer Mode ativado | Com Developer Mode desativado |
|---|---|
http://localhost:* → ✅ permitido | http://localhost:* → verificado contra allowed origins |
http://127.0.0.1:* → ✅ permitido | http://127.0.0.1:* → verificado contra allowed origins |
| Origins configurados → ✅ permitido | Origins configurados → ✅ permitido |
Desative o developer mode em produção. Ele existe para conveniência durante desenvolvimento. Em produção, configure explicitamente os origins permitidos.
Setup de Desenvolvimento Recomendado
// Use pk_test_* para desenvolvimento, pk_live_* para produção
const NOTIFICA_KEY = process.env.NODE_ENV === 'production'
? process.env.NEXT_PUBLIC_NOTIFICA_PK_LIVE
: process.env.NEXT_PUBLIC_NOTIFICA_PK_TEST;
<NotificaProvider
apiKey={NOTIFICA_KEY}
subscriberId={currentUser.id}
>
{children}
</NotificaProvider>
Com essa abordagem:
- Desenvolvimento:
pk_test_*+ developer mode ativado no environment sandbox - Produção:
pk_live_*+ allowed origins configurados, developer mode desativado
Theming
O SDK usa CSS custom properties para theming. Você pode customizar cores, fontes e espaçamentos sem tocar no código do componente.
Dark Mode
import { NotificaProvider, NotificaBell, darkTokens, tokensToCSS } from '@notifica/react';
function App() {
return (
<>
<style>{tokensToCSS(darkTokens)}</style>
<NotificaProvider apiKey="pk_live_..." subscriberId="user_123">
<NotificaBell />
</NotificaProvider>
</>
);
}
Labels Customizadas
<NotificaProvider
apiKey="pk_live_..."
subscriberId="user_123"
labels={{
notifications: 'Central de Avisos',
emptyTitle: 'Nada por aqui!',
emptyDescription: 'Volte mais tarde.',
markAllAsRead: 'Limpar tudo',
}}
>
Componentes e Hooks Exportados
Componentes
| Componente | Descrição |
|---|---|
NotificaProvider | Context provider — obrigatório como wrapper |
NotificaBell | Ícone de sino com badge + popover |
NotificaInbox | Painel completo de notificações |
NotificationItem | Item individual (para composição) |
NotificationList | Lista com infinite scroll (para composição) |
Popover | Popover genérico (para composição) |
Hooks
| Hook | Retorno | Descrição |
|---|---|---|
useNotifica() | { config, labels, apiFetch } | Acesso ao context do provider |
useNotifications(pageSize?) | { notifications, isLoading, markAsRead, markAllAsRead, loadMore, hasMore, ... } | Fetch, polling e gerenciamento |
useUnreadCount() | { count, isLoading, refresh } | Contagem de não lidas (com polling) |
Troubleshooting
403 — Origin Not Allowed
{
"error": {
"code": "origin_not_allowed",
"message": "Origin 'https://meuapp.com.br' is not in the allowed origins list"
}
}
Causas possíveis:
- Origin não configurado — Adicione
https://meuapp.com.brna lista de allowed origins - Scheme errado —
http://≠https://. Verifique se o scheme no origin cadastrado bate com o do seu app - Port faltando — Se seu app roda em porta não-padrão (ex:
https://meuapp.com.br:8443), inclua a porta no origin - Subdomínio diferente —
app.meudominio.com≠meudominio.com. Adicione cada subdomínio separadamente - Developer mode desativado — Se está rodando em
localhost, ative o developer mode ou adicionehttp://localhost:PORTAnos allowed origins
Diagnóstico rápido:
# Verifique quais origins estão configurados
curl https://app.usenotifica.com.br/v1/inbox-embed/allowed-origins \
-H "Authorization: Bearer $NOTIFICA_API_KEY"
# Verifique se developer mode está ativo
curl https://app.usenotifica.com.br/v1/inbox-embed/settings \
-H "Authorization: Bearer $NOTIFICA_API_KEY"
401 — Unauthorized
{
"error": {
"code": "unauthorized",
"message": "Invalid or missing API key"
}
}
Causas possíveis:
- Key errada — Verifique se está usando a publishable key (
pk_*), não a secret key - Key revogada — A key pode ter sido revogada no dashboard
- Ambiente incorreto —
pk_test_*só funciona no sandbox,pk_live_*só na produção
Notificações não aparecem
- Subscriber existe? — O
subscriberIdpassado ao provider precisa ser um subscriber cadastrado (viaPOST /v1/subscribersou SDK server-side) - Canal correto? — Ao enviar notificação, use
"channel": "in_app"para que apareça no inbox - Polling parado? — O default é 30s. Use
pollingInterval={5000}para testar mais rápido - Erros no console? — Abra o DevTools do browser e verifique a aba Network/Console
CORS errors no browser
Se você vê erros de CORS (e não o JSON de erro 403), o problema pode ser:
- API URL errada — Verifique a prop
apiUrldo provider - Extensão do browser — Algumas extensões bloqueiam requests cross-origin
- Proxy reverso — Se usa um proxy, garanta que ele repasse os headers
OrigineAccess-Control-*
Referências
- API Reference — Inbox Embed — Endpoints de configuração
- API Reference — Notificações In-App — Endpoints consumidos pelo SDK
- Quickstart Email — Primeiros passos com o Notifica
- Templates de Email — Templates reutilizáveis