Skip to content
NanoFlags
Start free

SDKs

React Native SDK

@nanoflags/react-native evaluates flags on the device, locally and synchronously, against a signed configuration that the edge pushes over a live WebSocket. It runs the same engine and client core as the JavaScript SDK, keeps the last verified configuration on the device for offline starts, and pauses its connection while the app is in the background.

Install

Install
npx expo install @nanoflags/react-native @react-native-async-storage/async-storage @react-native-community/netinfo
# or: npm install @nanoflags/react-native @react-native-async-storage/async-storage @react-native-community/netinfo
  • React Native 0.76 or newer (Expo SDK 52+), Hermes or JSC, React 18+. No native code of its own, so it works in Expo Go.
  • AsyncStorage (persistence) and NetInfo (connectivity) are optional peer dependencies. Without them the SDK keeps the configuration in memory only and does not react to connectivity changes.
  • No runtime dependencies: the engine, the client core and a pure-JavaScript Ed25519 verifier are compiled into the package. It is tested against the shared parity fixtures (21,998 cases) through the built package, so results match every other NanoFlags SDK.
  • Apache-2.0. Source in the nanoflags-sdk repository.

Client keys

Anyone can unpack a mobile app, so the SDK accepts browser/client keys (nf_pub_…) only. The edge sends them the client view: the flags marked client-exposed and only the segments those flags reference. A server key (nf_srv_…) makes createClient throw before any request is made. Copy the key from Settings → SDK keys in the dashboard.

Quickstart

flags.ts
import AsyncStorage from "@react-native-async-storage/async-storage";
import NetInfo from "@react-native-community/netinfo";
import { asyncStorage, createClient } from "@nanoflags/react-native";

// One client per app, created at module scope.
export const flags = createClient({
  sdkKey: "nf_pub_…",
  storage: asyncStorage(AsyncStorage),
  netInfo: NetInfo,
  context: { key: deviceId }, // anonymous until sign-in
});
App.tsx
import { NanoFlagsProvider, useBoolFlag, useFlag, useNanoFlags } from "@nanoflags/react-native";
import { flags } from "./flags";

export default function App() {
  return (
    <NanoFlagsProvider client={flags}>
      <Checkout />
    </NanoFlagsProvider>
  );
}

function Checkout() {
  const { loading, identify } = useNanoFlags();
  const newCheckout = useBoolFlag("new-checkout"); // false until loaded, or if missing
  const accent = useFlag("accent", "blue");         // typed by the fallback
  if (loading) return <Spinner />;                  // optional: the first load attempt is still running
  return <CheckoutScreen variant={newCheckout ? "new" : "classic"} accent={accent}
    onSignIn={(user) => identify({ key: user.id, plan: user.plan })} />;
}

Outside React:

ts
flags.on("error", (e) => console.warn(e.code, e.message)); // attach before ready()
await flags.ready();                                  // never rejects; check flags.status
flags.boolean("new-checkout", false);
flags.identify({ key: user.id, plan: "pro", country: "SA" }); // local and synchronous: no request
flags.detail("accent", "blue");  // { value, reason, ruleId, ruleIndex, revision, … }
flags.allFlags();                 // { "new-checkout": true, accent: "orange", … }

Accessors never perform I/O and never throw. Without a configuration, for a missing flag, or when the flag serves another type, they return your fallback. A runnable Expo app is in example/.

React hooks

Hook or componentWhat it does
<NanoFlagsProvider client context?>Makes the client available; context (optional) is merged over the client's context.
useFlag(key, fallback, ctx?)Typed by the fallback (boolean, string, number, otherwise JSON). Re-renders on new revisions and on identify().
useBoolFlag(key, fallback = false, ctx?)Boolean shorthand.
useFlagDetail(key, fallback, ctx?)detail() as a hook.
useAllFlags(ctx?)allFlags() as a hook.
useNanoFlags(){ client, loading, status, revision, hasBundle, transport, lifecycle, context, identify, refresh }. loading is true until the first load attempt (storage and network) has finished. No Suspense involved.
useFlagsStatus(){ status, revision, hasBundle }

Client API

ts
createClient({
  sdkKey,                           // nf_pub_… (required)
  baseUrl?: string,                 // default "https://edge.nanoflags.io"
  context?: Context,                // initial context; identify() replaces it
  service?: string,                 // service-report name, default "react-native"
  bootstrap?: Bundle,               // bundle shipped with the app, used until a newer one is loaded
  storage?: StorageAdapter | false, // default: memory only. asyncStorage(AsyncStorage), memoryStorage(), or your own
  netInfo?: NetInfo,                // @react-native-community/netinfo default export (optional)
  appState?: AppState | null,       // default React Native's AppState; null = no lifecycle handling
  pauseInBackground?: boolean,      // true
  dataSaver?: boolean,              // true: no live socket on metered connections (ETag polling only)
  pollIntervalMs?: number,          // 30000 while the socket is not in use; 0 disables polling
  livePollIntervalMs?: number,      // 300000 safety poll while the socket is healthy
  streaming?: boolean,              // true; false = polling only
  live?: boolean,                   // true; false = SSE + polling
  events?: EventsOptions | false,   // telemetry; false opts out
  verify?: VerifyOptions | false,   // default: embedded keys, signatures required on the official edge
})
MemberReturns
ready()Resolves once a usable bundle is loaded (network, storage or bootstrap) or the first load attempt finished without one. Never rejects.
status · settled"not-ready", "ready" or "stale" (last known bundle: offline, paused, or an update was refused) · whether the first load attempt finished.
revision · transportThe revision in use (null without one) · "live", "stream" or "poll".
context · identify(ctx)The current context · replace it. Evaluations without an explicit context use it; an explicit context is merged over it.
boolean / string / number / json(key, fallback, ctx?)The value, or the fallback.
detail(key, fallback, ctx?)Value plus reason, ruleId, ruleIndex, inRollout, revision, trace.
allFlags(ctx?)Values of every flag delivered to this key.
lifecycle{ background, offline, metered, paused, realtime }
on("update" | "error", cb)update: { revision, previousRevision, source, transport, latencyMs }. error: a NanoFlagsError with a code (signature, network, unauthorized, store, engine, environment_deleted, …).
refresh() · flush() · close()Revalidate now · send telemetry now · stop everything (evaluations keep working).

