Skip to content

About

React Native and Expo hooks for Hibira and other Pusher-compatible servers: channels, presence, LLM streams and push notifications

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

@hibira-io/react-native

npm ci

React Native and Expo hooks for Hibira, or any Pusher-compatible server, plus push notifications through Hibira Push.

  • Channels: the hooks of @hibira-io/react (useEvent, usePresence, useTrigger, useStream...) on the React Native build of pusher-js.
  • Background aware: the connection closes in the background (after 30 s on iOS, at once on Android) and opens again when the app returns, so a phone in a pocket does not hold one of your plan's connections.
  • Payloads of any size: triggerChunked() and useChunkedTrigger() split what does not fit in one message (Free plans allow 4 KB) and useChunkedEvent() puts it back together.
  • Push notifications: registers the device's FCM / APNs token with Hibira Push (Beams-compatible) from expo-notifications, or from any other source of the native token. Interests, users and token refresh included.
  • Plain ESM with TypeScript types. Expo SDK 50+ and bare React Native 0.70+.

Install

npx expo install @hibira-io/react-native pusher-js @react-native-community/netinfo
# for push notifications:
npx expo install expo-notifications @react-native-async-storage/async-storage

In a bare React Native app use npm install with the same packages, then npx pod-install.

Setup

Wrap your app once. The app key is in the Hibira portal; it is public.

import { HibiraProvider } from '@hibira-io/react-native';

export default function App() {
  return (
    <HibiraProvider
      appKey={process.env.EXPO_PUBLIC_HIBIRA_KEY}
      options={{
        channelAuthorization: {
          endpoint: 'https://api.example.com/hibira/auth',
          transport: 'ajax',
          headersProvider: () => ({ Authorization: `Bearer ${session.token}` }),
        },
      }}
    >
      <Home />
    </HibiraProvider>
  );
}

options are pusher-js options merged over the Hibira defaults (wsHost: 'ws.hibira.io', TLS). For a server on your computer, set wsHost to its LAN address (not localhost, which is the phone itself), wsPort and forceTLS: false.

Prop Default
appKey app key from the portal
options pusher-js options
client an existing pusher-js client to use instead
backgroundTimeout 30000 ms in the background before the connection closes; null keeps it open. Android pauses JS timers in the background, so there the connection closes as soon as the app leaves the foreground

Subscriptions survive the background: they are made again when the connection comes back. Events sent while the app was away are not replayed, so refetch what matters when the app becomes active.

Allowed origins

Apps on Hibira need nothing in their allowed origins for React Native. React Native's WebSocket sends an Origin made from the socket URL (iOS https://ws.hibira.io, Android https://ws.hibira.io:443); Hibira knows that Origin as a native app's and does not apply the allowlist to it. A self-hosted pusher-server older than v0.2.26 does not, so there add both to the app's allowed origins (or upgrade).

Encrypted channels

private-encrypted- channels work as they are: the React Native build of pusher-js includes encryption. Your backend encrypts each event with its encryption master key (encryptionMasterKeyBase64 in the pusher package) and returns the channel's key from the auth endpoint; Hibira relays ciphertext it cannot decrypt. Client events are not allowed on encrypted channels.

Hooks

import { useEvent, usePresence, useTrigger, useConnectionState, useStream } from '@hibira-io/react-native';

function Orders() {
  const [orders, setOrders] = useState([]);
  useEvent('orders', 'order.created', (order) => setOrders((list) => [order, ...list]));
  return <OrderList orders={orders} />;
}

function Room({ id }) {
  const { others, count } = usePresence(`presence-room-${id}`);
  const trigger = useTrigger(`presence-room-${id}`);
  return <TextInput onChangeText={() => trigger('client-typing', {})} />;
}

usePusher, useChannel, useEvent, usePresence, useTrigger, useConnectionState and useStream behave exactly as in @hibira-io/react, including LLM streaming with streamToChannel() (import it from @hibira-io/react-native/server).

Payloads bigger than one message

The Free plan allows 4 KB per message. Send bigger payloads in chunks from your backend:

import Pusher from 'pusher';
import { triggerChunked } from '@hibira-io/react-native/server';

await triggerChunked(pusher, 'catalogue', 'catalogue.updated', { items });

