Docs.

Thirteen sections. Read the first two for the idea, then sections 04 to 07 and you can send a message.

The problem. (01)

Realtime in Laravel means running your own infrastructure and handling each direction separately.

1. A socket serverLaravel Echo Server, Soketi or similar. You install it, keep it running, and put it behind your proxy.
2. RedisThe socket server and Laravel talk through Redis, so you run that too.
3. A frontend setupEcho and the client library, configured to match the server.
4. Two channels for one conversationLaravel can broadcast events from your server to browsers. The way back is plain AJAX calls to your own routes.
5. A listener commandTo catch what browsers send to each other, you write a command that subscribes to Redis and keep it alive with Supervisor. That is a second long-running process next to the first.

Two processes to run, a Redis to secure, and a frontend that talks to your server in two different ways.

The idea. (02)

RealtimeHub is a hosted SignalR hub. Your frontend connects to it directly and messages travel both ways on that one connection. Your Laravel app never holds a socket open.

Your backend does one thing: it asks the hub for a token for the signed-in user. After that the browser talks to the hub.

You needWhat you set upWhat runs on your server
Client to clientOne route that returns a token (section 05).Nothing extra. No Redis, no socket server, no command.
Your server to clientsOne call with your app secret (section 07).Nothing extra. No connection to hold open.
Client to your serverTurn on the webhook for the app and add one env value (section 10).Nothing extra. The hub calls a route in your app for each message.

The other direction works too. Your backend can send a message to any user with one call and your secret, with no connection to keep open (section 07).

Concepts. (03)

AppOne product of yours. It has a key, a secret, allowed origins, schemas and settings. An account can have three.
App keyA public id that starts with rhk_. Your backend sends it when it asks for a token.
SecretA private value that starts with rhs_. It is shown once when you create the app. It lives on your backend and nowhere else.
User idThe id of a signed-in user in your own system. 1 to 128 characters from A-Z a-z 0-9 _ - . : @.
TokenProof that one user belongs to one app. Valid for one hour unless you ask for a different time. Your frontend gets it from your backend.
ChannelA room you name yourself, such as trips.21. Users join it when they connect, and a message sent to it reaches everyone in it. 1 to 64 characters from A-Z a-z 0-9 _ - ..
EventThe name of a kind of message, such as chat or typing. Up to 100 characters from A-Z a-z 0-9 _ - . :.

Quick start. (04)

  1. Create an account, confirm your email, and create an app in the dashboard. Copy the key and the secret.
  2. Put both on your backend as configuration. The secret never goes to a browser.
  3. Add a route that asks the hub for a token for the signed-in user (section 05).
  4. Load the browser client and connect with that token (section 06).
  5. Call send and listen with onEvent (section 07).

The app page in the dashboard has a Quickstart tab with these steps filled in with your own key and app id.

Want to see it work first? Open the live demo in two browsers and try public, private and presence channels. See Try it live.

Get a token. (05)

Your backend calls the hub with the secret and names the user. The hub returns a token for that user.

curl
curl -X POST https://realtimehub.dev/api/token \
  -H "Authorization: Bearer YOUR_APP_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"appKey":"YOUR_APP_KEY","userId":"42"}'
Response
{"token":"eyJhbGciOi...","expiresAtUtc":"2026-11-21T10:00:00Z"}
  • ttlSeconds is optional. The default is 3600. The minimum is 60 and the maximum is 86400.
  • The token is checked when a connection opens. A connection that is already open keeps working after the token expires. A reconnect needs a fresh token, which the browser client fetches on its own.
  • A wrong secret, an unknown app key and an inactive app all return 401. A bad user id returns 400. More than 300 requests a minute from one address returns 429.
Laravel: config
// config/hub.php
return [
    'url'    => env('HUB_URL', 'https://realtimehub.dev'),
    'key'    => env('HUB_KEY'),     // YOUR_APP_KEY
    'secret' => env('HUB_SECRET'),  // the secret shown once in the dashboard
];
Laravel: route
// routes/web.php
use Illuminate\Support\Facades\Http;

