=============== LIBRARY RULES =============== From library maintainers: - Use @trycourier/courier-react-native. Do not use the web packages (@trycourier/courier-react) or the deprecated v7 @trycourier/react-inbox in React Native. - Sign in with await Courier.shared.signIn({ accessToken: jwt, userId }). - Use CourierInboxView for the prebuilt Inbox and CourierPreferencesView for preferences; use Courier.shared.addInboxListener for a custom UI and remove it on unmount. - After npm install, run cd ios && pod install, then complete the native iOS and Android push setup in docs/push-notifications.md. - Mint the Courier JWT on your backend with your Courier API key (POST /auth/issue-token). Never put the API key in the app. - Call signIn once, after your own login resolves. Credentials persist across app launches. Call signOut when the user logs out. - The user_id in the JWT scope must match the userId passed to signIn, or the Inbox loads empty. - Scopes: inbox:read:messages inbox:write:events for Inbox; add read:preferences write:preferences for preferences and write:user-tokens for push. - Always set expires_in when minting. The SDK does not refresh tokens: mint a new JWT and call signIn again before it expires. - EU workspaces: mint the JWT at https://api.eu.courier.com/auth/issue-token and pass EU apiUrls to signIn. Token and client must be in the same region. ### Install courier-react-native and pod install for iOS Source: https://github.com/trycourier/courier-react-native/blob/main/docs/add-a-preference-center.md Install the SDK with npm, then run pod install for iOS native setup. ```bash npm install @trycourier/courier-react-native # then, for iOS: cd ios && pod install ``` -------------------------------- ### Install with yarn Source: https://github.com/trycourier/courier-react-native/blob/main/docs/sdk-reference.md Install the Courier React Native SDK using yarn. ```bash yarn add @trycourier/courier-react-native ``` -------------------------------- ### Install @trycourier/courier-react-native Source: https://github.com/trycourier/courier-react-native/blob/main/docs/push-notifications.md Install the Courier React Native SDK via npm. ```bash npm install @trycourier/courier-react-native ``` -------------------------------- ### read and click usage example Source: https://github.com/trycourier/courier-react-native Example of calling client.inbox.read and client.inbox.click with a messageId and trackingId. ```TypeScript await client.inbox.read({ messageId: 'msg_123' }); await client.inbox.click({ messageId: 'msg_123', trackingId: trackedId }); ``` -------------------------------- ### Example usage of readMessage and readAllInboxMessages Source: https://github.com/trycourier/courier-react-native Example calls to readMessage and readAllInboxMessages on the shared Courier instance. ```TypeScript await Courier.shared.readMessage({ messageId: 'msg_123' }); await Courier.shared.readAllInboxMessages(); ``` -------------------------------- ### getBrand usage example Source: https://github.com/trycourier/courier-react-native Example of calling client.brands.getBrand with a brandId and logging the primary color from the response. ```TypeScript const response = await client.brands.getBrand({ brandId: 'BRAND_ID' }); console.log(response.data?.brand?.settings?.colors?.primary); ``` -------------------------------- ### Set and get push tokens example Source: https://github.com/trycourier/courier-react-native Example usage of setTokenForProvider and getAllTokens. Sets a Firebase FCM token and then retrieves all tokens, logging the APN token. ```typescript await Courier.shared.setTokenForProvider({ provider: CourierPushProvider.FIREBASE_FCM, token: fcmToken, }); const tokens = await Courier.shared.getAllTokens(); console.log(tokens.get(CourierPushProvider.APN)); ``` -------------------------------- ### getUserPreferences usage example Source: https://github.com/trycourier/courier-react-native Example of calling getUserPreferences and iterating over the returned topics, logging topicName and status. ```TypeScript const prefs = await client.preferences.getUserPreferences({ paginationCursor: undefined }); prefs.items.forEach((topic) => { console.log(topic.topicName, topic.status); }); ``` -------------------------------- ### Install Courier React Native SDK with npm and CocoaPods Source: https://github.com/trycourier/courier-react-native/blob/main/README.md Install the SDK via npm and then run pod install in the ios directory. For Swift Package Manager mode, use npx react-native spm instead of pod install. ```bash npm install @trycourier/courier-react-native cd ios && pod install ``` -------------------------------- ### setIOSForegroundPresentationOptions usage example Source: https://github.com/trycourier/courier-react-native Example call to set foreground presentation options to sound, badge, and banner. ```TypeScript Courier.setIOSForegroundPresentationOptions({ options: ['sound', 'badge', 'banner'] }); ``` -------------------------------- ### Add push notification listener example Source: https://github.com/trycourier/courier-react-native Example of adding a push notification listener with callbacks for clicked and delivered events. Logs the push title when clicked and the full push object when delivered. ```typescript const pushListener = Courier.shared.addPushNotificationListener({ onPushNotificationClicked: (push) => { console.log('Clicked', push.title); }, onPushNotificationDelivered: (push) => { console.log('Delivered', push); }, }); ``` -------------------------------- ### Example usage of fetchNextPageOfMessages Source: https://github.com/trycourier/courier-react-native Example of fetching the next page of messages from the 'feed' feed and appending them to the current messages state. ```TypeScript const nextPage = await Courier.shared.fetchNextPageOfMessages({ inboxMessageFeed: 'feed', }); setMessages((prev) => [...prev, ...nextPage]); ``` -------------------------------- ### postTrackingUrl usage example Source: https://github.com/trycourier/courier-react-native Shows how to call postTrackingUrl with a tracking URL and event. Rejects with the native API error; invalid URLs are rejected by the host. ```TypeScript try { await client.tracking.postTrackingUrl({ url: message.trackingIds?.clickTrackingId, event: CourierTrackingEvent.Clicked, }); } catch (error) { // Rejects with the native API error; invalid URLs are rejected by the host console.error(error); } ``` -------------------------------- ### putUserPreferenceTopic usage example Source: https://github.com/trycourier/courier-react-native Example of updating a user preference topic with opted-in status and custom routing to email and push channels. ```TypeScript await client.preferences.putUserPreferenceTopic({ topicId: 'topic_1', status: CourierUserPreferencesStatus.OptedIn, hasCustomRouting: true, customRouting: [CourierUserPreferencesChannel.Email, CourierUserPreferencesChannel.Push], }); ``` -------------------------------- ### Usage example of getCourierApiUrlsForRegion Source: https://github.com/trycourier/courier-react-native Shows how to import and call getCourierApiUrlsForRegion with 'eu' to get EU endpoints. The console.log outputs https://api.eu.courier.com. ```TypeScript import { getCourierApiUrlsForRegion, DEFAULT_COURIER_API_URLS } from '@trycourier/courier-react-native'; const urls = getCourierApiUrlsForRegion('eu'); console.log(urls.rest); // https://api.eu.courier.com ``` -------------------------------- ### Build your own UI with addInboxListener Source: https://github.com/trycourier/courier-react-native/blob/main/docs/build-a-custom-inbox.md Start the feed by adding an inbox listener, render your own UI from messages, toggle read on tap, and remove the listener when the view goes away. Sign in first; adding the listener loads the first page. refreshInbox() is only for pull-to-refresh. ```jsx // 1. Start: adding a listener loads the first page (sign in first) const listener = await Courier.shared.addInboxListener({ onMessagesChanged: (messages, canPaginate, feed) => { render(messages); // 2. Build your own UI }, }); // 3. Toggle read on tap message.isRead ? await Courier.shared.unreadMessage({ messageId: message.messageId }) : await Courier.shared.readMessage({ messageId: message.messageId }); // 4. Tear down await listener.remove(); ``` -------------------------------- ### Example usage of addInboxListener and removeInboxListener Source: https://github.com/trycourier/courier-react-native Example of adding an inbox listener with callbacks for loading, unread count, messages changed, and error, then removing it using the returned listener ID. ```TypeScript const inboxListener = await Courier.shared.addInboxListener({ onLoading: (isRefresh) => setRefreshing(isRefresh), onUnreadCountChanged: (unreadCount) => setBadge(unreadCount), onMessagesChanged: (messages, canPaginate, feed) => { setMessages(feed === 'feed' ? messages : archived); }, onError: (error) => console.error('Inbox error', error), }); await Courier.shared.removeInboxListener({ listenerId: inboxListener.listenerId }); ``` -------------------------------- ### Install iOS pods Source: https://github.com/trycourier/courier-react-native/blob/main/docs/sdk-reference.md Install CocoaPods dependencies for iOS. Skip this step in React Native's Swift Package Manager mode (0.87 and later). ```bash cd ios && pod install ``` -------------------------------- ### fromJson usage example Source: https://github.com/trycourier/courier-react-native Example of parsing an action JSON string and accessing trackingId. Catches invalid JSON errors. ```TypeScript try { const action = InboxAction.fromJson( JSON.stringify({ content: 'Open', href: 'https://courier.com', data: { trackingId: 't' } }) ); console.log(action.trackingId); } catch (error) { // invalid JSON } ``` -------------------------------- ### getMessages pagination usage Source: https://github.com/trycourier/courier-react-native Example of fetching two pages of inbox messages using paginationLimit and startCursor from the first response's pageInfo. ```TypeScript const page1 = await client.inbox.getMessages({ paginationLimit: 25 }); const cursor = page1.data?.messages?.pageInfo?.startCursor; const page2 = await client.inbox.getMessages({ paginationLimit: 25, startCursor: cursor }); ``` -------------------------------- ### Quick Start: Sign in and render CourierInboxView Source: https://github.com/trycourier/courier-react-native/blob/main/README.md Sign in with a JWT generated by your backend, then drop in the prebuilt CourierInboxView. The onClickInboxMessageAtIndex handler toggles read/unread state based on the message's current read status. ```jsx import Courier, { CourierInboxView } from "@trycourier/courier-react-native"; // Sign in (JWT generated by your backend) await Courier.shared.signIn({ userId: "user_123", accessToken: jwt, }); // Drop in a prebuilt Inbox view { message.read ? Courier.shared.unreadMessage({ messageId: message.messageId }) : Courier.shared.readMessage({ messageId: message.messageId }); }} style={{ flex: 1 }} /> ``` -------------------------------- ### putUserToken usage example Source: https://github.com/trycourier/courier-react-native Example call to putUserToken with a Firebase FCM token and device metadata. The device object includes appId, adId, deviceId, platform, manufacturer, and model. ```TypeScript await client.tokens.putUserToken({ token: fcmToken, provider: CourierPushProvider.FIREBASE_FCM, device: { appId: 'com.example.app', adId: 'AD_ID', deviceId: 'DEVICE_ID', platform: 'android', manufacturer: 'Google', model: 'Pixel 9', }, }); ``` -------------------------------- ### deleteUserToken usage example with error handling Source: https://github.com/trycourier/courier-react-native Example call to deleteUserToken wrapped in a try-catch. The promise rejects when signed out or on network error, logging 'Token deletion failed'. ```TypeScript try { await client.tokens.deleteUserToken({ token: oldToken }); } catch (error) { console.error('Token deletion failed', error); // rejects when signed out / network error } ``` -------------------------------- ### Display modes: topic and channels Source: https://github.com/trycourier/courier-react-native/blob/main/docs/add-a-preference-center.md Two example usages of CourierPreferencesView with mode prop: topic mode for simple on/off toggles, channels mode for per-channel controls. ```jsx ``` ```jsx ``` -------------------------------- ### Read and write user preferences via the preferences client Source: https://github.com/trycourier/courier-react-native/blob/main/docs/customize-preferences.md After signIn, get the client and use the preferences client to fetch user preferences and update a topic's routing. Note: putUserPreferenceTopic replaces the topic's routing rather than merging; send hasCustomRouting and the full customRouting array together. ```typescript // Get the client, available after signIn const client = await Courier.shared.getClient(); const prefs = await client.preferences.getUserPreferences({ paginationCursor: undefined, }); await client.preferences.putUserPreferenceTopic({ topicId: "TOPIC_ID", status: CourierUserPreferencesStatus.OptedIn, hasCustomRouting: true, customRouting: [CourierUserPreferencesChannel.Push], }); ``` -------------------------------- ### archive usage with error handling Source: https://github.com/trycourier/courier-react-native Example of calling client.inbox.archive and logging the HTTP status, with a try/catch for native API errors. ```TypeScript try { const status = await client.inbox.archive({ messageId: 'msg_123' }); console.log('Archive HTTP status', status); } catch (error) { // Native API error (e.g. network failure, invalid credentials) console.error(error); } ``` -------------------------------- ### Get brand by ID Source: https://github.com/trycourier/courier-react-native/blob/main/docs/sdk-reference.md Fetches a brand using its brandId. ```typescript const brand = await client.brands.getBrand({ brandId: "..." }); ``` -------------------------------- ### enablePush function using requestNotificationPermission Source: https://github.com/trycourier/courier-react-native Example async function that requests notification permission and logs 'Notifications enabled' if authorized. ```TypeScript async function enablePush() { const status = await Courier.requestNotificationPermission(); if (status === 'authorized') { Courier.log('Notifications enabled'); } } ``` -------------------------------- ### CourierInboxView Callbacks for Message Actions and Scroll Source: https://github.com/trycourier/courier-react-native Example of using onClickInboxMessageAtIndex with defensive error handling, onClickInboxActionForMessageAtIndex to open action href, and onScrollInbox to log offsetY. ```TSX { try { // parse failures inside fromJson log and throw; defensive handling: message.markAsOpened().catch(console.error); } catch (error) { console.error('Bad message payload', error); } }} onClickInboxActionForMessageAtIndex={(action, message) => action.href && Linking.openURL(action.href) } onScrollInbox={(y) => console.log('offsetY', y)} /> ``` -------------------------------- ### Defensive push notification handling Source: https://github.com/trycourier/courier-react-native Example showing defensive parsing of push payloads. Events are parsed defensively; malformed payloads log but never throw into the listener. Uses try/catch to navigate to a message screen. ```typescript // The payload is JSON; events are parsed defensively — malformed payloads log, // they never throw into the listener. Courier.shared.addPushNotificationListener({ onPushNotificationClicked: (push) => { try { NavigationService.navigate('Message', { id: push.messageId }); } catch (error) { console.error(error); } }, }); ``` -------------------------------- ### CourierPreferencesView with topic mode and error/scroll handlers Source: https://github.com/trycourier/courier-react-native Example using topic mode with onPreferenceError and onScrollPreferences callbacks. The error callback receives a message string; the scroll callback receives offsetY. ```TSX { // e.g. preferences failed to load for the current user Alert.alert('Preferences error', message); }} onScrollPreferences={(y) => setScrolled(y > 0)} /> ``` -------------------------------- ### new CourierClient(options) Source: https://github.com/trycourier/courier-react-native/blob/main/docs/sdk-reference.md Initializes a new CourierClient instance with the provided options. Each client holds its own credentials, allowing multiple clients to be created as needed. ```APIDOC ## new CourierClient(options) ### Description Initializes a new CourierClient instance with the provided options. Each client holds its own credentials, allowing multiple clients to be created as needed. ### Method Constructor ### Parameters #### Options - **jwt** (string) - Optional - JWT for authentication, required for most authenticated calls. - **userId** (string) - Required - The user ID. - **connectionId** (string) - Optional - Used for the inbox websocket. - **tenantId** (string) - Optional - Scopes the client to a tenant. - **apiUrls** (object) - Optional - API URLs for a specific region, e.g., `getCourierApiUrlsForRegion("eu")`. - **showLogs** (boolean) - Optional - Defaults to your build configuration. ### Example ```typescript import { CourierClient, getCourierApiUrlsForRegion } from "@trycourier/courier-react-native"; const client = new CourierClient({ jwt: "...", // Optional. Required for most authenticated calls userId: "your_user_id", connectionId: "...", // Optional. Used for the inbox websocket tenantId: "...", // Optional. Scopes the client to a tenant apiUrls: getCourierApiUrlsForRegion("eu"), // Optional. Use for EU users showLogs: true // Optional. Defaults to your build configuration }); const options = client.options; // Tear the client down when you no longer need it client.remove(); ``` ``` -------------------------------- ### Initialize CourierClient Source: https://github.com/trycourier/courier-react-native/blob/main/docs/sdk-reference.md Creates a low-level CourierClient with optional JWT, userId, connectionId, tenantId, EU API URLs, and logging. Each client holds its own credentials. Call remove() to tear down when no longer needed. ```typescript import { CourierClient, getCourierApiUrlsForRegion } from "@trycourier/courier-react-native"; const client = new CourierClient({ jwt: "...", // Optional. Required for most authenticated calls userId: "your_user_id", connectionId: "...", // Optional. Used for the inbox websocket tenantId: "...", // Optional. Scopes the client to a tenant apiUrls: getCourierApiUrlsForRegion("eu"), // Optional. Use for EU users showLogs: true // Optional. Defaults to your build configuration }); const options = client.options; // Tear the client down when you no longer need it client.remove(); ``` -------------------------------- ### Creating a CourierClient instance Source: https://github.com/trycourier/courier-react-native Instantiates a CourierClient with a user ID, JWT, connection ID, tenant ID, EU API URLs, and debug logging enabled. Then queries the inbox unread count and logs the client options and native client ID. ```TypeScript import { CourierClient, getCourierApiUrlsForRegion } from "@trycourier/courier-react-native"; const client = new CourierClient({ userId: 'user_123', jwt, connectionId: 'conn_1', tenantId: 'tenant_a', apiUrls: getCourierApiUrlsForRegion('eu'), showLogs: true, }); const unread = await client.inbox.getUnreadMessageCount(); console.log(client.options, client.clientId); ``` -------------------------------- ### Send message to tenant inbox (Go) Source: https://github.com/trycourier/courier-react-native/blob/main/docs/send-to-the-inbox.md Send a message to a tenant's inbox using the Go client. Set context.tenant_id on the recipient. ```go response, err := client.Send.Message(context.TODO(), courier.SendMessageParams{ Message: courier.SendMessageParamsMessage{ To: courier.SendMessageParamsMessageToUnion{ OfUserRecipient: &shared.UserRecipientParam{ UserID: courier.String("user_123"), Context: shared.MessageContextParam{TenantID: courier.String("acme")}, }, }, Template: courier.String("nt_01kx4h2jdafq8bk9aftxak4b40"), Data: map[string]any{"name": "Sarah Bennett"}, Routing: courier.SendMessageParamsMessageRouting{ Method: string(shared.MessageRoutingMethodSingle), Channels: []shared.MessageRoutingChannelUnionParam{ {OfString: courier.String("inbox")}, }, }, }, }) ``` -------------------------------- ### openSettingsForApp Source: https://github.com/trycourier/courier-react-native Opens the OS settings screen for the current app. On iOS it calls `Courier.openSettingsForApp()`, on Android it uses the `ACTION_APPLICATION_DETAILS_SETTINGS` intent. Returns nothing. ```APIDOC ## openSettingsForApp ### Description Opens the OS settings screen for the current app. On iOS it calls `Courier.openSettingsForApp()`, on Android it uses the `ACTION_APPLICATION_DETAILS_SETTINGS` intent. Returns nothing. ### Method openSettingsForApp ### Returns Nothing. ``` -------------------------------- ### fromJson usage example Source: https://github.com/trycourier/courier-react-native Creates an InboxMessage from a JSON string. The example shows that a message with read: false still reports isRead as true. ```TypeScript const message = InboxMessage.fromJson( JSON.stringify({ messageId: 'msg_1', title: 'Welcome', read: false }) ); console.log(message.title, message.isRead); // "Welcome" true ``` -------------------------------- ### signIn Source: https://github.com/trycourier/courier-react-native Signs in a user with the provided credentials and options. ```APIDOC ## signIn ### Description Signs in a user with the provided credentials and options. ### Method async ### Signature `public async signIn(props: { accessToken: string; clientKey?: string; userId: string; tenantId?: string; apiUrls?: CourierApiUrls; showLogs?: boolean; }): Promise` ### Parameters #### Request Body - **accessToken** (string) - Required - JWT minted by your backend (scopes such as `inbox:read:messages`) - **clientKey** (string) - Optional - Client key - **userId** (string) - Required - Courier user id - **tenantId** (string) - Optional - Scopes the signed-in client to a tenant - **apiUrls** (CourierApiUrls) - Optional - Custom API endpoints (default: native defaults `DEFAULT_COURIER_API_URLS`) - **showLogs** (boolean) - Optional - Enables `Courier.log` debugging output; also stored as the client's `showLogs` (default: `__DEV__`) ### Returns - **Promise** - Resolves when sign-in completes. ### Request Example ```ts await Courier.shared.signIn({ userId: 'user_123', accessToken: jwt, tenantId: 'tenant_a', showLogs: true, }); ``` ```ts import Courier, { getCourierApiUrlsForRegion } from "@trycourier/courier-react-native"; try { await Courier.shared.signIn({ userId: 'user_123', accessToken: jwt, apiUrls: getCourierApiUrlsForRegion('eu'), // EU datacenter }); } catch (error) { // Rejects with the native error message; see errors.md console.error('Sign-in failed', error); } ``` ``` -------------------------------- ### Send message to tenant inbox (PHP) Source: https://github.com/trycourier/courier-react-native/blob/main/docs/send-to-the-inbox.md Send a message to a tenant's inbox using the PHP client. Set context.tenant_id on the recipient. ```php $client->send->message( message: [ 'to' => ['userID' => "user_123", 'context' => ['tenantID' => "acme"]], 'template' => "nt_01kx4h2jdafq8bk9aftxak4b40", 'data' => ['name' => "Sarah Bennett"], 'routing' => ['method' => "single", 'channels' => ["inbox"]], ], ); ``` -------------------------------- ### signIn: Sign in with access token and user ID Source: https://github.com/trycourier/courier-react-native Signs in a user with required accessToken and userId, optional clientKey, tenantId, apiUrls, and showLogs. Defaults apiUrls to native defaults and showLogs to __DEV__. Rejects with native error message on failure. ```ts public async signIn(props: { accessToken: string; clientKey?: string; userId: string; tenantId?: string; apiUrls?: CourierApiUrls; showLogs?: boolean; }): Promise ``` ```ts await Courier.shared.signIn({ userId: 'user_123', accessToken: jwt, tenantId: 'tenant_a', showLogs: true, }); ``` ```ts import Courier, { getCourierApiUrlsForRegion } from "@trycourier/courier-react-native"; try { await Courier.shared.signIn({ userId: 'user_123', accessToken: jwt, apiUrls: getCourierApiUrlsForRegion('eu'), // EU datacenter }); } catch (error) { // Rejects with the native error message; see errors.md console.error('Sign-in failed', error); } ``` -------------------------------- ### Set message.expiry with expires_in Source: https://github.com/trycourier/courier-react-native/blob/main/docs/send-to-the-inbox.md Use this JSON payload to set a message expiry using an ISO 8601 duration. The expiry clock starts when delivery starts, so a delayed send expires a day after it goes out, not a day after the call. Set either expires_in or expires_at, not both. ```json { "message": { "to": { "user_id": "user_123" }, "template": "nt_01kx4h2jdafq8bk9aftxak4b40", "routing": { "method": "single", "channels": ["inbox"] }, "expiry": { "expires_in": "P1D" } } } ``` -------------------------------- ### Send message to tenant inbox (C#) Source: https://github.com/trycourier/courier-react-native/blob/main/docs/send-to-the-inbox.md Send a message to a tenant's inbox using the C# client. Set context.tenant_id on the recipient. ```csharp await client.Send.Message(new SendMessageParams { Message = new Message { To = new To(new UserRecipient { UserID = "user_123", Context = new MessageContext { TenantID = "acme" } }), Template = "nt_01kx4h2jdafq8bk9aftxak4b40", Data = new Dictionary { { "name", JsonSerializer.SerializeToElement("Sarah Bennett") } }, Routing = new Routing { Method = Method.Single, Channels = new List { new MessageRoutingChannel("inbox") } } } }); ``` -------------------------------- ### fromJson error handling example Source: https://github.com/trycourier/courier-react-native Shows that invalid JSON causes JSON.parse to fail and the error is logged to console before being rethrown. ```TypeScript try { InboxMessage.fromJson('{not json}'); } catch (error) { // JSON.parse failed; the error was also logged to console } ``` -------------------------------- ### new CourierClient(props) Source: https://github.com/trycourier/courier-react-native Creates a new CourierClient instance with the provided options. Each client holds its own credentials and can be used concurrently. ```APIDOC ## new CourierClient(props) ### Description Creates a new CourierClient instance with the provided options. Each client holds its own credentials and can be used concurrently. ### Constructor #### Parameters - **props.userId** (string) - Required - Courier user id - **props.jwt** (string) - Optional - JWT access token - **props.clientKey** (string) - Optional - Client key - **props.connectionId** (string) - Optional - Inbox WebSocket connection id - **props.tenantId** (string) - Optional - Tenant scoping - **props.apiUrls** (CourierApiUrls) - Optional - API endpoints (default: native defaults) - **props.showLogs** (boolean) - Optional - Debug logging (default: `__DEV__`) ### Request Example ```ts import { CourierClient, getCourierApiUrlsForRegion } from "@trycourier/courier-react-native"; const client = new CourierClient({ userId: 'user_123', jwt, connectionId: 'conn_1', tenantId: 'tenant_a', apiUrls: getCourierApiUrlsForRegion('eu'), showLogs: true, }); ``` ``` -------------------------------- ### getInboxPaginationLimit / setInboxPaginationLimit Source: https://github.com/trycourier/courier-react-native Get or set the pagination limit for the shared inbox. The getter coerces the native result to a number. ```APIDOC ## getInboxPaginationLimit / setInboxPaginationLimit ### Description Get or set the pagination limit for the shared inbox. The getter coerces the native result to a number. ### Method async ### Endpoint `Courier.shared.getInboxPaginationLimit()` / `Courier.shared.setInboxPaginationLimit(limit)` ### Parameters #### Request Body - **limit** (number) - Required - Page size for the shared inbox (default: 32 native default) ### Response #### Success Response (Promise) - **number** - The current pagination limit ``` -------------------------------- ### Send message to tenant inbox (Java) Source: https://github.com/trycourier/courier-react-native/blob/main/docs/send-to-the-inbox.md Send a message to a tenant's inbox using the Java client. Set context.tenant_id on the recipient. ```java SendMessageParams.Message message = SendMessageParams.Message.builder() .to(SendMessageParams.Message.To.ofUserRecipient( UserRecipient.builder() .userId("user_123") .context(MessageContext.builder().tenantId("acme").build()) .build())) .template("nt_01kx4h2jdafq8bk9aftxak4b40") .data(SendMessageParams.Message.Data.builder() .putAdditionalProperty("name", JsonValue.from("Sarah Bennett")) .build()) .routing(SendMessageParams.Message.Routing.builder() .method(SendMessageParams.Message.Routing.Method.SINGLE) .channels(List.of(MessageRoutingChannel.ofString("inbox"))) .build()) .build(); client.send().message(SendMessageParams.builder().message(message).build()); ``` -------------------------------- ### Handling mutation failure Source: https://github.com/trycourier/courier-react-native Marking a message requires an active signed-in session; failures reject. This example shows try/catch around markAsRead. ```TypeScript // Marking a message requires an active signed-in session; failures reject. try { await message.markAsRead(); } catch (error) { console.error('Failed to mark as read', error); } ``` -------------------------------- ### Scope: Everything Source: https://github.com/trycourier/courier-react-native/blob/main/docs/authenticate-users.md Scope string granting all listed permissions: inbox, preferences, user-tokens, and brands. ```text user_id:user_123 inbox:read:messages inbox:write:events read:preferences write:preferences write:user-tokens read:brands ``` -------------------------------- ### Scope: Add the preference center Source: https://github.com/trycourier/courier-react-native/blob/main/docs/authenticate-users.md Scope string adding read:preferences and write:preferences for the embedded preference center. ```text user_id:user_123 inbox:read:messages inbox:write:events read:preferences write:preferences ``` -------------------------------- ### Send message to tenant inbox (Python) Source: https://github.com/trycourier/courier-react-native/blob/main/docs/send-to-the-inbox.md Send a message to a tenant's inbox using the Python client. Set context.tenant_id on the recipient. ```python client.send.message( message={ "to": {"user_id": "user_123", "context": {"tenant_id": "acme"}}, "template": "nt_01kx4h2jdafq8bk9aftxak4b40", "data": {"name": "Sarah Bennett"}, "routing": {"method": "single", "channels": ["inbox"]}, }, ) ``` -------------------------------- ### markAsClicked usage with try/catch Source: https://github.com/trycourier/courier-react-native Example of creating an InboxAction and calling markAsClicked. Resolves as no-op when no client is present; rejects when the underlying inbox.click call fails. ```TypeScript const action = new InboxAction('View', 'https://courier.com', { trackingId: 'trk_1' }); try { await action.markAsClicked('msg_1'); // resolves; no client present => no-op } catch (error) { // Rejected when the underlying inbox.click call fails } ``` -------------------------------- ### Manage user tokens with CourierClient Source: https://github.com/trycourier/courier-react-native/blob/main/docs/sdk-reference.md Shows how to put and delete user tokens using the client's tokens API. The device object is optional for putUserToken. ```typescript const device = { appId: "APP_ID", adId: "AD_ID", deviceId: "DEVICE_ID", platform: "ios", manufacturer: "Apple", model: "iPhone 15" }; await client.tokens.putUserToken({ token: "...", provider: "firebase-fcm", device // Optional }); await client.tokens.deleteUserToken({ token: "..." }); ``` -------------------------------- ### Using mutation helpers in CourierInboxView callback Source: https://github.com/trycourier/courier-react-native Example of toggling read/unread state in the onClickInboxMessageAtIndex callback. Uses the message's read property to decide which mutation to call. ```TypeScript { message.read ? message.markAsUnread() : message.markAsRead(); }} /> ``` -------------------------------- ### Sign in with tenantId Source: https://github.com/trycourier/courier-react-native/blob/main/docs/send-to-the-inbox.md Pass tenantId at sign-in to scope the inbox to a single tenant. Applies to every component, read, and realtime connection. ```jsx await Courier.shared.signIn({ accessToken: jwt, userId, tenantId: "acme" }); ``` -------------------------------- ### Read signed-in user and add authentication listener Source: https://github.com/trycourier/courier-react-native/blob/main/docs/authenticate-users.md Retrieve the current user, tenant, and sign-in status, and register a listener that fires on sign-in and sign-out. Use the listener to clear app state on sign-out or re-render after credentials are restored on launch. ```jsx const userId = await Courier.shared.getUserId(); const tenantId = await Courier.shared.getTenantId(); const isSignedIn = await Courier.shared.isUserSignedIn(); const listener = await Courier.shared.addAuthenticationListener({ onUserChanged: (userId) => console.log("User changed:", userId), }); await listener.remove(); ``` -------------------------------- ### Extend CourierReactNativeActivity in Java Source: https://github.com/trycourier/courier-react-native/blob/main/docs/sdk-reference.md Update MainActivity to extend CourierReactNativeActivity in Java. ```java import com.courierreactnative.CourierReactNativeActivity; public class MainActivity extends CourierReactNativeActivity { // ... } ``` -------------------------------- ### Set minimum SDK version in android/build.gradle Source: https://github.com/trycourier/courier-react-native/blob/main/docs/sdk-reference.md Set minSdkVersion, compileSdkVersion, and targetSdkVersion in your Android build.gradle. ```gradle ext { minSdkVersion = 23 compileSdkVersion = 36 targetSdkVersion = 36 } ``` -------------------------------- ### CourierPreferencesView with channels mode and theme Source: https://github.com/trycourier/courier-react-native Example usage of CourierPreferencesView with mode set to channels (email, push, sms) and custom light/dark themes. Requires a brand ID for theming. ```TSX import { CourierPreferencesView } from "@trycourier/courier-react-native"; ``` -------------------------------- ### new CourierClient(props) Source: https://github.com/trycourier/courier-react-native Constructor for the CourierClient class. Accepts configuration options to initialize the client. ```APIDOC ## new CourierClient(props) ### Description Creates a new CourierClient instance with the provided configuration options. ### Method Constructor ### Parameters #### Constructor Options - **userId** (string) - Required - Courier user id - **jwt** (string) - Optional - JWT for authenticated calls - **clientKey** (string) - Optional - Client key - **connectionId** (string) - Optional - Inbox WebSocket connection id - **tenantId** (string) - Optional - Tenant scoping - **apiUrls** (`CourierApiUrls`) - Optional - Custom endpoints; shallow-copied before storing. Default: native `CourierClient.ApiUrls()` defaults (the `DEFAULT_COURIER_API_URLS` values) - **showLogs** (boolean) - Optional - Debug logging; also forwarded to the native client. Default: `__DEV__` ### Response No return value documented. ``` -------------------------------- ### Send message to tenant inbox (CLI) Source: https://github.com/trycourier/courier-react-native/blob/main/docs/send-to-the-inbox.md Send a message to a tenant's inbox using the Courier CLI. Set context.tenant_id on the recipient. ```bash courier send message --message '{ "to": { "user_id": "user_123", "context": { "tenant_id": "acme" } }, "template": "nt_01kx4h2jdafq8bk9aftxak4b40", "data": { "name": "Sarah Bennett" }, "routing": { "method": "single", "channels": ["inbox"] } }' ``` -------------------------------- ### CourierInboxView Usage with Theme and Message Actions Source: https://github.com/trycourier/courier-react-native Example of using CourierInboxView with canSwipePages, theme customization, and onClickInboxMessageAtIndex to toggle read/unread state. The theme uses CourierInboxTheme objects with unreadIndicatorStyle and titleStyle. ```TSX import Courier, { CourierInboxView } from "@trycourier/courier-react-native"; { message.read ? Courier.shared.unreadMessage({ messageId: message.messageId }) : Courier.shared.readMessage({ messageId: message.messageId }); }} style={{ flex: 1 }} /> ``` -------------------------------- ### CourierInboxView onClickInboxActionForMessageAtIndex usage Source: https://github.com/trycourier/courier-react-native Example of using markAsClicked in a custom action handler. Opens the href if present and marks the action as clicked. Note: CourierInboxView already reports clicks natively; call this only when rendering your own action buttons. ```TypeScript { if (action.href) { Linking.openURL(action.href); } action.markAsClicked(message.messageId); }} /> ``` -------------------------------- ### Send message to tenant inbox (Node.js) Source: https://github.com/trycourier/courier-react-native/blob/main/docs/send-to-the-inbox.md Send a message to a tenant's inbox by setting context.tenant_id on the recipient. The message is visible only when the user signs in with the same tenant. ```javascript await client.send.message({ message: { to: { user_id: "user_123", context: { tenant_id: "acme" } }, template: "nt_01kx4h2jdafq8bk9aftxak4b40", data: { name: "Sarah Bennett" }, routing: { method: "single", channels: ["inbox"] }, }, }); ``` -------------------------------- ### Manage user preferences Source: https://github.com/trycourier/courier-react-native/blob/main/docs/sdk-reference.md Fetches user preferences and updates a specific topic with opt-in status, custom routing, and channel selection. ```typescript const prefs = await client.preferences.getUserPreferences({ paginationCursor: undefined }); const topic = await client.preferences.getUserPreferenceTopic({ topicId: "..." }); await client.preferences.putUserPreferenceTopic({ topicId: "...", status: CourierUserPreferencesStatus.OptedIn, hasCustomRouting: true, customRouting: [CourierUserPreferencesChannel.Push] }); ``` -------------------------------- ### Sign in with EU API URLs Source: https://github.com/trycourier/courier-react-native/blob/main/docs/authenticate-users.md Pass EU datacenter URLs via `apiUrls` when signing in with `Courier.shared.signIn`. Use `getCourierApiUrlsForRegion("eu")` to get the correct hosts. The JWT must be minted against the same region (EU) to authenticate. ```jsx import { getCourierApiUrlsForRegion } from "@trycourier/courier-react-native"; await Courier.shared.signIn({ userId, accessToken: jwt, apiUrls: getCourierApiUrlsForRegion("eu"), }); ``` -------------------------------- ### Send message with metadata.tags using Go Source: https://github.com/trycourier/courier-react-native/blob/main/docs/send-to-the-inbox.md Use the Courier Go client to send a message with metadata.tags set to ['order'] so it appears in an inbox tab filtered by that tag. The send uses routing method 'single' with the 'inbox' channel. A message can carry at most 9 tags, each up to 30 characters; exceeding either limit fails with a validation error on metadata.tags. ```go response, err := client.Send.Message(context.TODO(), courier.SendMessageParams{ Message: courier.SendMessageParamsMessage{ To: courier.SendMessageParamsMessageToUnion{ OfUserRecipient: &shared.UserRecipientParam{ UserID: courier.String("user_123"), }, }, Template: courier.String("nt_01kx4h2jdafq8bk9aftxak4b40"), Metadata: courier.SendMessageParamsMessageMetadata{ Tags: []string{"order"}, }, Routing: courier.SendMessageParamsMessageRouting{ Method: string(shared.MessageRoutingMethodSingle), Channels: []shared.MessageRoutingChannelUnionParam{ {OfString: courier.String("inbox")}, }, }, }, }) ``` -------------------------------- ### openSettingsForApp method signature Source: https://github.com/trycourier/courier-react-native Static method to open the OS settings screen for the current app. On iOS it calls Courier.openSettingsForApp(); on Android it uses ACTION_APPLICATION_DETAILS_SETTINGS intent. Returns nothing. ```TypeScript public static openSettingsForApp() ``` -------------------------------- ### Forward APNs callbacks to CourierDelegate in Swift AppDelegate Source: https://github.com/trycourier/courier-react-native/blob/main/docs/push-notifications.md In the iOS AppDelegate, hold a CourierDelegate and forward the APNs registration callbacks to it. This syncs the device token. CourierDelegate is not part of the package; copy it from the example app on GitHub. ```swift private let courierDelegate = CourierDelegate() func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { courierDelegate.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { courierDelegate.application(application, didFailToRegisterForRemoteNotificationsWithError: error) } ``` -------------------------------- ### open / read / unread / click / archive / readAll method signatures Source: https://github.com/trycourier/courier-react-native Signatures for the mutation methods. Each takes messageId (click also requires trackingId) and returns a Promise (HTTP status). ```TypeScript public async open(props: { messageId: String }): Promise public async read(props: { messageId: String }): Promise public async unread(props: { messageId: String }): Promise public async click(props: { messageId: String; trackingId: string }): Promise public async archive(props: { messageId: String }): Promise public async readAll(): Promise ``` -------------------------------- ### Sign in with JWT using Courier.shared.signIn Source: https://github.com/trycourier/courier-react-native/blob/main/docs/authenticate-users.md Pass the JWT and userId to signIn when the app starts or the user logs in. Until signIn runs, components render empty. On mobile, credentials persist across sessions; call signIn again only when the user changes or the token expires. ```jsx import { useEffect } from "react"; import Courier from "@trycourier/courier-react-native"; export default function App() { useEffect(() => { // jwt is the token your backend issued in step 1 Courier.shared.signIn({ accessToken: jwt, userId }); }, []); // ... render } ``` -------------------------------- ### Send message to tenant inbox (Ruby) Source: https://github.com/trycourier/courier-react-native/blob/main/docs/send-to-the-inbox.md Send a message to a tenant's inbox using the Ruby client. Set context.tenant_id on the recipient. ```ruby courier.send_.message( message: { to: { user_id: "user_123", context: { tenant_id: "acme" } }, template: "nt_01kx4h2jdafq8bk9aftxak4b40", data: { name: "Sarah Bennett" }, routing: { method: "single", channels: ["inbox"] } } ) ``` -------------------------------- ### getInboxPaginationLimit / setInboxPaginationLimit method signatures Source: https://github.com/trycourier/courier-react-native Method signatures for getting and setting the pagination limit of the shared inbox. The default limit is 32 (native default). getInboxPaginationLimit coerces the native result with Number(...) because older native modules resolved a string. ```TypeScript public async getInboxPaginationLimit(): Promise public async setInboxPaginationLimit(limit: number): Promise ``` -------------------------------- ### Courier constructor Source: https://github.com/trycourier/courier-react-native Instance constructor that sets initial iOS foreground presentation options to ['sound', 'badge', 'list', 'banner'] and attaches push notification native listeners. Not meant to be called directly; use Courier.shared. ```TypeScript public constructor() ``` -------------------------------- ### getNotificationPermissionStatus method signature Source: https://github.com/trycourier/courier-react-native Async static method to get the current notification permission status. Returns platform-specific values: iOS returns one of 'notDetermined', 'denied', 'authorized', 'provisional', 'ephemeral', 'unknown'; Android returns 'authorized' or 'denied', or 'unknown' when no activity is present. ```TypeScript public static async getNotificationPermissionStatus(): Promise ``` -------------------------------- ### Add Jitpack repository to android/build.gradle Source: https://github.com/trycourier/courier-react-native/blob/main/docs/sdk-reference.md Add the Jitpack repository to your Android build.gradle repositories. ```gradle allprojects { repositories { google() mavenCentral() maven { url 'https://www.jitpack.io' } } } ``` -------------------------------- ### Send message with metadata.tags using Java Source: https://github.com/trycourier/courier-react-native/blob/main/docs/send-to-the-inbox.md Use the Courier Java client to send a message with metadata.tags set to ['order'] so it appears in an inbox tab filtered by that tag. The send uses routing method SINGLE with the 'inbox' channel. A message can carry at most 9 tags, each up to 30 characters; exceeding either limit fails with a validation error on metadata.tags. ```java SendMessageParams.Message message = SendMessageParams.Message.builder() .to(SendMessageParams.Message.To.ofUserRecipient( UserRecipient.builder().userId("user_123").build())) .template("nt_01kx4h2jdafq8bk9aftxak4b40") .metadata(SendMessageParams.Message.Metadata.builder() .tags(List.of("order")) .build()) .routing(SendMessageParams.Message.Routing.builder() .method(SendMessageParams.Message.Routing.Method.SINGLE) .channels(List.of(MessageRoutingChannel.ofString("inbox"))) .build()) .build(); SendMessageResponse response = client.send().message( SendMessageParams.builder().message(message).build()); ``` -------------------------------- ### Send message with metadata.tags using C# Source: https://github.com/trycourier/courier-react-native/blob/main/docs/send-to-the-inbox.md Use the Courier C# client to send a message with metadata.tags set to ['order'] so it appears in an inbox tab filtered by that tag. The send uses routing method Single with the 'inbox' channel. A message can carry at most 9 tags, each up to 30 characters; exceeding either limit fails with a validation error on metadata.tags. ```csharp var response = await client.Send.Message(new SendMessageParams { Message = new Message { To = new To(new UserRecipient { UserID = "user_123" }), Template = "nt_01kx4h2jdafq8bk9aftxak4b40", Metadata = new() { Tags = ["order"] }, Routing = new Routing { Method = Method.Single, Channels = new List { new MessageRoutingChannel("inbox") } } } }); ``` -------------------------------- ### Scope: Add mobile push Source: https://github.com/trycourier/courier-react-native/blob/main/docs/authenticate-users.md Scope string adding write:user-tokens to sync push tokens from a mobile client. ```text user_id:user_123 inbox:read:messages inbox:write:events write:user-tokens ```