and receive them whole in the app:

import { useChunkedEvent } from '@hibira-io/react-native';

useChunkedEvent('catalogue', 'catalogue.updated', (data) => setItems(data.items));

Client events work the same way, on private and presence channels with client events turned on:

const send = useChunkedTrigger('private-board-1');
await send('client-drawing', strokes); // true once every chunk is sent

A payload that fits is sent as one ordinary event, so other listeners (useEvent, the web SDKs) still get small events as they are. A bigger one becomes a run of events of at most 3500 bytes each (maxBytes), sent one after another; client events go out 110 ms apart to stay inside the 10 client events per second a connection may send. Each chunk counts as one message against the plan's daily messages, and payloads that would need more than 100 chunks (maxChunks) are refused. Chunks that never complete (the sender went away) are dropped after 30 s.

Other runtimes can use the same format from @hibira-io/react-native/chunk (chunkPayload, createChunkAssembler), which has no React Native imports.

Push notifications

Hibira Push delivers through FCM on Android and APNs on iOS, with a device API compatible with Pusher Beams. In the portal, turn on Push notifications for the app, upload your Firebase service account and APNs key, and copy the instance ID.

import { createExpoPush, useHibiraPush, TokenProvider } from '@hibira-io/react-native/expo';
import * as Application from 'expo-application';

const push = createExpoPush({
  instanceId: process.env.EXPO_PUBLIC_HIBIRA_PUSH_INSTANCE,
  bundleIdentifier: Application.applicationId, // iOS: the APNs topic
});

const tokenProvider = new TokenProvider({
  url: 'https://api.example.com/push-auth',
  headers: () => ({ Authorization: `Bearer ${session.token}` }),
});

function Notifications({ user }) {
  const { ready, error } = useHibiraPush(push, {
    interests: ['orders', `team-${user.teamId}`],
    userId: user.id,
    tokenProvider,
  });
  return ready ? null : <Text>{error?.message ?? 'Turning on notifications…'}</Text>;
}

createExpoPush() asks for notification permission on start(), registers the device's native token (getDevicePushTokenAsync(), not an Expo push token), keeps the device ID in AsyncStorage so a relaunch does not register again, and sends a new token when the system changes it. useHibiraPush(push, options) starts it while mounted (enabled: false waits, for example until after onboarding), keeps the device's interests equal to interests, and links userId.

Without the hook:

await push.start();                     // → device ID
await push.addDeviceInterest('news');
await push.setDeviceInterests(['news', 'sale-jp']);
await push.getDeviceInterests();
await push.setUserId('user-1', tokenProvider);
await push.stop();                       // on sign out: deletes the device
await push.getRegistrationState();       // PERMISSION_DENIED, PERMISSION_GRANTED_REGISTERED...

Your backend's token endpoint answers GET ?user_id=... with {"token": "..."}, made with generateToken(userId) of any Beams server SDK and the instance's secret key, after checking the signed-in user is that user. Publish with any Beams server SDK pointed at https://ws.hibira.io.

Notes:

  • Push needs a development build (npx expo run:ios, EAS Build), not Expo Go. Add "plugins": ["expo-notifications"] to app.json.
  • Android: put the Firebase project's google-services.json in the app (android.googleServicesFile in app.json). On Android 13+ create a notification channel with Notifications.setNotificationChannelAsync().
  • iOS: debug builds get development APNs tokens; set the instance's APNs environment to Development while you test from Xcode.
  • Showing notifications while the app is open is up to Notifications.setNotificationHandler().

Without Expo

HibiraPush from @hibira-io/react-native/push takes the token from anywhere, for example @react-native-firebase/messaging:

import messaging from '@react-native-firebase/messaging';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { HibiraPush } from '@hibira-io/react-native/push';

const push = new HibiraPush({
  instanceId: 'YOUR_INSTANCE_ID',
  storage: AsyncStorage,
  getToken: async () =>
    Platform.OS === 'ios'
      ? { platform: 'apns', token: await messaging().getAPNSToken() }
      : { platform: 'fcm', token: await messaging().getToken() },
});
messaging().onTokenRefresh((token) => push.updateToken(token));

Pass endpoint for a self-hosted server.