Route::get('/hub-token', function () {
    $hub = config('hub');

    return Http::withToken($hub['secret'])
        ->post($hub['url'].'/api/token', [
            'appKey' => $hub['key'],
            'userId' => (string) auth()->id(),
        ])->throw()->json();
})->middleware('auth');
Node and Express: route
app.get('/hub-token', requireLogin, async (req, res) => {
  const r = await fetch(`${process.env.HUB_URL}/api/token`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.HUB_SECRET}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      appKey: process.env.HUB_KEY,
      userId: String(req.user.id),
    }),
  });
  res.status(r.status).json(await r.json());
});

Take the user id from your own session, never from the request. Whoever controls the user id controls who they appear to be.

Browser client. (06)

The hub serves a small wrapper around the SignalR browser library. It caches the token, reconnects with backoff, and retries a first connection that fails.

HTML
<script src="https://cdn.jsdelivr.net/npm/@microsoft/signalr@8.0.7/dist/browser/signalr.min.js"></script>
<script type="module">
  import { createRealtimeClient } from 'https://realtimehub.dev/sdk/realtimehub-client.js';

  const client = createRealtimeClient({
    hubUrl: 'https://realtimehub.dev/hub/chat',
    fetchToken: () => fetch('/hub-token').then((r) => r.json()),
    onEvent: (m) => console.log(m.from, m.event, m.payload),
    onStatus: (s) => console.log('status', s),
  });

  await client.start();
  const sent = await client.send('bob', 'chat', { text: 'hello' });
  console.log(sent.id, sent.persisted);
</script>
Option or methodWhat it does
hubUrlThe hub address followed by /hub/chat.
fetchTokenReturns { token, expiresAtUtc }. Usually a call to your /hub-token route.
channelsOptional list of channels to join when the connection opens.
onEvent(message)Called for every message addressed to this user or sent to a channel they are in.
onStatus(status, error)connecting, connected, reconnecting or disconnected.
start()Resolves when connected.
send(userId, event, payload)Resolves with { id, timestampUtc, persisted }. Rejects with the reason when the hub refuses the message.
onPresence({ channel, userId, type })Someone joined or left a channel you are in. type is join or leave.
joinChannel(name), leaveChannel(name)Change channels after connecting. Joined channels are joined again after a reconnect. joinChannel resolves with who is in the channel.
getPresence(name)Resolves with { channel, count, users } for a channel you are in.
sendToChannel(name, event, payload)Sends to everyone in a channel you are in. Same result and errors as send.
stop()Closes the connection and stops reconnecting.

React Native and other non-browser apps can use the official SignalR client for their platform with the same URL and token.

Send and receive. (07)

A message goes from one user to one user in the same app. The hub sets from from the token, so a client cannot send as someone else.

What the recipient gets
{
  "id": "9f2c6e1a4b7d4c0a8e3d5b6a7c8d9e0f",
  "from": "alice",
  "to": "bob",
  "event": "chat",
  "payload": { "text": "hello" },
  "timestampUtc": "2026-11-21T09:00:32.296Z"
}
  • Every open connection of the recipient receives it, so a user with two tabs sees it in both.
  • A user who is offline does not receive it later. Send messages to your own server (section 10) if you need a record.
  • A message to your own user id reaches your own connections, so you can test with one account.
  • Users in other apps never receive it, even with the same user id.

Channels

A channel is a room you name yourself. There is nothing to create: it exists while someone is in it. One connection can be in up to 20 channels.

JavaScript
const client = createRealtimeClient({
  hubUrl: 'https://realtimehub.dev/hub/chat',
  fetchToken,
  channels: ['trips.21'],                  // joined when the connection opens
  onEvent: (m) => console.log(m.channel ?? 'direct', m.from, m.event, m.payload),
});
await client.start();

