Skip to content

React Native and Expo quickstart ​

Build an iOS and Android screen that reads a public BTC-USD REST price and subscribes to WebSocket prices with coinbase-api. No API key is needed. Prices are BTC-USD last traded prices.

Use Node.js 24 and npm, with an iOS simulator or Android emulator and a matching Expo Go installation. iOS simulators require macOS and Xcode; Android virtual devices can be created with Android Studio or the Android SDK command-line tools. You can also view the complete Coinbase Expo example on GitHub.

See Runtime compatibility for runtime requirements.

This example reads public market data only. The supplied configuration disables the SDK’s Node-only JWT signing helper. Keep both Metro configuration files and coinbase-public-auth.cjs. Run authenticated calls on your Node.js server.

Create the project ​

sh
mkdir coinbase-expo-quickstart
cd coinbase-expo-quickstart

1. Create package.json ​

Declare the SDK dependency and the commands used by this project.

json
{
  "name": "coinbase-expo-quickstart",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "expo start",
    "ios": "expo start --ios",
    "android": "expo start --android"
  },
  "dependencies": {
    "coinbase-api": "latest",
    "expo": "58.0.23",
    "react": "19.3.0",
    "react-native": "0.88.1",
    "buffer": "6.0.3",
    "events": "3.3.0",
    "https-browserify": "1.0.0",
    "stream-http": "3.2.0",
    "url": "0.11.4"
  },
  "main": "index.js"
}

2. Create app.json ​

Name the Expo app and enable iOS and Android.

json
{
  "expo": {
    "name": "Coinbase price screen",
    "slug": "coinbase-price-screen",
    "version": "1.0.0",
    "platforms": [
      "ios",
      "android"
    ]
  }
}

3. Install dependencies ​

Run this after saving package.json:

sh
npm install

4. Create coinbase-public-auth.cjs ​

Disable JWT signing in this public-market-data app. Keep authenticated API calls on a Node.js server.

js
// This app reads public market data only. Keep API credentials on your server.
function signJWT() {
  throw new Error('JWT signing is server-only in this public market-data starter.');
}
module.exports = { signJWT, signWSJWT: signJWT };

5. Create siebly-sdk.metro.cjs ​

Resolve Node-style HTTP imports to the configured React Native polyfills.

js
const path = require('node:path');

module.exports = function configureSdkMetro(config, projectRoot) {
  const aliases = {
    https: require.resolve('https-browserify', { paths: [projectRoot] }),
    http: require.resolve('stream-http', { paths: [projectRoot] }),
    url: require.resolve('url/', { paths: [projectRoot] }),
  };
  const previousResolveRequest = config.resolver.resolveRequest;

  config.resolver.resolveRequest = (context, moduleName, platform) => {
    // Replace Coinbase's Node-only JWT implementation for this public-market-data app.
    if (moduleName.endsWith('/jwtNode.js') &&
        context.originModulePath.startsWith(path.join(projectRoot, 'node_modules/coinbase-api') + path.sep)) {
      return { type: 'sourceFile', filePath: path.join(projectRoot, 'coinbase-public-auth.cjs') };
    }
    if (aliases[moduleName]) {
      return { type: 'sourceFile', filePath: aliases[moduleName] };
    }

    const resolveRequest = previousResolveRequest || context.resolveRequest;
    return resolveRequest(context, moduleName, platform);
  };

  return config;
};

6. Create metro.config.cjs ​

Apply the SDK resolver to Expo’s default Metro configuration.

js
const { getDefaultConfig } = require('expo/metro-config');
const configureSdkMetro = require('./siebly-sdk.metro.cjs');

const config = getDefaultConfig(__dirname);

module.exports = configureSdkMetro(config, __dirname);

7. Create App.js ​

Build the native screen. Its effect reads the price, subscribes to updates and closes the connection when the price panel unmounts.

js
import React, { useEffect, useState } from 'react';
import { Button, SafeAreaView, Text, View } from 'react-native';
import { CBAdvancedTradeClient, WebsocketClient } from 'coinbase-api';

function Prices() {
  const [restPrice, setRestPrice] = useState('Loading');
  const [livePrice, setLivePrice] = useState('Connecting');
  const [error, setError] = useState('');

  useEffect(() => {
    let mounted = true;
    const ws = new WebsocketClient();

    function showError(error) {
      console.error(error);
      if (mounted) {
        setError(error instanceof Error ? error.message : String(error));
      }
    }

    async function loadPrice() {
      const client = new CBAdvancedTradeClient();
      const ticker = await client.getPublicProduct({ product_id: 'BTC-USD' });
      const price = ticker.price;

      if (!price) {
        throw new Error('No price was returned.');
      }

      if (mounted) {
        setRestPrice(String(price));
      }
    }

    loadPrice().catch(showError);

    const timeout = setTimeout(() => {
      showError(new Error('No BTC-USD update within 30 seconds.'));
    }, 30_000);

    ws.on('update', (message) => {
      if (message.channel !== 'ticker') {
        console.log('WebSocket update:', message);
        return;
      }

      let price;
      for (const event of message.events ?? []) {
        for (const ticker of event.tickers ?? []) {
          if (ticker.product_id === 'BTC-USD') {
            price = ticker.price;
          }
        }
      }
      if (!price) {
        console.log('WebSocket update:', message);
      }

      if (mounted && price) {
        clearTimeout(timeout);
        setLivePrice(String(price));
      }
    });
    ws.on('exception', showError);

    // React can clean up an effect before its subscription starts.
    Promise.resolve().then(async () => {
      if (!mounted) {
        return;
      }

      try {
        await Promise.resolve(ws.subscribe({ topic: 'ticker', payload: { product_ids: ['BTC-USD'] } }, 'advTradeMarketData'));
      } finally {
        // Close again if pending setup completed after unmount.
        if (!mounted) {
          ws.closeAll();
        }
      }
    }).catch(showError);

    return () => {
      mounted = false;
      clearTimeout(timeout);
      ws.closeAll();
    };
  }, []);

  return (
    <View style={{ gap: 12, paddingVertical: 24 }}>
      <Text>BTC-USD REST price: {restPrice}</Text>
      <Text>BTC-USD WebSocket price: {livePrice}</Text>
      <Text accessibilityRole="alert">{error}</Text>
    </View>
  );
}

export default function App() {
  const [running, setRunning] = useState(true);

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ padding: 24 }}>
        <Text style={{ fontSize: 24 }}>BTC-USD price</Text>
        {running ? (
          <Prices />
        ) : (
          <Text style={{ paddingVertical: 24 }}>
            Stream stopped. WebSocket closed.
          </Text>
        )}
        <Button
          title={running ? 'Stop stream' : 'Start stream'}
          onPress={() => setRunning(!running)}
        />
      </View>
    </SafeAreaView>
  );
}

8. Create index.js ​

Register the native app entry point with Expo.

js
import { registerRootComponent } from 'expo';
import App from './App';
registerRootComponent(App);

Run on iOS or Android ​

sh
npm start

Press i to open the iOS simulator or a to open the Android emulator. Keep Expo Go in the foreground. The screen shows BTC-USD REST price and BTC-USD WebSocket price, each followed by a positive price such as 65000.5.

Tap Stop stream. The price component unmounts, its effect cleanup calls closeAll(), and the screen shows Stream stopped. WebSocket closed. Tap Start stream to create a new subscription. Late REST responses are ignored after unmount.

For apps that move between the foreground and background, use React Native’s AppState API to stop connections when the app is inactive and reload account or market state before reconnecting.

Troubleshooting ​

  • An unresolved events, https, http, url or buffer import means a dependency or Metro helper is missing. Install all dependencies and keep metro.config.cjs beside package.json.
  • If Metro still reports an import error after you fix the dependencies or configuration, stop it and run npx expo start --clear from the project directory.
  • If Expo Go rejects the project version, use the Expo Go release that supports the starter's Expo SDK. Match Expo Go to the Expo SDK version in package.json.
  • If price fields stay at Loading or Connecting, check internet access from the simulator or emulator and inspect the error shown on the screen. Exchange regional restrictions apply there too.

Built by Siebly. Open source SDKs for exchange APIs.