# React Native SDK

**Requirements:** React Native 0.75+, React 18+, iOS 15+ and/or Android API 26+. This SDK requires native modules and does **not** work with Expo Go. Use a development build.

**Source:** [github.com/WarpLinkApp/warplink-react-native-sdk](https://github.com/WarpLinkApp/warplink-react-native-sdk)

## Installation

```bash
npm install @warplink/react-native
```

The iOS SDK is distributed through Swift Package Manager and needs dynamic linkage, so add this to `ios/Podfile` inside your app target before installing pods:

```ruby
# ios/Podfile, inside your app target
use_frameworks! :linkage => :dynamic
```

```bash
cd ios && pod install
```

```bash
npx expo install @warplink/react-native
npx expo prebuild
```

## Platform Setup

The React Native SDK bridges to native iOS and Android SDKs. Both platforms need configuration.

### iOS

1. Open Xcode, select your app target > **Signing & Capabilities**
2. Add **Associated Domains** > `applinks:yourapp.aplnk.to`
3. Enable Associated Domains in your App ID at [developer.apple.com](https://developer.apple.com)

Find your app's subdomain in the dashboard: open the app, then **Settings**. Or see [Your app's own link address](https://warplink.app/docs/migration/aasa-subdomain).

For Expo, add to `app.json`:

```json
{
  "expo": {
    "ios": {
      "associatedDomains": ["applinks:yourapp.aplnk.to"]
    }
  }
}
```

### Android

Add the intent filter to your main Activity in `android/app/src/main/AndroidManifest.xml`:

```xml
<intent-filter android:autoVerify="true">
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" />
    <data android:scheme="https" android:host="yourapp.aplnk.to" />
</intent-filter>
```

For Expo, add to `app.json`:

```json
{
  "expo": {
    "android": {
      "intentFilters": [{
        "action": "VIEW",
        "autoVerify": true,
        "data": [{ "scheme": "https", "host": "yourapp.aplnk.to" }],
        "category": ["BROWSABLE", "DEFAULT"]
      }]
    }
  }
}
```

Serving links from a [custom domain](https://warplink.app/docs/concepts/custom-domains)? Add it to the associated domains and the intent filter alongside `yourapp.aplnk.to`, then declare it in [`configure()`](#declare-your-link-domains).

Every app has its own subdomain, `yourapp.aplnk.to`. Add that exact host, never a wildcard such as `applinks:*.aplnk.to` on iOS. If your app existed before subdomains, keep `aplnk.to` listed next to the new address: links you already have stay on `aplnk.to` and keep opening your app. See [Your app's own link address](https://warplink.app/docs/migration/aasa-subdomain).

## iOS AppDelegate Hook

iOS does not hand Universal Links to native modules on its own. Add the WarpLink call to the delegate methods you already have, and leave their return values to your existing linking code.

`handleIncomingURL` returns nothing and does no domain filtering, so never let it decide your delegate's return value. Keep returning whatever your existing forwarding returns, or the deep links your app already handles stop arriving. Forwarding every URL is safe: the SDK tries to resolve each one and silently drops anything that is not a WarpLink link, so custom schemes and OAuth callbacks never reach the `onLink` you passed to `configure()`. An explicit `onDeepLink()` subscriber can still receive them, as an `{ error }` event with code `E_INVALID_URL`.

```swift
// ios/YourApp/AppDelegate.swift
import React
import warplink_react_native

// Universal Links (https://): cold start and warm start
func application(
  _ application: UIApplication,
  continue userActivity: NSUserActivity,
  restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void
) -> Bool {
  if userActivity.activityType == NSUserActivityTypeBrowsingWeb,
     let url = userActivity.webpageURL {
    WarpLinkModule.handleIncomingURL(url)
  }
  return RCTLinkingManager.application(
    application, continue: userActivity, restorationHandler: restorationHandler)
}

// Custom URL schemes (myapp://): only if your app uses them
func application(
  _ application: UIApplication,
  open url: URL,
  options: [UIApplication.OpenURLOptionsKey: Any] = [:]
) -> Bool {
  WarpLinkModule.handleIncomingURL(url)
  return RCTLinkingManager.application(application, open: url, options: options)
}
```

```objc
// ios/YourApp/AppDelegate.mm
#import <React/RCTLinkingManager.h>
#import <warplink_react_native/warplink_react_native-Swift.h>

// Universal Links (https://): cold start and warm start
- (BOOL)application:(UIApplication *)application
    continueUserActivity:(NSUserActivity *)userActivity
      restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> *))restorationHandler
{
  if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb] &&
      userActivity.webpageURL != nil) {
    [WarpLinkModule handleIncomingURL:userActivity.webpageURL];
  }
  return [RCTLinkingManager application:application
                  continueUserActivity:userActivity
                    restorationHandler:restorationHandler];
}

// Custom URL schemes (myapp://): only if your app uses them
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
  [WarpLinkModule handleIncomingURL:url];
  return [RCTLinkingManager application:application openURL:url options:options];
}
```

The Swift module name is the pod name with hyphens replaced by underscores (`warplink_react_native`). If your delegate forwards to `super` as well as a linking library, keep every call and store each result in a local before you combine them. A `||` chain short-circuits, so a handler placed after one that returns `true` never runs.

### Expo

A plain `npx expo prebuild` layers its changes onto the native files already there, so a hand-edited `AppDelegate` usually survives it, but `npx expo prebuild --clean` deletes the native directories first and any build machine that starts without `ios/` regenerates the file from the template. In both of those cases the call you added by hand is gone. Pick one:

- Commit the generated `ios/` directory and add the calls to the `AppDelegate` there.
- Add the calls from an [Expo config plugin](https://docs.expo.dev/config-plugins/introduction/) with `withAppDelegate`, so they survive every prebuild.

Expo Go cannot load native modules, so a development build is required either way.

Android needs no host code: `configure()` handles cold start automatically, and warm start works once your launch Activity uses `android:launchMode="singleTask"`.

## iOS SceneDelegate Hook

Skip this section unless your app declares a `UIApplicationSceneManifest` in `Info.plist` and has a `SceneDelegate` that owns the window. That is the default shape of a plain Xcode single-view app template. Apple requires the scene life cycle for apps built with its newer SDKs: an app built without one does not launch at all. Once a scene manifest exists, iOS routes Universal Link and custom-scheme delivery to the scene, and stops calling the [AppDelegate hook](#ios-appdelegate-hook) above entirely. The AppDelegate methods stay in the app, but never run again. Nothing errors, nothing crashes, and `configure()` still reports the SDK as healthy. The app only stops resolving WarpLink links, silently.

Add the same call to the `SceneDelegate` methods that receive delivery once a scene owns the window: `scene(_:willConnectTo:options:)` for cold start, `scene(_:continue:)` for a Universal Link on a warm start, and `scene(_:openURLContexts:)` for a custom scheme on a warm start. Keep the `AppDelegate` hook too: it is harmless once a scene exists, and an app that later turns scenes off still needs it.

```swift
// ios/YourApp/SceneDelegate.swift
import React
import warplink_react_native

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
  var window: UIWindow?

  func scene(
    _ scene: UIScene,
    willConnectTo session: UISceneSession,
    options connectionOptions: UIScene.ConnectionOptions
  ) {
    // ... your existing window and React Native startup ...

    // Cold start: a Universal Link arrives here, never in the AppDelegate,
    // once a scene manifest exists.
    if let userActivity = connectionOptions.userActivities.first(where: {
      $0.activityType == NSUserActivityTypeBrowsingWeb
    }), let url = userActivity.webpageURL {
      WarpLinkModule.handleIncomingURL(url)
    } else if let urlContext = connectionOptions.urlContexts.first {
      WarpLinkModule.handleIncomingURL(urlContext.url)
    }
  }

  // Warm start, Universal Link (https://): the scene counterpart of the
  // AppDelegate's continue userActivity.
  func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
    if userActivity.activityType == NSUserActivityTypeBrowsingWeb,
       let url = userActivity.webpageURL {
      WarpLinkModule.handleIncomingURL(url)
    }
  }

  // Warm start, custom URL schemes (myapp://): only if your app uses them.
  // The scene counterpart of the AppDelegate's open url.
  func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    if let url = URLContexts.first?.url {
      WarpLinkModule.handleIncomingURL(url)
    }
  }
}
```

```objc
// ios/YourApp/SceneDelegate.h
#import <UIKit/UIKit.h>

@interface SceneDelegate : UIResponder <UIWindowSceneDelegate>
@property (nonatomic, strong) UIWindow *window;
@end
```

```objc
// ios/YourApp/SceneDelegate.m
#import "SceneDelegate.h"
#import <warplink_react_native/warplink_react_native-Swift.h>

@implementation SceneDelegate

- (void)scene:(UIScene *)scene
    willConnectToSession:(UISceneSession *)session
                  options:(UISceneConnectionOptions *)connectionOptions
{
  // ... your existing window and React Native startup ...

  NSUserActivity *userActivity = nil;
  for (NSUserActivity *activity in connectionOptions.userActivities) {
    if ([activity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) {
      userActivity = activity;
      break;
    }
  }
  if (userActivity != nil && userActivity.webpageURL != nil) {
    [WarpLinkModule handleIncomingURL:userActivity.webpageURL];
  } else if (connectionOptions.URLContexts.count > 0) {
    [WarpLinkModule handleIncomingURL:connectionOptions.URLContexts.anyObject.URL];
  }
}

// Warm start, Universal Link (https://): the scene counterpart of the
// AppDelegate's continueUserActivity.
- (void)scene:(UIScene *)scene continueUserActivity:(NSUserActivity *)userActivity
{
  if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb] &&
      userActivity.webpageURL != nil) {
    [WarpLinkModule handleIncomingURL:userActivity.webpageURL];
  }
}

// Warm start, custom URL schemes (myapp://): only if your app uses them.
// The scene counterpart of the AppDelegate's open url.
- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts
{
  NSURL *url = URLContexts.anyObject.URL;
  if (url != nil) {
    [WarpLinkModule handleIncomingURL:url];
  }
}

@end
```

Register the delegate the way any React Native scene-based app does: name this class in `Info.plist`'s `UIApplicationSceneManifest` (`$(PRODUCT_MODULE_NAME).SceneDelegate` in Swift, the plain class name in Objective-C), or return it from `application(_:configurationForConnecting:options:)` if you configure scenes in code. Neither step is specific to WarpLink.

`handleIncomingURL` still returns nothing and does no domain filtering here either, so forwarding every url from these methods is exactly as safe as forwarding every url from the AppDelegate hook, for the same reason: the SDK resolves what it recognizes and silently drops the rest.

**React Native's own `Linking` API.** If you also forward to `RCTLinkingManager` from these scene methods (`RCTLinkingManager.application(_:continue:restorationHandler:)`, `RCTLinkingManager.application(_:open:options:)`), a warm start keeps `Linking.addEventListener('url', ...)` working: neither call depends on which delegate makes it. Cold-start links reach your app through the SceneDelegate hook above.

## Configure the SDK

Call `configure()` once at app startup, **outside** of any React component. Pass an `onLink` callback and the SDK wires cold start, warm start, and the deferred deep link check into that single sink.

The credential below is an **SDK key**, created in the dashboard under **Keys** > **SDK keys**. Configure the SDK with an SDK key, since only an SDK key records installs. If your organization has several apps, create the key for this app: a key tied to one app is refused for any other app with `KEY_APP_MISMATCH`.

```tsx
import { WarpLink } from '@warplink/react-native';

WarpLink.configure({
  apiKey: 'wl_live_yoursdkkeyhere000000000000000000',
  debugLogging: true, // Enable native console logging
  onLink: ({ deepLink, error }) => {
    if (error || !deepLink) return; // resolution or config failure
    // Fired for taps AND deferred installs. Check deepLink.isDeferred.
    navigateTo(deepLink.destination);
  },
});
```

`configure()` returns a `Promise<void>`. A configuration failure is delivered to `onLink` as `{ error }` when you pass `onLink`, as in the example above. Only when you omit `onLink` does the returned promise reject with the error instead, so `await` it in that case:

```tsx
try {
  await WarpLink.configure({ apiKey: 'wl_live_yoursdkkeyhere000000000000000000' });
} catch (error) {
  // No onLink was passed, so a configuration failure rejects here instead.
}
```

### Declare Your Link Domains

The SDK always recognizes `aplnk.to`. List your app's subdomain, `yourapp.aplnk.to`, and any custom domain you serve links from in `linkDomains`. `configure()` passes the list straight to the native iOS and Android SDKs, so a link on those hosts resolves on the very first launch, with no network round trip.

```tsx
WarpLink.configure({
  apiKey: 'wl_live_yoursdkkeyhere000000000000000000',
  linkDomains: ['yourapp.aplnk.to', 'links.yourapp.com', 'go.yourapp.com'],
  onLink: ({ deepLink }) => deepLink && navigateTo(deepLink.destination),
});
```

With `linkDomains` set, your own links resolve inside the SDK on the very first launch.

The native declaration works too, and is read before any JavaScript runs: a `WarpLinkDomains` array in `Info.plist` on iOS, an `app.warplink.DOMAINS` meta-data entry in `AndroidManifest.xml` on Android. See the [iOS](https://warplink.app/docs/sdks/ios#declare-your-link-domains) and [Android](https://warplink.app/docs/sdks/android#declare-your-link-domains) guides. Expo apps can set the iOS key through `expo.ios.infoPlist` in `app.json`, and the Android entry from a config plugin.

Every form is optional and additive. Domains are normalized natively (trimmed, lowercased, a full URL reduced to its host), so paste whichever form you have.

### Opt Out of Automatic Handling

Both pieces are on by default. Disable either to drive it yourself with the manual methods:

```tsx
WarpLink.configure({
  apiKey: 'wl_live_yoursdkkeyhere000000000000000000',
  automaticDeepLinks: false,          // use onDeepLink / getInitialDeepLink yourself
  automaticDeferredDeepLinks: false,  // use checkDeferredDeepLink yourself
});
```

## Testing

### iOS: Physical Device Required

1. Build and run on a physical device
2. Paste your test link (e.g., `https://yourapp.aplnk.to/abc123`) into Notes or Messages and tap it. Typing it into the Safari address bar never opens the app.
3. The app should open and trigger the deep link callback
4. Check Xcode console for `[WarpLink]` log messages

On the iOS Simulator, `xcrun simctl openurl booted https://yourapp.aplnk.to/abc123` opens the app only when its Associated Domains entitlement lists the host and the domain serves a valid apple-app-site-association file that matches the path. Confirm the iOS path on a physical device before you ship.

### Android: Physical Device or Emulator

```bash
# Verify App Links status
adb shell pm get-app-links com.yourcompany.yourapp

# Open a test link
adb shell am start -a android.intent.action.VIEW \
    -d "https://yourapp.aplnk.to/abc123" com.yourcompany.yourapp

# Filter Logcat for WarpLink messages
adb logcat -s WarpLink
```

Android App Links work on both a physical device and the emulator, unlike iOS Universal Links.

### Deferred Deep Links

Testing a deferred deep link, meaning a click that happens before the app is installed, needs a delete/uninstall-then-reinstall cycle so the SDK treats it as a fresh install. See [Testing](https://warplink.app/docs/sdks/react-native/deferred#testing) in the Deferred Deep Links guide.

## Keep a link through the App Store with Tether

Tether carries a link through the App Store install on iPhone. The page the person tapped copies a short code, and the SDK reads it by read mode. Tether needs SDK 1.4.0 or newer. Android needs no change, because the install referrer carries the link.

Set `tetherReadMode` to `'pasteButton'` (the default), `'automatic'` or `'onCall'`.

```tsx
await WarpLink.configure({ apiKey: warpLinkKey, tetherReadMode: 'pasteButton' });

// In the first-run screen. The system asks only after a tap.
<WarpLinkPasteButton onResult={(result) => result.kind === 'matched' && open(result.link)} />;
```

In `'onCall'` mode, call `WarpLink.readTether()`. After the SDK reads a test code, `await WarpLink.lastTetherTestReceipt()` returns the receipt. Pass it to `verify_setup` as `tether_test_receipt`. See [Tether](https://warplink.app/docs/tether/sdk-modes) for the modes, the [privacy page](https://warplink.app/docs/tether/privacy) for the App Review note, and [Test Tether](https://warplink.app/docs/tether/testing) for the check.

## Use a Test key in debug builds

Use a `wl_test_` key in debug builds and a `wl_live_` key in release builds. A Test key reads and writes [Test mode](https://warplink.app/docs/concepts/test-mode) data only, and the SDK keeps its stored attribution apart from live state on the same device.

```typescript
const warpLinkKey = __DEV__
  ? 'wl_test_yoursdkkeyhere000000000000000000'
  : 'wl_live_yoursdkkeyhere000000000000000000';
```

To test a first install again without deleting the app, call `WarpLink.clearAttribution()`. It clears the attribution stored on the device and starts a new check. With a `wl_live_` key it does nothing and succeeds. If a stored item cannot be deleted, it fails with `E_STORAGE_ERROR` and the message "Could not clear stored attribution data." Calling it again is safe. See [Test your integration](https://warplink.app/docs/guides/testing).

## Next Steps

- [Deep Links](https://warplink.app/docs/sdks/react-native/deep-links): Cold start, warm start, and React Navigation
- [Deferred Deep Links](https://warplink.app/docs/sdks/react-native/deferred): Preserve context through installs
- [Attribution](https://warplink.app/docs/sdks/react-native/attribution): Platform-specific matching and privacy
- [Tether](https://warplink.app/docs/tether): Keep a link through the App Store on iPhone
- [Referral Invitations](https://warplink.app/docs/sdks/react-native/attribution#referral-invitations): Redeem a pasted invitation and credit a referral
- [API Reference](https://warplink.app/docs/sdks/react-native/api-reference): Full TypeScript API documentation