await client.joinChannel('alerts');         // join later
await client.sendToChannel('trips.21', 'trip.updated', { status: 'arrived' });
await client.leaveChannel('alerts');
  • Without the browser client, add the channels to the connection address: /hub/chat?channel=trips.21&channel=alerts. The hub methods are JoinChannel, LeaveChannel and SendToChannel.
  • A channel message has channel set and no to. A user can only send to a channel they are in. The sender hears their own message.
  • By default any user can join any channel of your app. To decide who may join what, list the channels when you ask for the token. The user can then join those and nothing else. An empty list means no channels. A channel in the address that the token does not allow closes the connection.
curl: token for one channel
curl -X POST https://realtimehub.dev/api/token \
  -H "Authorization: Bearer YOUR_APP_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"appKey":"YOUR_APP_KEY","userId":"42","channels":["trips.21"]}'

Your backend can send to a channel with channel in place of to, even when nobody is in it yet:

curl
curl -X POST https://realtimehub.dev/api/send \
  -H "Authorization: Bearer YOUR_APP_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"appKey":"YOUR_APP_KEY","channel":"trips.21","event":"trip.updated","payload":{"status":"arrived"}}'
Laravel: broadcast
use Ohad\RealtimeHub\Facades\RealtimeHub;

RealtimeHub::broadcast('trips.21', 'trip.updated', ['status' => 'arrived']);

A channel message counts as one message however many people are in it. With persistence on, a message a connected client sends to a channel is also sent to your webhook, with a channel field and an empty to. Messages your backend sends are never sent back to it.

Presence

The hub knows who is in each channel. It counts users, not connections, so a user with two tabs is one member. They join when their first tab joins and leave when their last tab closes.

JavaScript
const client = createRealtimeClient({
  hubUrl: 'https://realtimehub.dev/hub/chat',
  fetchToken,
  channels: ['trips.21'],
  onPresence: ({ channel, userId, type }) => console.log(userId, type, channel),   // type: 'join' or 'leave'
});
await client.start();

const { count, users } = await client.getPresence('trips.21');   // who is here now
  • joinChannel also returns who is in the channel, you included. getPresence(channel) asks again later. You can only ask about a channel you are in.
  • Joins and leaves arrive as messages from $server with the event $presence.join or $presence.leave and the payload { "userId": "..." }. With the browser client they go to onPresence instead of onEvent. You are never told about yourself. A user who connects at the same moment you join can be announced even though they were already in the list you got, so apply each event as adding or removing that user from a set. No client can send an event name that starts with $, so these cannot be faked.
  • count is exact. users lists up to 1,000, sorted.
  • Joining and leaving use your connection's message rate, so a client that joins and leaves in a loop is rate limited. Presence messages are not counted against the app's message rate.
  • Your backend can ask too:
curl
curl "https://realtimehub.dev/api/channels/trips.21/presence?appKey=YOUR_APP_KEY" \
  -H "Authorization: Bearer YOUR_APP_SECRET"
Response
{"channel":"trips.21","count":2,"users":["ann","bob"]}
Laravel: presence
use Ohad\RealtimeHub\Facades\RealtimeHub;

$here = RealtimeHub::presence('trips.21');   // ['channel' => 'trips.21', 'count' => 2, 'users' => ['ann', 'bob']]

Each server keeps its own members in memory. When Redis is configured the servers share them, so a user connected to any server is listed, and a server that stops is dropped within a minute. A restart empties that server and its clients join again when they reconnect.

Try it live

The channels demo lets you test all three kinds of channel without writing code. Open it in two browsers, or in one normal and one private window, and connect as two different users.

  • Public. public.lobby is listed in everyone's token, so anyone can join and chat.
  • Private. private.room-a and private.room-b are joinable only when the token lists them. Try to join one you were not given and read the refusal in the event log. Switch the token to Open (no channel list) and the same join works.
  • Presence. Join presence.office in both browsers and watch the member list and the join and leave events update live.

The demo is a static page plus one small serverless function that asks the hub for tokens, the role your own backend plays. Its source is on GitHub.

From your server

Your backend can send a message to users without a connection. It calls the hub with the same app secret it uses for tokens.