Chat

@hibira-io/react-native/chat is a client for the Hibira Chat API: conversations with stored history, live messages, edits, reactions, typing, read receipts and translations. Live events come from the provider's connection once the user is signed in (pusher.signin()), so there is nothing else to wire.

Your backend gives the app two things, both signed with the app secret:

  1. A user token for the HTTP calls: an HS256 JWT {"sub": userId, "exp": ...} (or one from the Chat API's POST /apps/{app_id}/chat/tokens).
  2. A user authentication endpoint for pusher.signin() (pusher.authenticateUser(socket_id, { id }) in the Node library), set as userAuthentication: { endpoint } in the provider's options.
import { HibiraProvider, usePusher } from '@hibira-io/react-native';
import { useChatClient, useChatConversation, useChatConversations, messageText } from '@hibira-io/react-native/chat';

<HibiraProvider appKey="YOUR_APP_KEY" options={{ userAuthentication: { endpoint: 'https://api.example.com/pusher/user-auth' } }}>
  <Chat />
</HibiraProvider>;

function Chat() {
  const pusher = usePusher();
  useEffect(() => pusher?.signin(), [pusher]);
  const chat = useChatClient({ appId: 'YOUR_APP_ID', token: () => api.fetchChatToken() });
  const { conversations, unread } = useChatConversations(chat);
  // ...
}

function Room({ chat, id }) {
  const room = useChatConversation(chat, id);
  return (
    <FlatList
      data={room.messages}
      keyExtractor={(m) => String(m.seq)}
      renderItem={({ item }) => <Text>{item.deleted_at ? 'Message deleted' : messageText(item, myLanguage)}</Text>}
      onStartReached={room.loadOlder}
      onViewableItemsChanged={() => room.markRead()}
      ListFooterComponent={room.typingUsers.length ? <Text>{room.typingUsers.join(', ')} typing…</Text> : null}
    />
  );
  // In the composer: onChangeText={() => room.typing()} and room.send(text).
}

The conversation re-reads its newest messages each time the connection comes back, so edits, deletes and reactions made while the app was in the background show up. The client has every user route (conversations, messages, search, send, edit, remove, react, report, read, typing, translate, setLanguage, upload from a picker's { uri }), and createConversationStore / createConversationListStore work without React. Set the user's language with chat.setLanguage('ja') and messages from others arrive translated a moment later; messageText(m, 'ja') picks the translation (translation needs a Chat add-on on the hosted service).

中文摘要:@hibira-io/react-native/chat 是 Hibira Chat API 的 React Native 用戶端。useChatClient 用 provider 的連線收 chat.* 即時事件(使用者需先 pusher.signin()),useChatConversation 提供單一對話的訊息、往前翻頁、輸入中、已讀與翻譯,重連後自動補齊;useChatConversations 提供含未讀數的對話列表。App 需要你的後端提供使用者 token(用 app secret 簽的 JWT)和使用者認證端點;建立對話、加成員仍由你的後端呼叫。

Example

example/ is an Expo app with a live order feed, presence, a chunked catalogue and push notifications.

Development

npm install
npm test            # unit tests, React Native stubbed
npm run typecheck
npm run test:e2e    # against a running server, see test/e2e/sdk.e2e.mjs

The android workflow builds e2e/android as a release APK and runs it on an Android emulator, driven from the host by e2e/android/backend.mjs. It checks the connection, chunked events both ways under a 4 KB limit, presence, the background disconnect and reconnect, and push registration. Each run goes against soketi first, and also against ws.hibira.io when these repository secrets are set:

Secret For
HIBIRA_E2E_APP_ID, HIBIRA_E2E_KEY, HIBIRA_E2E_SECRET a Free app with client events on (native Origin, 4 KB limit)
HIBIRA_E2E_PUSH_INSTANCE, HIBIRA_E2E_PUSH_SECRET a Hibira Push instance: registration, interests, delete
GOOGLE_SERVICES_JSON Firebase config for package io.hibira.e2e, with that project's service account uploaded to the push instance: real FCM delivery

Licence

MIT

About

React Native and Expo hooks for Hibira and other Pusher-compatible servers: channels, presence, LLM streams and push notifications

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages