React Native Integration
Prerequisites
siteKeyfrom Selwise dashboard.- Mobile public API key from
Dashboard -> Sites -> Overview -> Mobile API Keys. - API URL ending with
/api/v1. - Expo or Bare RN app with
fetchsupport.
Currency rule: use ISO-4217 uppercase codes and replace SITE_CURRENCY in examples with your configured site currency.
Installation
npm install @selwise/react-native @react-native-async-storage/async-storage
Supports Expo and Bare React Native.
Create Mobile API Key (Dashboard)
- Open site overview.
- Create key for mobile client.
- Choose scopes by use case:
mobile_readfor GET endpointsmobile_writefor POST/PUT/PATCH/DELETE endpoints
- Copy one-time secret and store it in your secure secret flow.
Initialization
import Selwise from '@selwise/react-native';
const sdk = new Selwise();
await sdk.init({
siteKey: 'YOUR_SITE_KEY',
apiUrl: 'https://api.selwise.com/api/v1',
apiKey: 'YOUR_MOBILE_API_KEY',
sdkVersion: '0.1.2',
});
apiKey is required for mobile requests.
Full Config Contract
| Field | Required | Default | Notes |
|---|---|---|---|
siteKey | Yes | - | Site public key. |
apiKey | Yes | - | Mobile scoped key (mobile_read, mobile_write). |
apiUrl | No | https://api.selwise.com/api/v1 | Base API URL. |
sdkPlatform | No | react-native | Sent in x-selwise-client-platform. |
sdkVersion | No | 0.1.0 | Sent in x-selwise-client-version. |
flushIntervalMs | No | 15000 | Periodic queue flush interval. |
batchSize | No | 25 | Max events per flush batch. |
maxRetries | No | 5 | Retry attempts per failed event. |
maxQueueSize | No | 500 | Queue cap; oldest entries trimmed first. |
journeyTtlMs | No | 1800000 | Journey validity duration. |
storagePrefix | No | selwise_rn | Key prefix in storage. |
storage | No | AsyncStorage if available, in-memory fallback | Custom storage adapter (getItem/setItem/removeItem). |
Scope Behavior
| HTTP Method | Required Scope |
|---|---|
GET | mobile_read |
POST, PUT, PATCH, DELETE | mobile_write |
Screen Context
Update context on navigation changes so events/orders include current path and referrer.
sdk.setScreenContext({
name: 'ProductDetail',
path: '/products/sku-123',
referrer: '/home',
});
Identity and Consent
await sdk.identify('user_42', { email: 'user@example.com', tier: 'gold' });
await sdk.setTraits({ locale: 'en', marketingOptIn: true });
console.log(sdk.getVisitorId());
console.log(sdk.getSessionId());
console.log(sdk.getJourneyState());
sdk.grantConsent({
categories: {
necessary: true,
analytics: true,
marketing: false,
preferences: true,
},
});
sdk.revokeConsent(['analytics']);
Event Sending
sdk.track('product_view', {
entityType: 'product',
entityId: 'sku-123',
metadata: { productItemCode: 'sku-123', source: 'pdp' },
});
await sdk.flush();
Queue lifecycle:
track()appends canonical events to queue.- Flush runs periodically (
flushIntervalMs) and on app background transitions. - Failed batches retry with exponential backoff up to
maxRetries.
track vs pushDataLayer in RN
track(...)-> network-intended event queue (events/batch).pushDataLayer(...)-> local snapshot store only (getDataLayer()), useful for local/debug/in-app mirroring.
Order Tracking
await sdk.trackOrder({
orderId: 'ORDER-1001',
currency: 'SITE_CURRENCY',
total: 149.9,
items: [{ productItemCode: 'sku-123', quantity: 1, unitPrice: 149.9 }],
});
Search and Recommendation Usage (Headless)
const siteConfig = await sdk.getSiteConfig();
const searchConfig = await sdk.getSearchConfig();
const searchResult = await sdk.search('shoe', { limit: 20, inStock: true });
const suggestions = await sdk.getSearchSuggestions();
const widgets = await sdk.getRecommendationWidgets({ pageUrl: '/home' });
const products = await sdk.getRecommendationProducts('widget_id', {
currentProductId: 'sku-123',
});
Secret Management (Expo and Bare RN)
Expo
- Store API key in EAS secrets or secure runtime config.
- Do not hardcode key in source files.
- Inject at build/runtime and pass into
sdk.init(...).
Bare React Native
- Use environment injection through native build system (Xcode/Gradle) or secure config providers.
- Avoid committing key to repository or plain config files.
- Rotate key immediately on suspected leak.
Verification Checklist
sdk.init(...)resolves successfully.getVisitorId()andgetSessionId()return stable values.- Headers are present on requests:
x-selwise-api-keyx-selwise-client-platformx-selwise-client-version
track()+flush()reachesPOST /public/sites/:siteKey/events/batch.trackOrder()reachesPOST /public/sites/:siteKey/orders.- Consent writes succeed with
mobile_writescope. - Offline -> online flow drains queued events.
Full runbook: Verification
Troubleshooting (Common)
- 403 invalid API key or scope.
- Verify key is active and has required method scope.
- Queue never drains.
- Call
await sdk.flush()manually and check network connectivity/retry window.
- Search/recommendation data exists but no UI.
- SDK is headless; rendering is your responsibility.
Full matrix: Integration Troubleshooting
Production Go-Live Checklist
- Mobile API key created with least-privilege scopes.
- Key injected via secure secret management (not hardcoded).
- Screen context wired to navigation changes.
- Tracking/order/consent probes pass on staging device.
- Retry/backoff behavior validated in offline recovery scenario.
Not Supported in RN v1
- DOM widget/campaign rendering
- script injection
window.Selwiseglobal binding