Start

Auth and tokens

Your server signs a token; the browser connects with it. No round trip.

Your server signs tokens with your project's secret key, so handing one out needs no call to Pulse. A token names a user, lists the channels they may join and expires; the browser client asks your server for a new one when it needs to.

Sign a token

server.ts
typescript
import { Pulse } from "@anishroy/pulse/server"
const rt = new Pulse() // reads PULSE_SECRET_KEY and PULSE_URL
const token = await rt.token({ user: { id: user.id, name: user.name }, channels: ["orders:*", `chat:${user.id}:*`], // may join publish: [`chat:${user.id}:*`], // may publish to, from the browser ttlSeconds: 600, // the default})
OptionMeaning
userAn id, or { id, name, image }. Others see the name and image in presence.
channelsChannel names or patterns the user may join, like orders:*. * matches any run of characters.
publishPatterns the browser may publish to; true means the same as channels. Leave it out and the browser only reads.
ttlSecondsHow long the token lasts. Default 10 minutes.

A token route

createTokenRoute turns that into a route handler for any Fetch API router (Next.js, Remix, Hono, a plain fetch handler). Decide who the caller is from your own session; return null to refuse.

app/api/pulse/token/route.ts
typescript
import { createTokenRoute } from "@anishroy/pulse/server"
export const POST = createTokenRoute({ authorize: async (request) => { const user = await currentUser(request) // your session if (!user) return null // 401 return { user: { id: user.id, name: user.name, image: user.avatarUrl }, channels: [`orders:${user.id}`, "room:*"], } },})

In the browser

Point the provider at your route, or pass a function that returns a token. It's safe with server rendering: nothing touches the network during render, and a relative URL is resolved in the browser only.

layout.tsx
tsx
import { PulseProvider } from "@anishroy/pulse/react"
<PulseProvider url={PULSE_URL} auth="/api/pulse/token"> {children}</PulseProvider>
// Or fetch it yourself<PulseProvider url={PULSE_URL} auth={async () => (await api.pulseToken()).token}>

When a token is refused

A bad, expired or out-of-scope token never reaches the channel: the connection closes with a code the client acts on.

CodeMeansThe client
4401Missing, malformed, badly signed or expiredFetches a new token and reconnects
4403Valid, but not for this channelStops; the status becomes forbidden
4400A bad channel name or resume pointStops
4429Far too many presence updatesWaits a minute, then reconnects
4503The channel is full (5,000 connections)Retries with backoff

Keep the key secret

  • The secret key signs tokens and publishes to any channel. Keep it on your server, in PULSE_SECRET_KEY.
  • Keys belong to a project. Create and revoke them in the dashboard; a revoked key stops working within a minute.
  • Server-side publishing doesn't need a token at all: see Events.