Skip to content
Laravel Backend Software Architecture

A React Native Chat Client for Your Laravel Real-Time Signalr Hub

Raheel Shan

Raheel Shan

December 1st, 2026 · 11 min read

A React Native Chat Client for Your Laravel Real-Time Signalr Hub

The Laravel code from articles 5 to 9 does not change for a mobile app. Only the client does, and it is about 60 lines.

That is the payoff of a hub that holds the connection. Your backend never knew what kind of client was on the other end.

What changes on mobile

  • No cookie session, so the token route needs a bearer token (Sanctum)
  • No browser SDK, so you use the official SignalR client directly
  • No Origin header, so the token alone gates the connection
  • The OS suspends your socket when the app goes to the background

The first three are setup. The fourth is the real work.

The token route

The browser version used the session. A mobile app sends a Sanctum token instead, and the route lists the user's channels exactly as in article 6:

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

    $channels = auth()->user()->rooms()
        ->pluck('rooms.id')
        ->map(fn ($id) => "room.$id")
        ->all();

    return Http::withToken($hub['secret'])
        ->post($hub['url'].'/api/token', [
            'appKey'   => $hub['key'],
            'userId'   => (string) auth()->id(),
            'channels' => $channels,
        ])
        ->throw()
        ->json();
})->middleware('auth:sanctum');

Mobile clients send no Origin header, and the hub accepts them on the token alone, so this route is your only gate. Article 9 covers why that matters, including why channels must always be present.

Store the Sanctum token in secure storage (Keychain on iOS, Keystore on Android), not in AsyncStorage.

The client

npm install @microsoft/signalr@8

The browser SDK is a thin wrapper over the same library, and its source shows what the hub expects. These hub method names matter:

  • SendToUser(toUserId, eventName, payload) for one-to-one messages
  • SendToChannel(channel, eventName, payload) for a channel
  • JoinChannel(name) and LeaveChannel(name)
  • ReceiveEvent is the handler for every incoming message

The docs page lists the channel methods and not the user one, so I read the names from the browser SDK's source. Pin your client version and recheck them if the hub updates.

// hub.js
import { HubConnectionBuilder, LogLevel } from '@microsoft/signalr';

const REFRESH_MARGIN_MS = 30_000;

export function createHub({ hubUrl, fetchToken, onEvent, onStatus }) {
  let cached = null;
  const joined = new Set();   // the hub forgets channels when the connection drops

  const getToken = async () => {
    if (!cached || cached.expiresAt - Date.now() < REFRESH_MARGIN_MS) {
      const { token, expiresAtUtc } = await fetchToken();
      cached = { token, expiresAt: Date.parse(expiresAtUtc) };
    }
    return cached.token;
  };

  const connection = new HubConnectionBuilder()
    .withUrl(hubUrl, { accessTokenFactory: getToken })
    .withAutomaticReconnect([0, 2000, 5000, 10000, 30000])
    .configureLogging(LogLevel.Warning)
    .build();

  const rejoin = () => {
    joined.forEach((name) =>
      connection.invoke('JoinChannel', name).catch(() => joined.delete(name)));
  };

  connection.on('ReceiveEvent', onEvent);
  connection.onreconnecting(() => onStatus('reconnecting'));
  connection.onreconnected(() => { onStatus('connected'); rejoin(); });
  connection.onclose(() => { cached = null; onStatus('disconnected'); });

  return {
    async start() {
      onStatus('connecting');
      await connection.start();
      onStatus('connected');
      rejoin();
    },
    stop: () => { cached = null; return connection.stop(); },
    send: (to, event, payload) =>
      connection.invoke('SendToUser', to, event, payload),
    async joinChannel(name) {
      await connection.invoke('JoinChannel', name);
      joined.add(name);
    },
    async leaveChannel(name) {
      joined.delete(name);
      await connection.invoke('LeaveChannel', name);
    },
    sendToChannel: (channel, event, payload) =>
      connection.invoke('SendToChannel', channel, event, payload),
  };
}

The token cache refreshes 30 seconds before expiry, the same margin the browser SDK uses. accessTokenFactory runs on every negotiate, so a reconnect gets a fresh token on its own. stop() clears the cache, which matters in the next section.

Using it in a screen

