Real-Time Laravel Security: Treat Every Browser Message as Hostile
Raheel Shan
November 30th, 2026 · 12 min read
Anything a user's browser sends can be forged. The only message your app can fully trust is one that came from your own server.
The hub's security page says exactly that, and everything in this article follows from it.
What the hub guarantees
Four facts you can build on:
-
fromcomes from the token. A browser cannot send as another user.
$serveris yours. Messages from your backend arrive withfromset to$server, and no client can use that id.
- Presence events are the hub's. They carry event names starting with
$, which a client cannot send.
- Only a hash of your secret is stored. The hub cannot show it again, so keep your own copy.
Everything else in a message, the payload, the channel name, the text, the to, is input from a stranger.
1. The token route
The token route decides who a browser is, and which channels it may join. Get it wrong and every other check is useless.
// wrong: the browser chooses who it is
'userId' => (string) $request->input('user_id'),
// right: the session chooses
'userId' => (string) auth()->id(),
Keep it behind auth. The token is valid for one hour by default, and you can set ttlSeconds between 60 and 86,400.
A token is checked when a connection opens. An already open connection keeps working after the token expires, and the docs do not describe the hub closing it. So token expiry is not a way to remove someone.
2. List the channels in the token
This is the control that decides who may listen.
'channels' => auth()->user()->rooms()
->pluck('rooms.id')
->map(fn ($id) => "room.$id")
->all(),
- A token with a list can join those channels and nothing else
- An empty list means no channels
- A token with no
channelskey at all means open mode, where any user can join any channel of your app
For rooms that come from your database, open mode is a data leak. A user types room.7 and listens in. Always send the key, even with an empty list.
A connection that asks for a channel its token does not allow is closed, and a joinChannel call fails with "This token does not allow that channel."
3. Check membership on the route that writes
The token covers reading. Writing goes through a Laravel route, and that route checks the same table:
Route::post('/rooms/{room}/messages', function (Request $request, Room $room) {
Gate::authorize('post', $room);
// validate, save, broadcast
})->middleware('auth');
The room id in the URL is a claim, and auth()->id() is the proof. Look up the claim against the proof on every request.
A removed member is the gap to know about. Removing a row from room_user stops their posts at once, since the route reads the table every time. It does not remove them from a live connection, and I found nothing that does. They keep receiving until they disconnect. Where that matters, send sensitive content to individuals with send() instead of to the channel.
4. Validate with schemas
Attach a JSON Schema to each event. The hub checks it before delivery and tells the sender why a message was refused.
{
"type": "object",
"required": ["text"],
"properties": {
"text": { "type": "string", "minLength": 1, "maxLength": 500 }
},
"additionalProperties": false
}
Three rules from the docs:
- Turn on strict mode, so an event with no schema is rejected
- A schema can be up to 64 KB, and an app can describe 50 events
patternandpatternPropertiesare not supported, so useenum,const,minLength,maxLength,minimum,maximum, ortype
Ephemeral events sent straight over a channel, like typing, need a schema too, with no properties. A schema is a first filter. It does not replace the checks in sections 2 and 3.
5. Escape what you render
A message from another user is text, so render it as text.
// wrong
li.innerHTML = m.payload.text;
// right
li.textContent = m.payload.text;
The hub does not clean the content. If one user sends <img src=x onerror=...> and another page puts it in innerHTML, that is stored cross-site scripting delivered over a socket. In Blade, {{ }} escapes for you, and {!! !!} does not.
6. Lock down origins
Each app has an allowed-origins list, up to 20 entries. An origin is the scheme, host, and port, with no path:
→ https://app.example.com → http://localhost:3000
Remove the localhost entries from a live app. Mobile apps and servers send no Origin header, so they are accepted on the token alone, which makes the token route more important, not less.
The docs do not mention wildcards, so list each origin you use.
7. The webhook
Your webhook is a public URL that writes to your database. It receives one-to-one messages. Protect it in layers.
- Signature. Each request carries
RealtimeHub-Signature: t=<unix>,v1=<hmac>. The package computes HMAC-SHA256 over the timestamp, a dot, and the raw body, and compares.
- Timestamp. A request more than 300 seconds old is refused, so keep your server clock accurate.
- Failures. A bad signature returns 401, a malformed body 400, and with no secret configured the route answers 500 and never accepts an unsigned request.
- Public https only. The hub refuses private network addresses and cloud metadata addresses, and does not follow redirects. A local development URL needs a tunnel.
- Answer within 10 seconds. Queue slow work.
- Expect duplicates. Delivery is at-least-once. A failed post retries after 30 seconds, 2, 10, and 30 minutes.
Handle duplicates with the event id, which is stable across redeliveries:
Schema::table('messages', function (Blueprint $t) {
$t->string('hub_event_id')->nullable()->unique();
});
// in the listener
Message::firstOrCreate(
['hub_event_id' => $e->eventId],
['from' => $e->from, 'to' => $e->to, 'text' => $e->payload['text']],
);
The built-in listener that fills realtime_events already does the same thing with insertOrIgnore on event_id.
8. Limits are abuse control
The hub enforces limits so one user cannot flood the rest:
- 10 messages per second per connection (burst 20)
- 100 messages per second per app (burst 200)
- 32 KB per payload
- 20 channels per connection
- 300 token requests per minute per address
When a client breaks one, send rejects with "Rate limit exceeded." or "App rate limit exceeded." Show that to the user. Joining and leaving channels use the connection's own rate, so a client cannot flood a room with presence events.
For your own broadcast, one rule matters: a server send that would pass the app limit is refused whole, and nothing is sent. The package throws RealtimeHubException, with the HTTP status in ->status (0 when the hub is unreachable). Catch it, log it, and rely on saved history to fill the gap:
try {
RealtimeHub::broadcast("room.{$room->id}", 'room.message', $payload);
} catch (RealtimeHubException $e) {
report($e);
}
9. Secrets
- The app secret (
rhs_) lives in.envon the server and nowhere in the browser or the repository
- If it leaks, rotate it in the dashboard and the old one stops working at once
- Use https for the hub and for your own site
The checklist
- Token route takes the user id from the session
- Token route is behind auth
- Token route always sends
channels, even when it is empty
- Write routes check membership with
auth()->id(), never an id from the payload
- Strict schemas on every event, including typing, with
additionalProperties: false
- Output escaped with
textContentor{{ }}
- Allowed origins list holds only live origins
- Webhook answers in under 10 seconds, and the listener is idempotent on
eventId
Broadcast failures are caught and logged
Secret rotated if it ever appears in a log or a screenshot
The rule
The hub proves who sent a message. The token decides who may listen, and your route decides who may speak. The browser decides nothing.
Try it: realtimehub.raheelshan.com/docs
Previous: Reverb, a Hub or Pusher? How to Pick a Laravel Real-Time Setup
Next: A React Native Chat Client for Your Laravel Real-Time Hub
Comment "LOCKED" and I'll send you the checklist as a one-page PDF.
Found this useful?
Support the work that goes into these posts.