
TL;DR
- A chat SDK gives you client-side building blocks for login, conversations, messages, media, unread counts, push, presence, and real-time events; a chat API gives your backend server-side control over users, auth, moderation, groups, and compliance workflows.
- The fastest production path is usually a managed chat messaging SDK plus a small backend that issues secure user signatures, maps your app users to chat users, and enforces business rules.
- For web apps, start with a javascript chat sdk and adapt it to React, Vue, Angular, or plain browser code; for mobile apps, choose native or cross-platform options such as Flutter, Swift, Android, or React Native.
- Social apps need more than basic text: typing indicators, read receipts, media messages, message recall, group chat, moderation, push notifications, offline sync, and scalable chat room architecture.
- Tencent RTC provides a production-ready Chat SDK, free Chat API tier, and official documentation so teams can ship reliable in-app chat without building a full real-time messaging stack from scratch.
Free Chat API — free forever: 1,000 MAU, no concurrency limits, push notifications included.
What Is a Chat SDK and How Is It Different from a Chat API?
A chat SDK is a client-side software development kit that helps you add real-time messaging to an application without implementing every networking, state management, media, and event-handling detail yourself. In practice, a chat SDK usually provides platform-specific libraries for web, iOS, Android, Flutter, React Native, Unity, or desktop apps. It handles the hard parts of in-app chat: connecting to the messaging service, logging users in, subscribing to message events, sending text and media messages, managing conversations, showing unread counts, reconnecting after network changes, and syncing state across devices.
A chat API, by contrast, is usually a backend-facing interface. Your server uses a chat API to create users, issue tokens, manage groups, apply moderation decisions, import history, export audit logs, trigger webhooks, and enforce rules that should not live on the client. If a chat SDK is the app-side toolkit, the chat API is the server-side control plane.
Most production apps need both. A social app, marketplace, livestreaming platform, education app, gaming community, or Web3 community may use a chat SDK on the client and a realtime chat API on the backend. The client SDK provides the real-time user experience. The backend API protects user identity, applies trust and safety rules, and connects chat events to your product database.
Here is the simplest mental model:
| Layer | Main user | Typical responsibilities | Example keyword fit |
|---|---|---|---|
| Chat SDK | Frontend or mobile developer | Login, send messages, render conversations, receive events, upload media, unread counts | chat sdk web, flutter chat sdk, javascript chat sdk, chat sdk swift |
| Chat API | Backend developer | Auth, token generation, user sync, group management, moderation, webhooks, compliance | chat api, api for chat application, laravel chat api |
| Chat UI kit | Product/frontend team | Prebuilt message list, input box, avatar, typing state, conversation list | in app chat sdk, best chat api |
| Push service | Mobile/backend team | Offline notifications, APNs, FCM, badge count, deep links | chat api for mobile app |
| Admin console | Ops/trust team | User ban, message audit, room management, analytics | chat room api, moderation API |
A chat SDK is not the same as a simple WebSocket wrapper. WebSockets are a transport protocol standardized in RFC 6455, while a chat SDK is an application-level toolkit built on top of one or more network transports. A good chat SDK abstracts connection recovery, message ordering, delivery state, offline caching, media upload, device notifications, and user-level permissions. Building all of that in-house can be expensive because the edge cases often appear only after launch: mobile network handoffs, duplicate messages, reconnection storms, unread count drift, and group chats with thousands of members.
A chat SDK is also not always a complete chat product. You still need to design your user experience, your conversation model, your moderation policy, and your data retention rules. For example, a dating app may need one-to-one conversations unlocked after matching. A live commerce app may need a large public chat room plus host moderation. A healthcare app may need stricter audit and retention controls. A game may need both text chat and voice chat through Tencent RTC GVoice.
If you are adding chat to a social app, the practical question is not “SDK or API?” The better question is: “Which responsibilities should live in the client SDK, which should live in my backend, and which should be delegated to a managed chat service?” This guide walks through that decision.
For implementation details, Tencent RTC offers official Chat SDK documentation here: TRTC Chat SDK documentation. For SDK downloads and platform setup, see TRTC SDK download documentation.
Core Real-Time Chat Features Social Apps Need
The minimum version of real-time chat is simple: a user types a message, taps send, and another user sees it quickly. But a production social app needs a larger feature set because users expect chat to behave like the messaging apps they use every day.
The exact feature list depends on your app category, but most social products should evaluate a chat SDK against the following capabilities.
One-to-One Messaging
One-to-one chat is the foundation for dating apps, marketplaces, creator communities, tutoring platforms, telehealth apps, customer support, and private social networks. The SDK should make it easy to create or fetch a direct conversation, send a text message, receive new messages, and update read status.
Key requirements include:
- Stable conversation IDs
- Message delivery state
- Read receipts
- Typing indicators
- User block or mute state
- Push notifications for offline recipients
- Multi-device sync when the same user logs in on more than one device
A basic in app chat SDK should handle these without requiring your team to design every event from scratch.
Group Chat and Chat Rooms
Group chat is different from one-to-one chat because scale and permissions become more complex. A small private group may have ten members. A fan community may have thousands. A live event chat room may have bursts of messages and reactions during peak moments.
A strong chat room api should support:
- Group creation and deletion
- Member invite, join, kick, mute, and role changes
- Owner, admin, member, and guest roles
- Message rate limits
- Large-group fanout
- Join and leave events
- System messages
- Searchable or paginated history
- Moderation actions
For livestreaming or real time live chat, message throughput and anti-spam controls matter as much as basic delivery. If chat becomes noisy, your app’s social experience suffers.
Media Messages
Modern chat is visual. Users expect images, short videos, voice notes, file attachments, stickers, emoji reactions, and rich cards. A chat messaging SDK should provide media message creation and upload workflows, not just plain text.
When evaluating media support, check:
- Maximum file size
- Image compression behavior
- Video thumbnail support
- File upload security
- CDN delivery
- Content moderation integration
- Retry behavior on weak mobile networks
- Message preview rendering
For privacy-sensitive apps, confirm whether media URLs are public, signed, expiring, or access-controlled.
Offline Sync and Message History
Real-time chat must also work when users are not online. A reliable SDK should reconnect and sync missed messages after the app resumes. Mobile apps especially need predictable lifecycle handling because users switch apps, lose signal, receive calls, or go offline.
Offline requirements include:
- Local message cache
- Server-side history
- Pagination for older messages
- Deduplication after reconnect
- Timestamp consistency
- Unread count reconciliation
- Multi-device state sync
If you build this yourself on a raw realtime chat api, test aggressively. Many chat bugs are state bugs, not send-message bugs.
Typing Indicators, Presence, and Read Receipts
These features make chat feel alive. Typing indicators tell users the other person is responding. Presence shows online, offline, or last-seen status. Read receipts reduce uncertainty.
However, these features also create privacy and performance considerations. Presence can become expensive if every user subscribes to every other user. Read receipts can trigger many small writes. A good chat SDK should provide efficient event models and let you configure which features are appropriate for your product.
For example, a workplace collaboration app may show detailed presence, while a dating app may choose approximate presence to protect privacy.
Push Notifications
Push is essential for mobile chat. Without push, users miss messages and churn. Apple’s push notification service documentation is available from Apple Developer, and Android push delivery is commonly implemented through Firebase Cloud Messaging. Web apps can also use the W3C Push API for browser notifications.
When choosing a chat api for mobile app development, ask:
- Does the provider support APNs and FCM?
- Can you customize notification payloads?
- Are badge counts handled automatically?
- Can notifications deep link into a conversation?
- Can muted conversations suppress push?
- Are push tokens refreshed correctly?
Tencent RTC Chat includes push notification support in the free tier referenced above, which is useful for early-stage apps that need mobile engagement without a separate push architecture.
Moderation, Safety, and Compliance
Social chat needs trust and safety. Moderation requirements vary by region, audience, and content type, but most products need at least user reporting, blocking, message deletion, and admin controls.
Security guidance should align with recognized frameworks such as the OWASP Mobile Application Security Verification Standard for mobile apps and the NIST Digital Identity Guidelines for authentication and identity proofing. These sources do not replace legal advice, but they provide useful engineering baselines for secure app design.
Moderation features to consider include:
- Profanity filters
- Spam detection
- Image moderation
- URL detection
- User report flows
- Admin message recall
- Mute or ban actions
- Audit logs
- Rate limiting
- Role-based permissions
The earlier you define your moderation model, the easier your chat SDK integration becomes. Retrofitting safety after launch is always harder.
How to Choose the Best Chat SDK or Chat API for Your App
The best chat api or chat SDK is not the one with the longest feature list. It is the one that fits your product model, platform mix, backend architecture, compliance needs, and team size. A small team building a social MVP has different needs than a global platform with enterprise governance.
Use the following selection matrix to compare vendors or decide whether to build in-house.
| Evaluation area | What to check | Why it matters |
|---|---|---|
| Platform coverage | Web, iOS, Android, Flutter, React Native, Unity | Avoid separate messaging stacks per platform |
| Real-time reliability | Reconnect, offline sync, message ordering, delivery callbacks | Chat quality depends on edge cases |
| Feature depth | Groups, media, reactions, read receipts, typing, push | Social apps need more than text |
| Backend APIs | User management, groups, tokens, webhooks, moderation | Your server must control identity and policy |
| Security | Token auth, role permissions, TLS, audit capability | Chat contains user-generated content |
| Scalability | Large groups, high concurrency, multi-region delivery | Growth can break naive chat systems |
| Developer experience | Docs, SDK examples, UI kits, logs, error codes | Faster integration and lower maintenance |
| Pricing | Free tier, MAU pricing, message volume, storage, push | Chat cost should scale predictably |
| Data governance | Retention, export, deletion, regional requirements | Important for regulated or global apps |
| Extensibility | Custom messages, metadata, webhooks, bots | Lets chat support product-specific workflows |
Match the SDK to Your Product Type
A dating app usually prioritizes direct messaging, safety, media moderation, and push. A marketplace needs buyer-seller chat, order metadata, file sharing, and dispute records. A livestreaming app needs high-volume chat rooms, host moderation, and message rate control. A gaming app may need text chat plus low-latency voice through GVoice. A Web3 community may need token-gated rooms, wallet-linked profiles, and event-based notifications; teams exploring this pattern can review Tencent RTC Web3 solutions.
Before comparing vendors, write down:
- Your user roles
- Conversation types
- Required message types
- Moderation model
- Push notification rules
- Expected launch platforms
- Regions you plan to serve
- Data retention needs
This prevents you from choosing a chat SDK based on a demo rather than your actual architecture.
Decide What You Will Not Build
A common mistake is underestimating the maintenance burden of chat. The first prototype may take a few days with WebSockets. The production version requires much more: reconnection, offline cache, unread counts, media upload, push, abuse controls, rate limits, backfills, monitoring, and customer support tools.
If chat is not your core infrastructure differentiator, a managed chat SDK usually gives a better return. Your team can focus on product-specific experiences such as matching, community ranking, creator monetization, virtual events, AI companions, or learning workflows.
Validate the Developer Experience
When testing a chat SDK, do not stop after sending one message. Build a small proof of concept that includes:
- Login with your real auth model
- Direct conversation
- Group conversation
- Offline push
- Media upload
- Message history pagination
- User blocking
- Logout and cleanup
- App restart and reconnect
- Error handling
A good SDK should make this straightforward and well documented. If the proof of concept is fragile, production will be harder.
Web Chat SDK Options: JavaScript, Angular, and Browser-Based Chat
For web apps, the most common choice is a javascript chat sdk that can be used in React, Vue, Angular, Next.js, Nuxt, Svelte, or plain browser applications. Even if a vendor advertises a React SDK or Angular SDK, the underlying layer is often a JavaScript SDK plus UI bindings.
Tencent RTC Chat for web uses the @tencentcloud/chat package. The following example shows a minimal browser or modern frontend setup with Vite. It logs in, listens for SDK readiness and incoming messages, sends a direct text message, and logs out cleanly.
Runnable Web Example: JavaScript Chat SDK
Install dependencies:
npm create vite@latest trtc-chat-web -- --template vanilla
cd trtc-chat-web
npm install @tencentcloud/chat tim-upload-plugin
npm run devCreate src/main.js:
import TencentCloudChat from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';
const SDKAppID = Number(import.meta.env.VITE_TRTC_SDK_APP_ID);
const userID = import.meta.env.VITE_TRTC_USER_ID;
const userSig = import.meta.env.VITE_TRTC_USER_SIG;
const peerUserID = import.meta.env.VITE_TRTC_PEER_USER_ID;
const app = document.querySelector('#app');
app.innerHTML = `
<main style="font-family: system-ui; max-width: 720px; margin: 40px auto;">
<h1>TRTC Web Chat Demo</h1>
<p>Status: <strong id='status'>initializing</strong></p>
<textarea id='messageText' rows="4" style="width:100%;">Hello from TRTC Chat SDK</textarea>
<button id='sendBtn'>Send message</button>
<button id='logoutBtn'>Logout</button>
<h2>Messages</h2>
<ul id='messages'></ul>
</main>
`;
const statusEl = document.querySelector('#status');
const listEl = document.querySelector('#messages');
const sendBtn = document.querySelector('#sendBtn');
const logoutBtn = document.querySelector('#logoutBtn');
const messageText = document.querySelector('#messageText');
const chat = TencentCloudChat.create({ SDKAppID });
chat.setLogLevel(1);
chat.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin });
function addMessage(text) {
const li = document.createElement('li');
li.textContent = text;
listEl.prepend(li);
}
chat.on(TencentCloudChat.EVENT.SDK_READY, () => {
statusEl.textContent = 'ready';
addMessage('SDK is ready. You can send a message.');
});
chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, (event) => {
for (const message of event.data) {
const text = message.payload?.text || JSON.stringify(message.payload);
addMessage(`From ${message.from}: ${text}`);
}
});
chat.on(TencentCloudChat.EVENT.ERROR, (event) => {
console.error('Chat SDK error:', event.data);
statusEl.textContent = `error: ${event.data.message || event.data.code}`;
});
async function login() {
if (!SDKAppID || !userID || !userSig) {
throw new Error('Missing VITE_TRTC_SDK_APP_ID, VITE_TRTC_USER_ID, or VITE_TRTC_USER_SIG');
}
await chat.login({ userID, userSig });
statusEl.textContent = 'logged in';
}
sendBtn.addEventListener('click', async () => {
const text = messageText.value.trim();
if (!text) return;
const message = chat.createTextMessage({
to: peerUserID,
conversationType: TencentCloudChat.TYPES.CONV_C2C,
payload: { text }
});
const result = await chat.sendMessage(message);
addMessage(`Me: ${result.data.message.payload.text}`);
messageText.value = '';
});
logoutBtn.addEventListener('click', async () => {
await chat.logout();
statusEl.textContent = 'logged out';
addMessage('Logged out and connection closed.');
});
login().catch((error) => {
console.error(error);
statusEl.textContent = error.message;
});Create .env.local:
VITE_TRTC_SDK_APP_ID=YOUR_SDKAPPID
VITE_TRTC_USER_ID=alice
VITE_TRTC_USER_SIG=USER_SIG_FROM_YOUR_SERVER
VITE_TRTC_PEER_USER_ID=bobThis example uses a generated userSig. Do not hardcode production secrets in the browser. Your backend should generate short-lived credentials after verifying your own app session. The backend pattern is covered later in this guide.
Adapting the JavaScript SDK to React, Vue, or Angular
A chat sdk web integration usually follows the same lifecycle in any frontend framework:
- Create the chat instance once.
- Register plugins and event listeners.
- Log in after your app auth is ready.
- Store conversations and messages in framework state.
- Send messages through SDK methods.
- Unsubscribe from events and log out when needed.
For real time chat angular, place SDK initialization in an Angular service rather than directly inside a component. The service can expose RxJS streams for messages, conversations, and unread counts. Components subscribe to the streams and render UI. This keeps your chat connection stable when routes change.
A simplified Angular service structure looks like this:
import { Injectable, OnDestroy } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import TencentCloudChat from '@tencentcloud/chat';
@Injectable({ providedIn: 'root' })
export class ChatService implements OnDestroy {
private chat = TencentCloudChat.create({
SDKAppID: Number(window.localStorage.getItem('SDKAppID'))
});
public messages$ = new BehaviorSubject<any[]>([]);
public ready$ = new BehaviorSubject<boolean>(false);
constructor() {
this.chat.on(TencentCloudChat.EVENT.SDK_READY, () => {
this.ready$.next(true);
});
this.chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, (event: any) => {
this.messages$.next([...event.data, ...this.messages$.value]);
});
}
login(userID: string, userSig: string) {
return this.chat.login({ userID, userSig });
}
async sendText(to: string, text: string) {
const message = this.chat.createTextMessage({
to,
conversationType: TencentCloudChat.TYPES.CONV_C2C,
payload: { text }
});
return this.chat.sendMessage(message);
}
async ngOnDestroy() {
await this.chat.logout();
}
}In React, the equivalent pattern is a context provider or custom hook. In Vue, use a composable. The important point is to keep chat connection management out of deeply nested UI components.
Browser Constraints You Should Plan For
Browser chat has a few constraints that mobile developers sometimes forget:
- Tabs can be suspended by the browser.
- Users may open the same account in multiple tabs.
- Network changes can interrupt WebSocket connections.
- Browser push notifications require permission and service worker setup.
- File uploads need CORS and size validation.
- Frontend bundles must not include secret keys.
For web apps, a chat SDK should expose clear connection state events so your UI can show “connecting,” “reconnecting,” or “offline” states. This matters for trust: users are more tolerant of network issues when the app explains what is happening.
Mobile Chat SDK Options: Flutter, Swift, React Native, and Android
Mobile chat is harder than web chat because devices sleep, networks change, push tokens expire, and operating systems enforce background restrictions. A mobile chat SDK should provide stable lifecycle handling and first-class platform support.
Flutter Chat SDK
A flutter chat sdk is ideal when your team wants one UI codebase for iOS and Android. Flutter is especially useful for social apps that need fast iteration and a custom interface. When evaluating Flutter support, check whether the SDK provides native push integration, media picker support, local cache, and platform-specific configuration for APNs and FCM.
A typical Flutter architecture includes:
- Auth service for your app session
- Chat credential endpoint
- Chat repository wrapping SDK calls
- State management with Provider, Riverpod, Bloc, or GetX
- Conversation list screen
- Message list screen
- Push notification handler
Even if you use cross-platform UI, keep mobile push setup explicit. APNs and FCM have separate certificates, tokens, payload formats, and testing workflows.
Runnable Mobile-Oriented Example: React Native Chat API Client
Many teams use React Native for social apps. The exact SDK package depends on your selected platform support, but the architecture is consistent: request a chat credential from your backend, initialize the SDK, then send and receive events. The following example shows a runnable React Native screen using the JavaScript SDK pattern in an Expo-compatible project for environments that support the required runtime APIs.
Install:
npx create-expo-app trtc-chat-rn
cd trtc-chat-rn
npm install @tencentcloud/chat tim-upload-plugin
npx expo startCreate App.js:
import React, { useEffect, useMemo, useState } from 'react';
import { Button, FlatList, SafeAreaView, Text, TextInput, View } from 'react-native';
import TencentCloudChat from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';
const SDKAppID = Number(process.env.EXPO_PUBLIC_TRTC_SDK_APP_ID);
const API_BASE = process.env.EXPO_PUBLIC_API_BASE;
const userID = 'alice';
const peerUserID = 'bob';
export default function App() {
const [ready, setReady] = useState(false);
const [text, setText] = useState('Hello from React Native');
const [messages, setMessages] = useState([]);
const chat = useMemo(() => {
const instance = TencentCloudChat.create({ SDKAppID });
instance.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin });
return instance;
}, []);
useEffect(() => {
const handleReady = () => setReady(true);
const handleMessage = (event) => {
const incoming = event.data.map((message) => ({
id: message.ID,
text: message.payload?.text || '[non-text message]',
from: message.from
}));
setMessages((current) => [...incoming, ...current]);
};
chat.on(TencentCloudChat.EVENT.SDK_READY, handleReady);
chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, handleMessage);
async function start() {
const res = await fetch(`${API_BASE}/chat/user-sig?userID=${encodeURIComponent(userID)}`);
const data = await res.json();
await chat.login({ userID, userSig: data.userSig });
}
start().catch(console.error);
return () => {
chat.off(TencentCloudChat.EVENT.SDK_READY, handleReady);
chat.off(TencentCloudChat.EVENT.MESSAGE_RECEIVED, handleMessage);
chat.logout().catch(console.error);
};
}, [chat]);
async function send() {
const message = chat.createTextMessage({
to: peerUserID,
conversationType: TencentCloudChat.TYPES.CONV_C2C,
payload: { text }
});
const result = await chat.sendMessage(message);
setMessages((current) => [
{ id: result.data.message.ID, text, from: 'me' },
...current
]);
setText('');
}
return (
<SafeAreaView style={{ flex: 1, padding: 20 }}>
<Text style={{ fontSize: 22, fontWeight: '700' }}>
TRTC React Native Chat
</Text>
<Text>Status: {ready ? 'ready' : 'connecting'}</Text>
<View style={{ flexDirection: 'row', marginVertical: 16 }}>
<TextInput
value={text}
onChangeText={setText}
style={{ borderWidth: 1, flex: 1, padding: 8 }}
/>
<Button title="Send" onPress={send} disabled={!ready || !text} />
</View>
<FlatList
data={messages}
keyExtractor={(item) => item.id}
renderItem={({ item }) => (
<Text style={{ paddingVertical: 6 }}>
{item.from}: {item.text}
</Text>
)}
/>
</SafeAreaView>
);
}Create .env:
EXPO_PUBLIC_TRTC_SDK_APP_ID=YOUR_SDKAPPID
EXPO_PUBLIC_API_BASE=http://localhost:3000This is a minimal react native chat api pattern. For production, validate runtime compatibility, configure native push, handle app foreground and background transitions, and test on physical devices.
Swift Chat SDK and Native iOS
A chat sdk swift integration is usually the best option when your iOS app is fully native, needs deep platform integration, or uses native UI patterns. Native iOS development gives you more direct control over:
- APNs token registration
- Background notification handling
- Keychain storage
- Media picker permissions
- UIKit or SwiftUI chat interfaces
- Accessibility behavior
- Performance profiling with Xcode
The backend responsibilities remain the same: your server authenticates the app user and returns a chat credential. The iOS client should never contain your secret key.
Android Chat SDK
For Android, the best chat api for android usually means an SDK that handles network changes, lifecycle events, push token updates, and media permissions cleanly. Android fragmentation makes testing important. Test on multiple OS versions, screen sizes, and network conditions.
Native Android considerations include:
- Runtime permissions for camera, microphone, and media files
- FCM token refresh
- Notification channels
- Background execution limits
- Local database size
- ProGuard or R8 configuration
- App links for notification deep linking
If your app also includes live audio or video, combine chat with TRTC Call documentation or TRTC Live documentation depending on whether your experience is calling or livestreaming.
Backend and Chat API Considerations: Laravel, Chat Rooms, Auth, and Moderation
Your backend is the trust boundary. It should decide who the user is, what they can access, which rooms they can join, and what moderation actions are allowed. The client SDK should not make policy decisions that a malicious user could bypass.
Secure UserSig Generation with Node.js
Tencent RTC Chat uses a user signature model. Your server generates a userSig after authenticating your app user. The server owns the secret key. The client receives only a limited credential.
Install:
mkdir trtc-chat-auth-server
cd trtc-chat-auth-server
npm init -y
npm install express cors dotenv tls-sig-api-v2
node server.jsCreate .env:
PORT=3000
TRTC_SDK_APP_ID=YOUR_SDKAPPID
TRTC_SECRET_KEY=YOUR_SECRET_KEY
TRTC_SIG_EXPIRE_SECONDS=3600Create server.js:
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import TLSSigAPIv2 from 'tls-sig-api-v2';
dotenv.config();
const app = express();
app.use(cors());
app.use(express.json());
const sdkAppId = Number(process.env.TRTC_SDK_APP_ID);
const secretKey = process.env.TRTC_SECRET_KEY;
const expire = Number(process.env.TRTC_SIG_EXPIRE_SECONDS || 3600);
if (!sdkAppId || !secretKey) {
throw new Error('Missing TRTC_SDK_APP_ID or TRTC_SECRET_KEY');
}
const api = new TLSSigAPIv2.Api(sdkAppId, secretKey);
// Demo authentication middleware.
// Replace this with your real session, JWT, or OAuth validation.
function requireAppUser(req, res, next) {
const requestedUserID = req.query.userID || req.body.userID;
if (!requestedUserID) {
return res.status(400).json({ error: 'userID is required' });
}
req.appUser = {
id: String(requestedUserID),
role: 'member'
};
next();
}
app.get('/chat/user-sig', requireAppUser, (req, res) => {
const userID = req.appUser.id;
const userSig = api.genUserSig(userID, expire);
res.json({
SDKAppID: sdkAppId,
userID,
userSig,
expireAt: Math.floor(Date.now() / 1000) + expire
});
});
app.post('/chat/moderation/report', requireAppUser, (req, res) => {
const { messageID, reason } = req.body;
if (!messageID || !reason) {
return res.status(400).json({ error: 'messageID and reason are required' });
}
// Store this in your database and trigger your review workflow.
console.log('New moderation report', {
reporter: req.appUser.id,
messageID,
reason,
createdAt: new Date().toISOString()
});
res.json({ ok: true });
});
app.listen(process.env.PORT || 3000, () => {
console.log(`Chat auth server running on port ${process.env.PORT || 3000}`);
});If your project uses CommonJS instead of ES modules, update package.json with "type": "module" or convert imports to require.
This backend gives you a safe credential endpoint and a placeholder moderation report endpoint. In production, add your real authentication middleware, rate limits, logging, and audit storage.
Laravel Chat API Pattern
A laravel chat api follows the same design. Laravel authenticates your user, maps the Laravel user ID to the chat user ID, and returns a short-lived signature. The exact PHP package and signature implementation should follow the current Tencent RTC documentation, but the controller pattern is:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ChatCredentialController extends Controller
{
public function show(Request $request)
{
$user = Auth::user();
if (!$user) {
return response()->json(['message' => 'Unauthenticated'], 401);
}
$sdkAppId = (int) config('services.trtc.sdk_app_id');
$secretKey = config('services.trtc.secret_key');
$expireSeconds = 3600;
// Generate UserSig on the server using Tencent RTC's official algorithm
// or a maintained server-side helper that matches the documentation.
$userSig = app('trtc.usersig')->generate(
(string) $user->id,
$sdkAppId,
$secretKey,
$expireSeconds
);
return response()->json([
'SDKAppID' => $sdkAppId,
'userID' => (string) $user->id,
'userSig' => $userSig,
'expireAt' => now()->addSeconds($expireSeconds)->timestamp,
]);
}
}Your Laravel routes can then expose:
Route::middleware('auth:sanctum')->get('/chat/credential', [ChatCredentialController::class, 'show']);The client calls /chat/credential after login and uses the returned values to initialize the chat SDK.
Authentication and Authorization
A secure api for chat application should separate app authentication from chat authentication:
- App authentication verifies the user with your system.
- Chat credential generation maps that verified user to a chat identity.
- Chat authorization determines what conversations or rooms the user may access.
Do not let a client request credentials for any arbitrary user ID. If your app user is 123, the backend should issue credentials only for 123 or for a carefully controlled mapped ID such as prod_user_123.
For group chat and rooms, enforce access at two levels:
- Your product database decides whether the user should be allowed to join.
- The chat service group membership reflects that decision.
This is especially important for paid communities, classrooms, private events, token-gated spaces, and age-restricted products.
Moderation Workflow
Moderation should be designed as a workflow, not a single API call. A practical flow is:
- User reports a message.
- Client sends report to your backend.
- Backend stores report with reporter, target user, message ID, reason, and timestamp.
- Automated filters classify urgency.
- Admin dashboard reviews the content.
- Backend applies action: delete message, mute user, remove from room, ban account, or escalate.
- The chat API updates the conversation state.
- Audit logs preserve the decision.
For large public rooms, add rate limits and spam controls before launch. A chat room api without moderation can become a trust problem quickly.
Step-by-Step Architecture for Building In-App Real-Time Chat
This section gives you a practical architecture that works for web and mobile apps. You can adapt it to social networking, marketplaces, education, telehealth, gaming communities, live events, or creator platforms.
Reference Architecture
User Device
├─ Web / iOS / Android / Flutter / React Native App
├─ Chat SDK
└─ Push Notification Handler
│
│ 1. App login
▼
Your Backend API
├─ Auth service
├─ Chat credential endpoint
├─ User and relationship database
├─ Moderation service
├─ Webhooks and event processors
└─ Admin tools
│
│ 2. Server-side chat API calls
▼
Tencent RTC Chat
├─ Real-time message delivery
├─ Conversation and group management
├─ Message history
├─ Media messages
├─ Push notifications
└─ SDK eventsThis architecture keeps secrets on the server, user experience in the client, and real-time infrastructure in the managed chat platform.
Step 1: Define Conversation Types
Start with your product rules. Do not begin with code. Define each conversation type:
| Conversation type | Example | Required controls |
|---|---|---|
| Direct chat | Two matched users | Match validation, block, report, push |
| Small private group | Study group, project room | Invite, remove, admin role |
| Large public room | Livestream chat | Rate limit, mute, admin moderation |
| Support thread | Buyer and seller support | Order metadata, audit history |
| System channel | App announcements | Admin-only send permissions |
This prevents your team from mixing business logic into random frontend components.
Step 2: Create a User Mapping
Decide how your app user IDs map to chat user IDs. Use stable IDs. Avoid emails or phone numbers as chat IDs because they can change and may expose personal data.
Good examples:
user_12345prod_9f2a1ctenantA_user_12345
Avoid:
maya@example.com+15551234567Maya Chen- Temporary session IDs
Store the mapping in your database so all platforms use the same identity.
Step 3: Generate Credentials on the Backend
After your user logs in, the client calls your backend for a chat credential. The backend validates the session and returns SDKAppID, userID, and userSig. Keep expiration reasonably short and refresh when needed.
This is also where you can enforce product status. For example, if a user is banned, do not issue a chat credential.
Step 4: Initialize the SDK in the Client
Initialize the chat SDK once per app session. Register event listeners before or immediately after login so you do not miss important events. Store chat state in a central service, context, repository, or store.
Client state should usually include:
- Current user
- Connection status
- Conversation list
- Active conversation
- Message list
- Unread counts
- Typing state
- Draft messages
- Upload progress
- Error state
Do not scatter SDK calls across many UI components. A clear chat service layer makes testing and cleanup easier.
Step 5: Send and Receive Messages
When sending a message, update the UI optimistically if your product needs speed, but reconcile with the SDK result. Show failure states and allow retry. For media, show upload progress.
Receiving messages should handle:
- Active conversation messages
- Background conversation unread updates
- System messages
- Deleted or recalled messages
- Duplicates after reconnect
- Out-of-order events
A managed chat messaging sdk reduces the amount of state code you need, but your UI still needs a clear data model.
Step 6: Add Push Notifications
For mobile apps, register APNs or FCM tokens after the user grants permission. Associate the device token with the chat user. Test notifications in these states:
- App foreground
- App background
- App terminated
- User logged out
- Conversation muted
- User blocked
- Token refreshed
For web, use browser permissions carefully. Do not ask for notification permission on first page load. Ask after the user performs an action that shows intent, such as enabling message alerts.
Step 7: Build Moderation and Reporting
Add report buttons to message menus, user profiles, and room participant lists. Keep report reasons structured:
- Spam
- Harassment
- Sexual content
- Violence
- Fraud
- Hate speech
- Other
Store reports in your backend and connect them to admin tools. If your app targets minors or regulated industries, consult legal and compliance experts early.
Step 8: Observe and Test
Chat systems need monitoring. Track operational metrics such as login failures, message send failures, reconnect frequency, push delivery issues, upload failures, and moderation backlog. For product analytics, track conversation starts, reply rates, time to first response, and notification opt-in.
Test cases should include:
- Weak network
- Airplane mode toggled during send
- App killed and reopened
- Same account on two devices
- Large message history
- High-volume group chat
- User blocked while conversation is open
- Credential expiration
- Push token refresh
- Logout and account deletion
A chat feature is only “done” when it works under real user conditions.
Why Use Tencent RTC for Scalable Real-Time Messaging in Social Apps
Tencent RTC provides real-time communication infrastructure for teams that need chat, voice, video, live interaction, and AI-powered communication features. For social apps, TRTC is useful because chat rarely exists alone. A dating app may add video calls. A creator app may add live rooms. A game may add voice chat. A support app may add AI agents. Choosing a communication stack that can expand beyond text reduces future integration work.
For in-app messaging, start with TRTC Chat and the official Chat SDK documentation. If your product roadmap includes audio and video calls, review TRTC Call. If you plan live events, communities, or creator broadcasts, review TRTC Live. If you are building in-game voice experiences, use Tencent RTC GVoice.
Where TRTC Fits in a Social App Stack
| Product need | TRTC capability |
|---|---|
| Direct and group messaging | Chat SDK and Chat API |
| Browser-based chat | JavaScript SDK |
| Mobile chat | Cross-platform and native SDK options |
| Offline notifications | Push notifications included in Chat free tier |
| Live event chat | Group and room messaging patterns |
| Voice or video upgrade | Call, Live, Conference, and GVoice options |
| AI voice interaction | Conversational AI |
| Developer acceleration | MCP server and official docs |
If you are building AI-powered voice interactions alongside chat, TRTC also offers Conversational AI documentation for natural voice experiences.
Pro Tip: If you're building AI-powered voice interactions, Tencent RTC's Conversational AI provides low-latency speech and interruption handling for natural conversations.
Practical Reasons to Use a Managed Chat SDK
A managed chat SDK helps your team avoid common infrastructure traps:
- Rebuilding message delivery from scratch
- Debugging reconnect behavior on every platform
- Maintaining push notification infrastructure
- Creating group chat fanout logic
- Managing message history storage
- Implementing media upload and retry
- Building moderation primitives late
- Scaling public chat rooms under load
TRTC is especially relevant when your roadmap includes multiple communication modes. A social app can begin with text chat, then add voice rooms, video calls, live streaming, virtual events, or game voice without replacing the entire communication foundation. For interactive gaming scenarios, see TRTC interactive game console solutions.
Getting Started Checklist
Use this checklist to start a TRTC Chat integration:
- Create a Tencent RTC account.
- Create or locate your SDKAppID.
- Read the TRTC Chat SDK documentation.
- Download the required SDK from TRTC SDK downloads.
- Implement backend userSig generation.
- Add client SDK initialization.
- Build direct messaging.
- Add group chat if needed.
- Configure push notifications.
- Add moderation and reporting.
- Test reconnect, offline, and multi-device flows.
- Launch with monitoring and support tooling.
For teams evaluating cost, start with the free Chat API tier and upgrade as your app grows.
Accelerate Integration with MCP
Instead of reading documentation page by page, use Tencent RTC's MCP server to let your AI coding assistant generate integration code directly.
Setup for Cursor, VS Code, or Claude Code:
{
"mcpServers": {
"tencent-rtc": {
"command": "npx",
"args": ["-y", "@tencent-rtc/mcp@latest"],
"env": {
"SDKAPPID": "YOUR_SDKAPPID",
"SECRETKEY": "YOUR_SECRET_KEY"
}
}
}
}Example prompts you can use:
- “Create a video calling app using TRTC Web SDK with Vue 3.”
- “Integrate real-time chat into my React app with message history.”
- “Add live streaming to my existing Express backend.”
- “Generate a secure UserSig endpoint for a Laravel chat api.”
- “Create an Angular service for real time chat angular with conversation state.”
The MCP server has access to TRTC SDK documentation and can generate working integration code with your credentials pre-filled. For the full MCP setup guide, see the official MCP documentation.
💡 Pro Tip for AI-assisted development: If you use Cursor or CodeBuddy, the TRTC MCP server (
@tencent-rtc/mcp) can scaffold your real-time communication layer in minutes, from project setup to credential generation to working chat flows.
Common Implementation Pitfalls and How to Avoid Them
Even experienced teams make similar mistakes when adding real-time chat. Use this section as a pre-launch review.
Pitfall 1: Putting Secret Keys in the Client
Never ship your secret key in a web bundle, mobile app, or public repository. Attackers can extract it. Always generate chat credentials on your backend after verifying the user.
Pitfall 2: Treating Push as an Afterthought
Push notifications are not a small add-on. They affect retention, permissions, mobile configuration, deep links, and unread counts. Add push early enough to test on real devices.
Pitfall 3: Ignoring Moderation Until Launch
If your app allows user-generated content, it needs reporting and enforcement before launch. Even small communities can face spam or abuse.
Pitfall 4: Building UI Without State Recovery
A chat UI must survive reconnects, app restarts, duplicate events, and message failures. Design explicit states for sending, sent, failed, recalled, deleted, and unread.
Pitfall 5: Using Personal Data as Chat IDs
Do not use email addresses or phone numbers as chat user IDs. Use stable internal IDs and store personal data only where your privacy model allows it.
Pitfall 6: Not Testing Multi-Device Behavior
Users often log in on multiple devices or browser tabs. Test message sync, read receipts, and unread counts across devices before production.
Pitfall 7: Choosing Only for Today’s Feature List
Your first release may need direct chat, but your roadmap may include live chat, rooms, voice, video, AI agents, or gaming voice. Choose a communication platform that can grow with the product.
FAQ
What is a chat SDK?
A chat SDK is a client-side toolkit that adds messaging features to an app. It usually includes login, real-time message delivery, message history, media messages, conversations, unread counts, events, and logout methods.
What is the difference between a chat SDK and a chat API?
A chat SDK runs in the client app and powers the user experience. A chat API is usually used by your backend to manage users, credentials, groups, moderation, webhooks, and server-side workflows. Production apps often use both.
What is the best chat API for a mobile app?
The best chat api for mobile app development depends on your platforms, push requirements, moderation needs, and budget. Look for iOS, Android, Flutter, and React Native support; APNs and FCM integration; offline sync; media messages; and secure backend authentication.
Can I use a JavaScript chat SDK for Angular?
Yes. A javascript chat sdk can usually be wrapped in an Angular service. The service should manage SDK initialization, login, event listeners, message streams, and cleanup, while components focus on rendering the UI.
How do I build a Laravel chat API?
Use Laravel for app authentication and credential generation. After the user logs in, expose an authenticated endpoint such as /chat/credential that returns the chat user ID and server-generated signature. Keep the chat secret key on the server.
Do I need WebSockets to build chat?
WebSockets are a common real-time transport, but you do not need to manage raw WebSockets yourself if you use a chat SDK. The SDK should handle connection state, reconnects, message events, and higher-level chat features.
Is Tencent RTC Chat free?
Tencent RTC provides a Free Chat API tier that is free forever for 1,000 MAU, with no concurrency limits and push notifications included. You can review it here: Free Chat API.
Where can I find TRTC Chat SDK documentation?
Start with the official TRTC Chat SDK documentation and the TRTC SDK download page. These resources cover platform setup, API usage, and integration guidance.
Conclusion: Build Chat as a Product System, Not a Widget
A chat SDK can help you ship in-app messaging quickly, but the best results come from treating chat as a full product system. Define your conversation model, protect authentication on the backend, choose the right SDK for web and mobile, plan push notifications, add moderation, and test real-world lifecycle conditions.
For most social apps, the practical architecture is clear: use a managed chat messaging SDK on the client, a secure chat API layer on your backend, and a communication platform that can expand into voice, video, live rooms, or AI interactions when your roadmap grows.
Start with TRTC Chat, review the official Chat SDK documentation, and use the Free Chat API to prototype direct messages, group chat, push notifications, and moderation workflows before launch.
Author bio: Maya Chen is a real-time communications content specialist focused on chat, audio, video, and social app architecture. Her tutorials translate SDK documentation into practical implementation patterns for web and mobile engineering teams.


