react-native-newinstance-chat
v0.3.0
Published
New instance LiveAndAiChat React Native SDK — AI + live-agent chat, drop-in native chat screen for iOS and Android.
Readme
react-native-newinstance-chat
React Native bindings for LiveAndAiChat — drops a complete AI + live-agent chat experience into your iOS and Android RN app via native module bridges.
The chat UI, transport, attachments, image cache, typing indicators, and silent gap-fill resync all come from the native iOS / Android SDKs. This package is a thin TurboModule surface over them — your React Native code stays small.
Requirements
- React Native 0.74+ (TurboModule support — recommended 0.85+)
- iOS 15.1+
- Android API 24+, JDK 17
Installation
npm install react-native-newinstance-chat
# or
yarn add react-native-newinstance-chatiOS
cd ios && pod installAutolink pulls the NewinstanceChat podspec, which transitively depends
on LiveAndAiChat (the native SDK pod, published on CocoaPods Trunk).
Both default static-library Podfiles and use_frameworks! (any linkage)
are supported. If you see 'NewinstanceChat-Swift.h' file not found you
are on 0.1.0, which only resolved the generated Swift header in
static-library builds. Upgrade to 0.1.1 or later, then reinstall pods:
npm install react-native-newinstance-chat@latest
cd ios && pod installAndroid
Autolink registers NewinstanceChatPackage. The underlying
cloud.newinstance:liveandaichat AAR is resolved from Maven Central —
ensure mavenCentral() is in settings.gradle.kts.
Quick start
import { NewinstanceChat } from 'react-native-newinstance-chat';
const sdk = new NewinstanceChat({
apiKey: 'sk_live_…',
});
sdk.setUser({
customerName: 'Ada Lovelace',
customerEmail: '[email protected]',
});
await sdk.initialize();
// `sdk.ready` is a Promise that resolves once the native module is configured -
// await it anywhere you need to know setup completed.
await sdk.ready;
// Later, in response to a host button tap:
sdk.openChat();The chat screen renders natively — there is no React component to mount.
Your RN UI is whatever button / banner / FAB triggers openChat().
Authenticating the customer
apiKey is the publishable widget key ID, never the keyId:secret
form, which belongs on your server only.
There are two ways to say who the customer is.
Anonymous. Supply nothing. The chat collects whatever it needs.
Verified. Have your backend mint a chat identity token and hand it to the app. The token is the identity, so no other customer fields are needed:
// Your backend, with the SECRET key, typically at sign-in:
// POST https://api.newinstance.cloud/api/v1/chat/sessions
// x-api-key: sk_live_abc123:YOUR_SECRET_KEY
// { "customerId": "usr_123", "customerName": "Ada Lovelace",
// "customerEmail": "[email protected]", "customerPhone": "+44 20 7946 0958",
// "metadata": { "plan": "enterprise" }, "expiresInSeconds": 21600 }
// -> { token, expiresAt, session: { sessionId, ... } }
sdk.setUserToken(tokenFromYourBackend);Everything you put in that payload is signed into the token, so the chat session already knows the customer before the app says anything:
customerId -> the verified customer id
customerName -> the name on the conversation and on every message
customerEmail -> also satisfies the merchant's "require email" setting
customerPhone -> shown to the agent
metadata -> any extra context your agents should seeThe client then passes one string. It never repeats the name, never repeats the email, and is never shown a pre-chat form.
The server verifies the signature and derives the name, email and customer
id from the token's claims, so a tampered app cannot claim to be someone
else. customerId passed without a token is recorded for agent context
only and is not treated as identity.
Tokens expire (one hour by default). A rejected token arrives on the error
event as INVALID_IDENTITY_TOKEN; mint a fresh one.
Sessions are managed over REST: POST /api/v1/chat/sessions to create,
DELETE /api/v1/chat/sessions?customerId=... on sign-out. You choose the
lifetime (60 seconds to 24 hours, default 1 hour) with expiresInSeconds.
A customer holds one live session at a time. Creating another while
theirs is valid returns 409 with the existing session; mint again once it
expires or after you revoke it. Revocation takes effect on the next request,
so an invalidated token stops working immediately even though its signature
is still valid.
The token is the session: the identity is signed into it, and the platform stores no copy. Decode the token if you need the name, email, phone or metadata back.
Theming
The chat resolves colours from three layers:
dashboard theme > your local theme > the SDK's built-in themeThe merchant's dashboard configuration wins, your local theme fills in what the dashboard did not set, and the built-in palette fills in the rest, so every colour always has a value, even with no network. Merging is per token, so setting one colour does not discard the others.
const sdk = new NewinstanceChat({
apiKey: 'sk_live_…',
theme: { mode: 'dark', sentBubble: '#16A34A' },
});Every ChatThemeOverride field is optional; colours are hex strings. An
unparseable value is ignored rather than throwing. mode is only a
preference: the dashboard's explicit light/dark wins, and its auto defers
to yours, then to the device.
If remote configuration cannot be fetched, your local theme still applies
and the chat stays fully usable; you get a CONFIG_FETCH_FAILED warning on
the error event.
Subscribing to events
const unsub = sdk.addListener('messageReceived', (m) => {
console.log('rx <-', m.content);
});
// Later:
unsub();Event names: messageReceived, messageSent, agentTypingChanged,
connectionStateChanged, unreadCountChanged, error,
attachmentUpdated, chatClosed. See src/types.ts for payload shapes.
The error event
error is the channel for "why is my chat not working". It never surfaces
in the chat interface the customer sees, and it never carries the API key,
the identity token, or customer data.
sdk.addListener('error', (e) => {
if (e.code === 'INVALID_IDENTITY_TOKEN') return refreshChatToken();
if (!e.recoverable) reportToYourMonitoring(e.code, e.message);
});| code | What went wrong |
|---|---|
| MISSING_WIDGET_KEY | No API key was supplied |
| INVALID_PUBLIC_KEY | The key was rejected: wrong key, wrong environment, revoked, expired |
| CHAT_CONFIG_UNAVAILABLE | The key is fine, but the organization has no chat configuration |
| CHAT_DISABLED | Chat is switched off in the dashboard |
| CONFIG_FETCH_FAILED | Remote configuration could not be loaded; the local/built-in theme is in use |
| INVALID_IDENTITY_TOKEN | The token was malformed, expired, or signed for another organization |
| NETWORK_ERROR | The backend could not be reached |
| TRANSPORT_ERROR | The realtime connection dropped |
| CHAT_INITIALIZATION_FAILED | The conversation could not be started |
| MESSAGE_SEND_FAILED | A message could not be delivered |
| ATTACHMENT_FAILED | An attachment could not be uploaded |
| SERVER_ERROR | The backend returned something unusable |
The same codes are emitted by the web, Android, iOS and Flutter SDKs.
type (network / validation / auth / system) is still present for
handlers written against 0.2.x; code is undefined only when the
underlying native SDK predates coded errors.
The chat-close event
chatClosed fires exactly once per chat presentation, however the
screen went away: the in-chat close button, Android back navigation
(button or gesture), an iOS dismissal gesture, closeChat(),
destroy() (reason session_ended), or the host app navigating the
screen away. Rerenders and lifecycle churn never produce duplicates.
useEffect(() => {
const unsub = sdk.addListener('chatClosed', (e) => {
// e.reason: 'close_button' | 'back_navigation' | 'gesture' |
// 'programmatic' | 'session_ended' | 'host_navigation'
// e.initiator: 'user' | 'host' | 'sdk'
// plus: timestamp, conversationId, assignmentId, channel,
// previousState, unreadCount, hasDraft,
// pendingAttachmentCount, metadata
analytics.track('chat_closed', { reason: e.reason });
});
return unsub; // always clean up on unmount
}, []);Ordering: chatClosed is emitted after the SDK has left the open
state (unreadCount and pendingAttachmentCount reflect the moment of
dismissal). The event never contains message contents, credentials, or
attachment bytes.
Sending messages programmatically
sdk.sendMessage('Hi, I have a question.');
sdk.retryMessage(failedMessageId);Programmatic attachments
attachFile accepts base64, data URIs, local file paths,
content:// / file:// URIs (picker outputs), and — when the native
SDK is configured with allowRemoteAttachmentUrls — remote URLs.
sourceType: 'auto' (the default) safely detects string inputs.
// Base64 (e.g. from a camera or canvas):
const id = await sdk.attachFile({
source: pngBase64,
sourceType: 'base64',
name: 'photo.png',
mimeType: 'image/png',
});
// React Native document picker result:
const [doc] = await pick(); // e.g. @react-native-documents/picker
await sdk.attachFile({
source: doc.uri, // content:// on Android, file:// on iOS
name: doc.name ?? 'document.pdf',
mimeType: doc.type ?? 'application/pdf',
size: doc.size ?? undefined,
});
// Data URI:
await sdk.attachFile({ source: dataUri, name: 'chart.png' });The returned promise resolves with the attachment id as soon as the
request is accepted and queued. Validation and upload run in the
background and never block the UI thread — failures surface as
attachmentUpdated with status: 'failed' plus an error event — and
the message is never sent until the upload succeeds (send drains only
uploaded attachments). Track progress and results via
attachmentUpdated:
sdk.addListener('attachmentUpdated', (a) => {
// a.status: 'queued' | 'uploading' | 'uploaded' | 'failed' | 'cancelled'
// a.progress: 0..1 real byte progress
if (a.status === 'failed') console.warn(a.error);
});
sdk.removeAttachment(id); // cancels an in-flight upload
sdk.clearAttachments();Validation happens before anything is queued: base64 must decode, URIs
must be readable, files must be non-empty and at most 25 MB, the MIME
type must be one of png/jpeg/webp/gif/pdf, a mismatched size is
rejected as corruption, and the extension must agree with the MIME
type. Attachment contents are never written to logs.
Allowed MIME types and the 25 MB cap mirror the web widget; keys and limits are enforced again server-side.
Handoff to a live agent and typing indicators are driven automatically by the native chat screen — there's nothing to wire up from the host.
Tear-down
sdk.destroy();Call this when your host component unmounts. After destroy() the
instance is unusable — construct a new one if you need to chat again.
Contributing
License
MIT