How updates arrive

  1. Live WebSocket (wss://…/v1/live): the edge pushes each new signed bundle the moment it is published. The key travels in the subprotocol list, never in the URL. Ping about every 30 seconds, the socket is replaced about every 50 minutes, and reconnects use jittered backoff (1 s · 2ⁿ, up to 5 minutes).
  2. Server-sent events (/v1/stream) over XMLHttpRequest (React Native's fetch cannot stream) when no socket can be opened.
  3. Polling of /v1/bundle with If-None-Match (a 304 is a few hundred bytes): every 30 seconds without a socket, every 5 minutes as a safety net with one.

Close code 4004 (environment deleted) stops reconnecting: the last configuration stays in use, status becomes stale, and an environment_deleted error is emitted.

App lifecycle and battery

EventWhat the SDK does
App goes to the background (AppState "background")Closes the socket, stops polling, sends queued telemetry once. Evaluations keep working from memory.
Back to the foreground ("active")One conditional request right away to catch up on anything published meanwhile, then the socket again.
"inactive" (iOS app switcher, incoming call)Nothing.
Offline (NetInfo) / back onlinePause / revalidate and reconnect.
Metered connection (NetInfo isConnectionExpensive) with dataSaver (default)No socket: ETag polling only.
Started in the background (headless task)Loads the stored bundle; no network until the app becomes active.

Offline-first persistence

storage takes any { getItem, setItem } object, synchronous or asynchronous. The SDK stores the last verified bundle with the signature it was accepted with, under one key per SDK key and edge. At launch the stored bundle is verified again before it is used (status stale until the edge confirms it); a modified or unsigned copy is ignored. bootstrap takes a bundle shipped with the app for the very first start.

ts
// Any synchronous or asynchronous key-value store works:
createClient({ sdkKey, storage: { getItem: (k) => store.get(k) ?? null, setItem: (k, v) => store.set(k, v) } });

Signature verification

With the default baseUrl, every bundle (fetched, pushed or loaded from storage) must carry a valid Ed25519 signature by one of the official signing keys, which are embedded in the package. When a bundle names an unknown key id, GET /v1/keys is loaded once (at most once a minute). Unsigned or tampered bundles are refused: the previous bundle stays in use and an error with code: "signature" is emitted. Verification runs in pure JavaScript, because Hermes has no WebCrypto; pass crypto to use a native implementation instead. For a self-hosted edge pass verify: { publicKeys: [...], require: true }. See Security for the signed string.

OpenFeature provider

ts
import { OpenFeature } from "@openfeature/react-sdk";
import { NanoFlagsReactNativeProvider } from "@nanoflags/react-native/openfeature";

await OpenFeature.setProviderAndWait(new NanoFlagsReactNativeProvider({ client: flags }));
await OpenFeature.setContext({ targetingKey: user.id, plan: "pro" }); // → flags.identify({ key: user.id, plan: "pro" })

A provider for the static-context paradigm (@openfeature/web-sdk and @openfeature/react-sdk, both of which run in React Native), with the same mapping as the web provider: targetingKey becomes key; reasons TARGETING_MATCH, SPLIT, DEFAULT, DISABLED, ERROR; the variant is the rule id; events READY, STALE, ERROR, CONFIGURATION_CHANGED.

Telemetry

As in every NanoFlags SDK: a service report (sdk: "react-native/0.1.0" and the revision in use) and a sample (10 % by default) of evaluations with the flag, value, reason and revision. Context values are never sent, only the names of the attributes the flag's rules use and their types. events: { sampleRate } tunes it, events: false turns it off. Telemetry is flushed when the app goes to the background.

Troubleshooting

  1. createClient throws about the key. Use a browser/client key (nf_pub_…); server keys are refused in apps.
  2. A flag always returns its fallback. Mark the flag client-exposed and publish: client keys only receive client-exposed flags.
  3. Code signature. A bundle did not verify and was not used. With a custom baseUrl, pin that edge's keys.
  4. Nothing persists on Android. Android's AsyncStorage refuses values above about 2 MB by default; use another storage adapter for very large configurations.
  5. Code environment_deleted. The edge closed the socket with 4004; the client keeps its last configuration as stale. Replace the key.
Other mobile platforms
Native SDKs exist for Flutter, iOS (Swift) and Android (Kotlin), with the same engine and the same results.