curl
curl -X POST https://realtimehub.dev/api/send \
  -H "Authorization: Bearer YOUR_APP_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"appKey":"YOUR_APP_KEY","to":["42","57"],"event":"notification","payload":{"text":"Your order shipped"}}'
Response
{"id":"9f2c6e1a4b7d4c0a8e3d5b6a7c8d9e0f","timestampUtc":"2026-11-21T09:00:32.296Z","recipients":2}
Laravel: .env
REALTIMEHUB_URL=https://realtimehub.dev
REALTIMEHUB_APP_KEY=YOUR_APP_KEY
REALTIMEHUB_APP_SECRET=<the secret shown once>
Laravel: send
use Ohad\RealtimeHub\Facades\RealtimeHub;

// one user, or an array of up to 50
RealtimeHub::send($order->user_id, 'notification', ['text' => 'Your order shipped']);
RealtimeHub::send([$a->id, $b->id], 'notification', ['text' => 'New comment']);
  • to is one user id or an array of up to 50. The receiver gets the message in onEvent with from set to $server. No client can use that id, so a message from $server always came from your backend.
  • recipients in the response is how many users the message was accepted for. The hub cannot tell whether a user is online, so it does not mean that many people received it. A user who is offline does not get it later.
  • The same rules apply as for a client message: event names, 32 KB payload, schemas and strict mode.
  • Each recipient counts as one message against the app's rate (100 a second by default). A call that would pass the limit is refused whole, and nothing is sent.
  • Messages you send are not saved to your database and are not sent to your webhook, so they never come back to your own server.
  • A wrong key or secret, a paused app and a suspended account all return 401. A bad request returns 400 with the reason in error, a payload over 32 KB returns 413, and the rate limit returns 429.

Allowed origins. (08)

A browser can only connect from a website you list on the app: scheme, host and port, no path. For example https://app.example.com or http://localhost:3000. An app can list 20.

Mobile apps and servers send no Origin header and are accepted on the strength of the token alone.

Schemas. (09)

Give an event a JSON Schema and every payload for that event is checked before delivery. A payload that does not match is rejected, and the sender gets the reason.

Schema for the event chat
{
  "type": "object",
  "required": ["text"],
  "properties": {
    "text": { "type": "string", "minLength": 1, "maxLength": 500 },
    "replyTo": { "type": "string" }
  },
  "additionalProperties": false
}
What the sender sees
Payload does not match the schema for 'chat': /text: Value is "integer" but should be "string"
  • Define schemas in the dashboard, under the app's Schemas tab. The tester there runs the same check the hub runs.
  • An event with no schema accepts any payload. Turn on strict mode and an event with no schema is rejected.
  • A schema can be up to 64 KB and an app can describe up to 50 events.
  • $ref works for references inside the same schema, such as #/$defs/name. References to other URLs are refused.
  • The regular expression keywords pattern and patternProperties are not supported yet. Use enum, const, minLength, maxLength, minimum, maximum or type.

Get messages into Laravel. (10)

Live delivery forgets a message once it is delivered. To act on a message in your own backend, or to keep it, use the webhook. It fires the RealtimeEventReceived event in Laravel and saves to the realtime_events table by default.

Webhook. Nothing to run.

The hub sends each message to a URL in your app. Your app needs one route, which the package adds for you.

  1. Open the app's Persistence tab, enter your URL, for example https://yourapp.com/realtimehub/events, and turn the webhook on. The signing secret is shown once.
  2. Install the Laravel package from GitHub.
  3. Put the signing secret in your .env. The route exists as soon as the secret is set.
  4. Press Send a test event on the Persistence tab. The result shows right there.
Install
composer config repositories.realtimehub vcs https://github.com/raheelshan/realtimehub-laravel
composer require ohad/realtimehub-laravel:^2.0