const hub = useMemo(() => createHub({
  hubUrl: 'https://realtimehub.raheelshan.com/hub/chat',
  fetchToken: () => api.get('/hub-token').then((r) => r.data),
  onEvent: (m) => {
    if (m.channel !== `room.${roomId}`) return;
    if (m.event === 'room.message') addMessage(m.payload);
    if (m.event === 'typing' && m.from !== me) showTyping(m.from);
  },
  onStatus: setStatus,
}), []);

useEffect(() => {
  let active = true;

  hub.start()
    .then(() => active && hub.joinChannel(`room.${roomId}`))
    .catch(() => setStatus('disconnected'));

  return () => { active = false; hub.leaveChannel(`room.${roomId}`).catch(() => {}); hub.stop(); };
}, [hub, roomId]);

start() can reject when the first connection fails. withAutomaticReconnect only covers a connection that was up and dropped. The browser SDK adds its own retry loop for the first connect, and on mobile you add one too, because a user opening the app in a tunnel is normal.

If the user joins a new room through your API, the cached token does not list it and joinChannel fails. Call await hub.stop(); await hub.start(); first, as in article 6.

The background problem

When the app goes to the background, iOS and Android suspend your socket. When it comes back, the connection is dead or about to be.

import { AppState } from 'react-native';

useEffect(() => {
  const sub = AppState.addEventListener('change', async (state) => {
    if (state !== 'active') return;
    await hub.start().catch(() => {});
    await loadMissed();
  });
  return () => sub.remove();
}, [hub]);

Reconnecting is half the job. The hub does not deliver messages sent while you were away, and channel messages are not stored, so loadMissed() asks your own server:

Route::get('/rooms/{room}/messages', function (Room $room) {
    Gate::authorize('view', $room);

    return $room->messages()
        ->where('id', '>', request('after', 0))
        ->orderBy('id')
        ->limit(100)
        ->get();
})->middleware('auth:sanctum');

The app sends the id of the last message it has. This is the history table from article 6, now carrying the whole offline story.

Sending while the connection is down

Two kinds of message, two answers.

A durable message is an HTTP post to your own route. It does not depend on the socket at all, so queue it on the device and retry:

const outbox = [];

async function sendMessage(roomId, text) {
  try {
    return await api.post(`/rooms/${roomId}/messages`, { text });
  } catch {
    outbox.push({ roomId, text });
  }
}

async function flush() {
  while (outbox.length) {
    const next = outbox[0];
    await api.post(`/rooms/${next.roomId}/messages`, { text: next.text });
    outbox.shift();
  }
}

Show the message in the UI at once, marked as sending, and mark it sent when the post resolves. Your server broadcasts it, and the sender hears their own message, so dedupe on id.

An ephemeral message, like typing, goes over the channel with sendToChannel. When the connection is down, drop it. A typing indicator that arrives late is wrong.

The hub's per-connection limit is 10 messages per second. A long outbox flushed in a tight loop hits your own API's throttle first, so add a short delay between posts.

Push notifications for the closed app

A hub cannot wake a closed app. For that you need Apple and Google push (FCM or APNs).

Use RealtimeHub::presence() from article 7 to decide who needs one: members who are in the room already see the message, so notify only the others.

$presence = RealtimeHub::presence("room.{$room->id}");
$inRoom = collect($presence['users'])->map(fn ($id) => (int) $id);

$room->members()
    ->whereNotIn('users.id', $inRoom)
    ->each(fn ($user) => $user->notify(new NewRoomMessage($message)));

What to test on a device

  • Open the app, kill the network, restore it, and confirm status goes reconnecting then connected, and the channel is joined again
  • Send from a second user while the first app is in the background, then bring it forward, and confirm loadMissed() fills the gap
  • Post a message in airplane mode, restore the network, and confirm the outbox sends it once
  • Leave the app idle past the token lifetime and confirm a reconnect still works
  • Send 30 typing events quickly and confirm the rate limit error is handled and not a crash

I have not run @microsoft/signalr inside a React Native app for this series, so run these on a real iOS and Android device before you ship.

The result

  • The Laravel app is the same: one token route, one post route, a few tables
  • A web app and a mobile app share one hub and one set of rooms → History, push, and presence come from your own database and the hub

No socket server. No Redis. No second code path for mobile.

Try it: realtimehub.raheelshan.com/docs

Previous: Real-Time Laravel Security: Treat Every Browser Message as Hostile

Next: Real-Time Message Not Arriving? 8 Places It Dies in Laravel

Comment "MOBILE" and I'll send you the hub.js client and the AppState hook.

Found this useful?

Support the work that goes into these posts.

Support
Comments


Comment created and will be displayed once approved.