REACT NATIVE • IN-APP CHAT • STEP-BY-STEP
How to add in-app chat to a React Native app
Build real-time, room-based chat in React Native with the RTCExpress chat SDK from npm. You will have two devices sending messages to each other instantly, with recent history loaded when the chat opens, and no chat server, database or WebSocket code to write yourself.
1. What you need
- A working React Native Android setup (Node.js, JDK 17 and Android Studio). React Native 0.73 or newer.
- Two Android devices, or one Android phone and an Android emulator, on Android 7.0 (API 24) or newer.
- A free RTCExpress project. Its App ID is in the customer console.
Android is the supported platform for the React Native SDK today; iOS is experimental. The SDK is a native module, so it does not run in Expo Go; use a React Native CLI project.
2. Create an app and install the SDK
Create a new React Native project and add rtcexpress-react-native:
npx @react-native-community/cli@latest init ChatDemo
cd ChatDemo
npm install rtcexpress-react-nativeAutolinking adds the native module, so you don't edit Gradle files or AndroidManifest.xml. Chat needs no runtime permissions.
3. Create two test tokens
Log in to your customer console → Token tools and create two short-lived tokens in the same project and room:
- User ID alice, room ID chat-test.
- User ID bob, room ID chat-test.
Create config.ts next to App.tsx and paste in your App ID and both tokens:
// Test values from the console's Token tools.
// In a real app, fetch the token from your own backend. Never ship an App Secret.
export const SERVER_URL = 'https://api.devsquarelabs.com';
export const APP_ID = 'YOUR_APP_ID';
export const ROOM_ID = 'chat-test';
export const TOKENS: Record<'alice' | 'bob', string> = {
alice: 'ALICE_TOKEN',
bob: 'BOB_TOKEN',
};4. Write the chat screen
Replace App.tsx with this. It is the whole app: pick a user, connect, join a room, load recent messages, and send and receive new ones.
import React, { useEffect, useRef, useState } from 'react';
import { Button, FlatList, SafeAreaView, StyleSheet, Text, TextInput, View } from 'react-native';
import RTCExpress from 'rtcexpress-react-native';
import { APP_ID, ROOM_ID, SERVER_URL, TOKENS } from './config';
type User = 'alice' | 'bob';
type ChatMessage = { id: string; from: string; text: string };
type MessagePayload = { fromUserId: string; text: string; sentAt: number };
type StoredMessage = { id: string; fromUserId: string; text: string };
export default function App() {
const rtc = useRef(new RTCExpress()).current;
const userRef = useRef<User | null>(null);
const [me, setMe] = useState<User | null>(null);
const [status, setStatus] = useState('Pick a user');
const [joined, setJoined] = useState(false);
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [draft, setDraft] = useState('');
useEffect(() => {
rtc.on('roomJoined', () => {
setJoined(true);
setStatus(`Joined ${ROOM_ID}`);
if (userRef.current) {
loadHistory(TOKENS[userRef.current]).catch((e) => setStatus(`Could not load history: ${e.message}`));
}
});
// Messages from the other people in the room.
rtc.on('message', (p) => {
const m = p as MessagePayload;
setMessages((list) => [...list, { id: `live-${m.sentAt}-${list.length}`, from: m.fromUserId, text: m.text }]);
});
rtc.on('error', (p) => setStatus(`Error: ${(p as { message: string }).message}`));
return () => rtc.destroy();
}, [rtc]);
// Reads the last 50 messages with the same user token. Call it after roomJoined.
async function loadHistory(token: string) {
const res = await fetch(`${SERVER_URL}/v1/rooms/${encodeURIComponent(ROOM_ID)}/messages?limit=50`, {
headers: { Authorization: `Bearer ${token}` },
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const body = (await res.json()) as { messages: StoredMessage[] };
const stored = body.messages
.reverse() // the server returns the newest first
.map((m) => ({ id: m.id, from: m.fromUserId, text: m.text }));
setMessages((list) => [...stored, ...list]);
}
async function connect(user: User) {
userRef.current = user;
setMe(user);
setStatus('Connecting...');
try {
await rtc.init({ serverUrl: SERVER_URL, appId: APP_ID, userId: user, token: TOKENS[user] });
rtc.joinRoom(ROOM_ID);
} catch (e) {
setStatus(`Error: ${(e as Error).message}`);
}
}
function send() {
const text = draft.trim();
if (!text || !me) return;
rtc.sendMessage(text);
// The server sends your message to everyone else in the room, so add it here yourself.
setMessages((list) => [...list, { id: `me-${Date.now()}`, from: me, text }]);
setDraft('');
}
if (!me) {
return (
<SafeAreaView style={styles.pick}>
<Text style={styles.title}>Chat demo</Text>
<Button title="I am Alice" onPress={() => connect('alice')} />
<Button title="I am Bob" onPress={() => connect('bob')} />
</SafeAreaView>
);
}
return (
<SafeAreaView style={styles.screen}>
<Text style={styles.status}>{status}</Text>
<FlatList
style={styles.list}
data={messages}
keyExtractor={(m) => m.id}
renderItem={({ item }) => {
const mine = item.from === me;
return (
<View style={[styles.bubble, mine ? styles.mine : styles.theirs]}>
<Text>{mine ? item.text : `${item.from}: ${item.text}`}</Text>
</View>
);
}}
/>
<View style={styles.row}>
<TextInput
style={styles.input}
value={draft}
onChangeText={setDraft}
placeholder="Type a message"
editable={joined}
onSubmitEditing={send}
/>
<Button title="Send" onPress={send} disabled={!joined} />
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
pick: { flex: 1, padding: 24, justifyContent: 'center', gap: 12 },
title: { fontSize: 22, fontWeight: '600', textAlign: 'center' },
screen: { flex: 1, padding: 12 },
status: { textAlign: 'center', marginBottom: 8 },
list: { flex: 1 },
bubble: { padding: 10, borderRadius: 12, marginVertical: 4, maxWidth: '80%' },
mine: { alignSelf: 'flex-end', backgroundColor: '#c8efe8' },
theirs: { alignSelf: 'flex-start', backgroundColor: '#eee' },
row: { flexDirection: 'row', alignItems: 'center', gap: 8 },
input: { flex: 1, borderWidth: 1, borderColor: '#ccc', borderRadius: 8, paddingHorizontal: 10 },
});How it works
- init connects with a short-lived user token, and joinRoom asks to join the room. The
roomJoinedevent confirms membership; only then can the user send or read history. - sendMessage sends text to the current room. The server stores it and delivers it to everyone else in the room, so the app adds your own message to the list itself.
- The
messageevent fires for each new message from someone else, withfromUserId,textandsentAt. - History comes from the REST endpoint
GET /v1/rooms/{roomId}/messages, called with the same user token. It returns the newest messages first and anextCursor; pass it as?before=to load older pages. See the API reference. - destroy runs when the screen unmounts. It closes the connection and removes the event listeners.
5. Run it on two devices
Connect both devices and list them with adb devices. Start Metro in one terminal:
npx react-native startIn a second terminal, install the app on each device:
npx react-native run-android --deviceId FIRST_DEVICE_ID
npx react-native run-android --deviceId SECOND_DEVICE_ID- On the first device press I am Alice, and on the second press I am Bob. Wait for Joined chat-test.
- Type a message on Alice's device and press Send. It appears on Bob's device straight away.
- Reply from Bob, then reload the app on one device and pick the same user: the earlier messages load from history.
Troubleshooting
- Send button stays disabled: the app hasn't joined the room. Check the App ID and that the token is for room
chat-testand hasn't expired. - Messages don't arrive on the other device: both users must be in the same room, and the other app must be open and connected.
- "Could not load history: HTTP 403": the token is for a different room, or history was read before
roomJoined. - "rtcexpress-react-native doesn't seem to be linked": stop the app and run
npx react-native run-androidagain, and don't use Expo Go. - Error that the message limit is reached: the project used its included messages. See pricing.
6. Before you ship
Replace config.ts with a call to your own backend. Your server signs the user in, checks they may join the room (for example, a one-to-one chat between two users), and requests a short-lived token from POST https://api.devsquarelabs.com/v1/token with your App ID and App Secret; the Node.js server SDK does this in a few lines. The App Secret stays on the server.
Then add the parts every chat needs: a stable room ID per conversation (for example dm_alice__bob), loading older pages with nextCursor, a "sending…" state while offline, and push notifications for messages that arrive while the app is closed (see the push notification setup guide).
React Native chat questions
Do I need my own chat server or database?
No. RTCExpress hosts the real-time connection and stores message history. Your backend only issues tokens.
Can users call each other from the chat?
Yes. The same SDK makes voice and video calls in the same room: rtc.callUser('bob'). Follow the React Native voice calling tutorial to add a call button.
How are messages counted?
Each message sent counts once, however many people are in the room. The Free trial includes 10,000 messages in total, Starter 100,000 a month and Pro 500,000 a month. See pricing.
Can web and mobile users chat together?
Yes. The JavaScript in-app chat tutorial uses the same project, rooms and history, so a browser user and a phone user can chat in one room.