php artisan vendor:publish --tag=realtimehub-config
php artisan vendor:publish --tag=realtimehub-migrations
php artisan migrate
.env
REALTIMEHUB_WEBHOOK_SECRET=<the signing secret shown above>
React to a message
// app/Providers/AppServiceProvider.php, in boot()
Event::listen(\Ohad\RealtimeHub\Events\RealtimeEventReceived::class, function ($e) {
    match ($e->eventName) {
        'chat' => \App\Models\Message::create(['from' => $e->from, 'to' => $e->to, 'text' => $e->payload['text']]),
        default => null,
    };
});
  • The hub sends up to 50 messages in one request, in order, signed with your secret. The package checks the signature and the timestamp for you.
  • Delivery is at least once. A message can arrive twice, so use the message id as a key. The saved row already does.
  • If your server does not answer with a 2xx, the hub tries the same messages again after 30 seconds, 2 minutes, 10 minutes and 30 minutes. After the fifth failure it sets them aside, shows the count on the Persistence tab, and moves on.
  • Messages set aside after the fifth failure are counted on the Persistence tab. They are not sent again, so fix the cause of the failures quickly.
  • The test event is named realtimehub.test, and the package saves it like any other message.
  • Your listener runs while the hub waits, up to 10 seconds. Keep it quick. Put heavy work on a Laravel queue, which needs a queue worker.
  • Messages sent while no URL is saved are not delivered later. The hub starts from the moment you turn the webhook on.
  • An app that sends very fast while its server stays down for hours can lose the oldest messages, because the hub keeps about 10,000 per app.

Approve before delivery. (11)

By default a message is delivered at once and your server hears about it afterwards, through the webhook. If your server is down or slow, a user can hold a message your database never saved. Turn on Approve before delivery when your database must be the record: the hub asks your server first and delivers only after your server has saved the message.

The flow

  1. A user calls send. The hub runs its usual checks: token, rate limits, schema and payload size.
  2. The hub sends that one message to your approval URL and waits up to 3 seconds. The request is signed with the same secret as the webhook.
  3. Your app saves it and answers 2xx. The hub then delivers it to the recipient.
  4. Any other answer, or no answer in 3 seconds, and the hub delivers to nobody and the sender's send fails.

Nothing is delivered without a 2xx. The hub never retries and never keeps a message for later.

Request and response

The hub calls your URL
{
  "type": "approval",
  "appKey": "app_8f2c...",
  "eventId": "3f1b9c0e-6a52-4d7e-9c1a-2b7d5e8f0a14",
  "event": "chat",
  "from": "alice",
  "to": "bob",
  "payload": { "text": "hello" },
  "timestampUtc": "2026-11-25T09:00:32.2960000Z"
}
Your answer
200  { "recordId": 4812 }                                   deliver as sent
200  { "recordId": 4812, "payload": { "text": "hello" } }   deliver this payload instead
4xx  { "reason": "You are blocked" }                        deliver to nobody, show the sender the reason
5xx, no answer in 3 seconds                                 deliver to nobody, "Not sent: server unavailable"
  • recordId is required in a 2xx answer. It is a string or a number, and it reaches both users: the recipient in the message and the sender in the result of send, together with the eventId.
  • A 4xx answer shows its reason to the sender (up to 200 characters). Without one the sender sees "Rejected by server".
  • A payload in a 2xx answer is delivered instead of the one the user sent. It can be up to 32 KB and is not checked against a schema.
  • An approved message is not sent to the batch webhook, because your server already has it. It does not fire RealtimeEventReceived and is not written to realtime_events.
  • A message counts toward your package only when it is delivered.

Retry with the same eventId

Every send carries an eventId, 1 to 64 characters. The browser client makes one for you, and the error from a failed send has it as .eventId. Retry a failed send by passing the same eventId. If the first attempt was saved but the answer never arrived, your server sees the same eventId again and must not save it twice. Save with firstOrCreate on the eventId, as the generated approver does. When approval is on, a send without an eventId is refused.

JavaScript
try {
  const sent = await client.send('bob', 'chat', { text: 'hello' });   // sent.recordId is the id your server saved
} catch (e) {
  // Retry with the same eventId: your server saves it only once.
  await client.send('bob', 'chat', { text: 'hello' }, { eventId: e.eventId });
}

Set it up

  1. Open the app's Persistence tab, enter your approval URL, for example https://yourapp.com/realtimehub/approve, and turn on Approve before delivery. It uses the signing secret of the webhook, which is shown once if you have none yet.
  2. In Laravel, set the secret and turn the route on. Then generate an approver and map it to the event name.
.env
REALTIMEHUB_WEBHOOK_SECRET=<the signing secret>
REALTIMEHUB_APPROVAL_ENABLED=true
Generate an approver
php artisan realtimehub:approver ChatApprover

// config/realtimehub.php
'approvers' => ['chat' => App\Realtime\ChatApprover::class],
The approver
final class ChatApprover implements ApprovesMessages
{
    public function approve(ApprovalRequest $request): ApprovalResult
    {
        $message = DB::transaction(fn () => Message::firstOrCreate(
            ['event_id' => $request->eventId],
            ['from' => $request->from, 'to' => $request->to, 'body' => $request->payload['text']],
        ));

        return ApprovalResult::accept($message->id); // or ApprovalResult::reject('You are blocked')
    }
}
  • An event with no approver gets a 422 "Event not accepted", so only the events you map can be sent while approval is on.
  • If your approver throws, Laravel answers 500 and the sender is told "Not sent: server unavailable". Do not catch the exception and accept.
  • The hub only calls public https addresses and does not follow redirects, like the webhook.

The trade-off

If your Laravel app is down, sending stops. Nothing goes out of sync. Every message also waits for your server, so keep the approver quick.

Channel messages are not covered yet. They are delivered at once as before. Messages your backend sends are not covered either.

Errors and limits. (12)

Message from sendCause
Not connected to the hub.Call start() first, or wait for connected.
Rate limit exceeded.One connection sent more than 10 messages a second (burst 20).
App rate limit exceeded.All connections of the app together passed the app limit (100 a second, burst 200, by default).
Message limit reached for your package.Your account used all the messages its package allows (the free package allows 50 in total). Upgrade under Billing. Over HTTP, /api/send answers 402.
Invalid toUserId. / Invalid eventName.The id or the name uses characters outside the allowed set.
Join the channel before asking who is in it.Presence can only be asked for a channel you are in.
Join the channel before sending to it.A client can only send to channels it is in.
This token does not allow that channel.The token request listed channels and this one was not among them.
Payload exceeds 32768 bytes.The payload JSON is larger than 32 KB.
Payload does not match the schema for '<event>': ...The payload failed the schema. The text after the colon says where.
Event '<event>' has no schema and this app requires one.Strict mode is on and the event is not described.
App is not active.The app was paused or the account was suspended.
Not sent: server unavailableApprove before delivery is on and your server answered 5xx or did not answer within 3 seconds. Nothing was delivered. Retry with the same eventId.
Rejected by server / your own reasonApprove before delivery is on and your server answered 4xx. The text is the reason it sent.
eventId is required (1-64 characters).Approve before delivery is on and the message had no eventId. The browser client always sends one.

Limits

Apps per account3
Open connections per app1,000
Messages per second per app100, burst 200
Messages per second per connection10, burst 20
Channels per connection20
Payload32 KB of JSON
Event schemas per app50, each up to 64 KB
Allowed origins per app20
Token requests300 a minute per address

The operator can raise the connection and message limits for an app. They are not editable from the dashboard.

Security. (13)

  • The secret stays on your backend. If it leaks, rotate it in the dashboard. The old one stops working at once.
  • Only the hash of the secret is stored. We cannot show it again, so keep a copy.
  • Use HTTPS for the hub and for your own site.
  • Take the user id for a token from your session. Never trust one sent by the browser.
  • Anything a user's browser sends can be forged, so treat a message from a user as untrusted input. Only a message from $server is guaranteed to come from your backend.
  • List only the origins you use. Remove http://localhost entries from a live app.
  • Webhook requests are signed with a secret only you and the hub know. Your app rejects any request with a wrong signature or a timestamp older than 5 minutes.
  • The hub only calls public https addresses. A webhook URL that points at a private network or a cloud metadata address is refused, and redirects are not followed.