> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ofauth.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Realtime from the browser

> Show live OnlyFans activity in a web page without exposing an access token.

A web page can receive [Realtime events](https://docs.ofauth.com/v3/guides/realtime-onlyfans-events.md) straight from OFAuth over Server-Sent Events. Your server creates a **stream URL**; the page opens it:

```typescript theme={null}
// Your server (it has the access token)
const { url } = await createStreamUrl(linkedAccountId)

// The page
const events = new EventSource(url)
```

The page sends no authorization headers or access tokens. The URL contains a scoped stream credential.

> [!WARNING]
>
> Never send an access token to a browser. Anyone who can read the page, its storage, or its network traffic could call the API as your app. The access-token APIs (`/v3/access`, `/v3/linked-accounts`, `/v3/vault-plus`, Realtime with `Authorization: Bearer`) send no CORS headers, so browsers block them.

## Create a stream URL on your server

```http theme={null}
POST https://api.ofauth.com/v3/realtime
Authorization: Bearer <access token>
Content-Type: application/json

{ "linkedAccountId": "conn_example123" }
```

```json theme={null}
{
  "url": "https://api.ofauth.com/v3/realtime/events?linkedAccountId=conn_example123&credential=ofrs_…",
  "expiresAt": "2026-10-25T09:40:00.000Z"
}
```

Return `url` only to a signed-in user who may see that linked account. An endpoint in your app, for example with Express:

```typescript theme={null}
app.post("/api/realtime-stream", requireUser, async (req, res) => {
  const linkedAccountId = String(req.body.linkedAccountId)
  // Your check: this user may see this linked account.
  if (!(await userOwnsLinkedAccount(req.user, linkedAccountId))) return res.sendStatus(403)

  const response = await fetch("https://api.ofauth.com/v3/realtime", {
    method: "POST",
    headers: {
      authorization: `Bearer ${await accessTokenFor(req.user)}`,
      "content-type": "application/json",
    },
    body: JSON.stringify({ linkedAccountId }),
  })
  if (!response.ok) {
    const retryAfter = response.headers.get("retry-after")
    if (retryAfter) res.set("retry-after", retryAfter)
    return res.sendStatus(response.status)
  }
  const { url, expiresAt } = await response.json()
  res.set("cache-control", "no-store").json({ url, expiresAt })
})
```

| Status | Meaning |
| - | - |
| `401` | The access token is missing, invalid, or expired. Refresh it. |
| `403` | The token's authorization does not cover this linked account. |
| `429` | More than 30 stream URLs in a minute for this authorization. Wait for `Retry-After`. |

## Open it in the page

The [TypeScript SDK](https://docs.ofauth.com/v3/sdk/typescript.md) provides a browser entry point that handles reconnects, cursor replay, duplicate events, and tab sharing:

```typescript theme={null}
import { connectRealtimeStream } from "@ofauth/onlyfans-sdk/realtime-browser"

class StreamUrlError extends Error {
	constructor(readonly status: number) {
		super(`Stream URL request failed: ${status}`)
	}
}

function mountRealtime(linkedAccountId: string) {
	const stream = connectRealtimeStream({
		linkedAccountId,
		getStreamUrl: async () => {
			const response = await fetch("/api/realtime-stream", {
				method: "POST",
				headers: { "content-type": "application/json" },
				body: JSON.stringify({ linkedAccountId }),
			})
			if (!response.ok) throw new StreamUrlError(response.status)
			return response.json()
		},
	})

	stream.on("realtime.inbox_counts.updated", (event) => updateCounts(event.data))
	stream.onResync(() => refetchFromYourServer())
	stream.onError((error) => {
		// Stop when your server refuses access; retrying cannot grant permission.
		if (error instanceof StreamUrlError && [401, 403].includes(error.status)) stream.close()
	})

	// Run this cleanup before switching accounts, signing out, or removing the view.
	return () => stream.close()
}
```

Call the returned function from your view's cleanup handler. Create a new stream with the new `linkedAccountId` after an account switch. The helper cancels pending reconnects and releases this tab's lock when closed.

Each event arrives as:

```
id: 42
event: realtime.inbox_counts.updated
data: {"eventId":"evt_…","type":"realtime.inbox_counts.updated","order":42,"linkedAccountId":"conn_example123",…}
```

`data` is the same JSON as on the [server stream](https://docs.ofauth.com/v3/guides/realtime-onlyfans-events.md#receive-realtime-over-server-sent-events). Delivery is at least once: ignore an `eventId` you have already handled.

## Reconnects and reauth

* **Network drops:** `EventSource` reconnects by itself with the same URL and sends the last `id`. OFAuth replays what you missed (the last 15 minutes, up to 1,000 events). You don't need to do anything.
* **`resync`:** the missed events are no longer available. Refetch the state you show, then keep listening.
* **`closed` with `reauth`:** the stream URL expired (after 10 minutes), or the account is no longer shared with your app. The SDK gets a new URL from your server. If your server can't create one (`401` or `403`), stop.
* **After `reauth`**, the old URL returns `401`, so `EventSource` stops retrying by itself.
* **`closed` with `unavailable`**, or the stream drops: `EventSource` reconnects by itself. If OFAuth answers `503` during an outage, `EventSource` stops (`readyState` is `CLOSED`); the SDK retries with jittered backoff, up to 30 seconds by default.
* **`closed` with `replaced`:** more than 10 streams were open for this linked account and authorization, and this one was the oldest. A new stream can replace a browser stream; if all 10 streams use server bearer authentication, it receives `429 stream_limit` instead. The replaced stream's URL now returns `409 stream_replaced`, so `EventSource` stops by itself; don't reconnect automatically. The SDK stops in `replaced` until you call `stream.resume()`.

## One stream per browser

Each open tab with its own `EventSource` counts as one stream. The SDK helper shares a stream by `linkedAccountId` using `BroadcastChannel` and a [Web Lock](https://developer.mozilla.org/docs/Web/API/Web_Locks_API). Only the leader tab requests a stream URL; followers receive events and cursors through the channel. When the leader closes its stream or tab, another tab takes over with a new URL and the last cursor it received.

Tab sharing needs both APIs in a secure context. Without them, each tab opens its own stream. Close the old stream before changing accounts or signing out. Use each URL for one `EventSource` only: reconnecting with the same URL replaces only that URL's previous connection.

## Why a URL is safe enough here

The stream URL carries a short-lived credential, so treat the URL like a password:

* It only opens this event stream, read-only, for one linked account. It can't call the API.
* It works for 10 minutes at most, and never longer than your access token.
* OFAuth checks the account's access on every connect and every 30 seconds while the stream is open. A new connection is refused after authorization is removed; an open stream closes when its next authorization check fails.
* The stream sends `Referrer-Policy: no-referrer`, and OFAuth doesn't log stream URLs. Don't log them in your app either.

Your server can use the same stream with `Authorization: Bearer` instead of a stream URL; see [Receive Realtime over Server-Sent Events](https://docs.ofauth.com/v3/guides/realtime-onlyfans-events.md#receive-realtime-over-server-sent-events).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.