Realtime Subscriptions
PaperDB lets you listen to document changes in real time over WebSockets. When a document is created, updated, or deleted, all subscribed clients receive an event immediately.
How it works
Your backend requests a short-lived JWT token scoped to specific collections. Your frontend connects to the realtime server using that token — your API key is never exposed to the browser.
Subscribe via SDK
The SDK handles token generation and WebSocket management automatically. It reconnects on disconnect and re-subscribes to channels.
import { createClient } from "paperdb";
const db = createClient({
apiKey: process.env.PAPERDB_API_KEY,
baseUrl: "https://api.paperdb.app",
realtimeUrl: "wss://realtime.paperdb.app",
});
// Subscribe to a collection — returns an unsubscribe function
const unsubscribe = db.realtime.subscribe("messages", (event) => {
if (event.type === "insert") {
console.log("New message:", event.data);
} else if (event.type === "update") {
console.log("Message updated:", event.data);
} else if (event.type === "delete") {
console.log("Message deleted:", event.data);
}
});
// Stop listening
unsubscribe();Generate a token manually
If you need the raw token (e.g., to pass to a custom WebSocket client):
const token = await db.realtime.generateToken({
collections: ["messages", "notifications"],
permissions: ["read"],
});
// Connect directly
const ws = new WebSocket(
`wss://realtime.paperdb.app?token=${encodeURIComponent(token)}`
);Token API (server-side)
curl -X POST https://api.paperdb.app/realtime/token \
-H "Authorization: Bearer your_api_key" \
-H "Content-Type: application/json" \
-d '{
"collections": ["messages", "notifications"],
"permissions": ["read"]
}'Event shape
// Every event has this shape:
{
type: "insert" | "update" | "delete",
collection: string,
data: Record<string, unknown> // the full document
}Realtime is only available on Pro and Team plans. Connecting on a Free plan returns 403 Forbidden from the token endpoint.