Skip to main content

React Native Integration

Prerequisites

  1. siteKey from Selwise dashboard.
  2. Mobile public API key from Dashboard -> Sites -> Overview -> Mobile API Keys.
  3. API URL ending with /api/v1.
  4. Expo or Bare RN app with fetch support.

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)

  1. Open site overview.
  2. Create key for mobile client.
  3. Choose scopes by use case:
  • mobile_read for GET endpoints
  • mobile_write for POST/PUT/PATCH/DELETE endpoints
  1. 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

FieldRequiredDefaultNotes
siteKeyYes-Site public key.
apiKeyYes-Mobile scoped key (mobile_read, mobile_write).
apiUrlNohttps://api.selwise.com/api/v1Base API URL.
sdkPlatformNoreact-nativeSent in x-selwise-client-platform.
sdkVersionNo0.1.0Sent in x-selwise-client-version.
flushIntervalMsNo15000Periodic queue flush interval.
batchSizeNo25Max events per flush batch.
maxRetriesNo5Retry attempts per failed event.
maxQueueSizeNo500Queue cap; oldest entries trimmed first.
journeyTtlMsNo1800000Journey validity duration.
storagePrefixNoselwise_rnKey prefix in storage.
storageNoAsyncStorage if available, in-memory fallbackCustom storage adapter (getItem/setItem/removeItem).

Scope Behavior

HTTP MethodRequired Scope
GETmobile_read
POST, PUT, PATCH, DELETEmobile_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',
});
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

  1. sdk.init(...) resolves successfully.
  2. getVisitorId() and getSessionId() return stable values.
  3. Headers are present on requests:
  • x-selwise-api-key
  • x-selwise-client-platform
  • x-selwise-client-version
  1. track() + flush() reaches POST /public/sites/:siteKey/events/batch.
  2. trackOrder() reaches POST /public/sites/:siteKey/orders.
  3. Consent writes succeed with mobile_write scope.
  4. Offline -> online flow drains queued events.

Full runbook: Verification

Troubleshooting (Common)

  1. 403 invalid API key or scope.
  • Verify key is active and has required method scope.
  1. Queue never drains.
  • Call await sdk.flush() manually and check network connectivity/retry window.
  1. 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.Selwise global binding

Next