Skip to content

React quickstart ​

Display public BTC REST and WebSocket prices from @siebly/kraken-api in a React component. No API key is needed. Prices are BTC/USD last traded prices. This is a React browser app built with Vite; the plain JavaScript Vite guide uses DOM elements directly.

Use Node.js 24 and npm. You can also view the complete Kraken React example on GitHub.

See Runtime compatibility for runtime requirements.

The public GET client below omits two SDK request headers that trigger a failing Kraken CORS preflight. This is an example-specific setup for public reads, not general browser REST support. See Browser REST and CORS for the limitation and a server-side alternative.

Create the project ​

sh
mkdir kraken-react-quickstart
cd kraken-react-quickstart

1. Create package.json ​

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

json
{
  "name": "kraken-react-quickstart",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite --host 127.0.0.1",
    "build": "vite build",
    "preview": "vite preview --host 127.0.0.1"
  },
  "dependencies": {
    "@siebly/kraken-api": "latest",
    "react": "19.2.0",
    "react-dom": "19.2.0",
    "events": "3.3.0"
  },
  "devDependencies": {
    "vite": "5.4.21",
    "@vitejs/plugin-react": "4.7.0"
  }
}

2. Install dependencies ​

Run this after saving package.json:

sh
npm install

3. Create sdk.vite.config.js ​

Resolve the SDK imports that need browser support. Keep this configuration when using the SDK in Vite.

js
import {fileURLToPath} from 'node:url';

export default {
  resolve: {
    alias: {
      events: fileURLToPath(new URL('./node_modules/events/events.js', import.meta.url)),
    },
  },
};

4. Create vite.config.js ​

Configure the development server and production build.

js
import { mergeConfig } from 'vite';
import react from '@vitejs/plugin-react';
import sdkConfig from './sdk.vite.config.js';

export default mergeConfig(sdkConfig, {
  plugins: [react()],
});

5. Create App.jsx ​

Build the React screen. The effect makes the REST request, subscribes to prices and closes the WebSocket on unmount.

jsx
import { useEffect, useState } from 'react';
import { SpotClient, WebsocketClient } from '@siebly/kraken-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() {
      // Public GET requests only. Keep credentials on your server.
      const client = new SpotClient({}, {
        transformRequest: [function (data, headers) {
          if (this.method !== 'get') {
            throw new Error('This browser client supports public GET requests only.');
          }
          // These SDK defaults trigger a preflight Kraken does not accept.
          headers.delete('UserAgent');
          headers.delete('locale');
          return data;
        }],
      });
      const response = await client.getTicker({ pair: 'XBTUSD' });
      const ticker = Object.values(response.result)[0];
      const price = ticker?.c[0];

      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('message', (message) => {
      if (message.channel !== 'ticker') {
        console.log('WebSocket message:', message);
        return;
      }

      const price = message.data?.[0]?.last;

      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: { symbol: ['BTC/USD'] } }, 'spotPublicV2'));
      } finally {
        // Close again if pending setup completed after unmount.
        if (!mounted) {
          ws.closeAll();
        }
      }
    }).catch(showError);

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

  return (
    <section>
      <p>BTC/USD REST price: <output aria-label="REST price">{restPrice}</output></p>
      <p>BTC/USD WebSocket price: <output aria-label="WebSocket price">{livePrice}</output></p>
      <p role="alert">{error}</p>
    </section>
  );
}

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

  return (
    <main>
      <h1>BTC/USD price</h1>
      {running && pageActive ? <Prices /> : <p>Stream stopped. WebSocket closed.</p>}
      <button type="button" onClick={() => setRunning(!running)}>
        {running ? 'Stop stream' : 'Start stream'}
      </button>
    </main>
  );
}

6. Create main.jsx ​

Mount the screen with StrictMode. Pause subscriptions while the browser caches the page, resume them on restoration and clean up when the page or entry module is discarded.

jsx
import { StrictMode } from 'react';
import { flushSync } from 'react-dom';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';

const root = createRoot(document.getElementById('root'));
let disposed = false;

function render(pageActive) {
  root.render(
    <StrictMode>
      <App pageActive={pageActive} />
    </StrictMode>,
  );
}

function dispose() {
  if (disposed) {
    return;
  }

  disposed = true;
  window.removeEventListener('pagehide', hide);
  window.removeEventListener('pageshow', show);
  root.unmount();
}

function hide(event) {
  if (event.persisted) {
    // Finish effect cleanup before the browser freezes this page.
    // Keep App mounted so its Stop/Start choice survives restoration.
    flushSync(() => render(false));
  } else {
    dispose();
  }
}

function show(event) {
  if (event.persisted && !disposed) {
    render(true);
  }
}

render(true);
window.addEventListener('pagehide', hide);
window.addEventListener('pageshow', show);

if (import.meta.hot) {
  import.meta.hot.dispose(dispose);
}

7. Create index.html ​

Create the browser page that loads the application entry module.

html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <title>React price screen</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/main.jsx"></script>
  </body>
</html>

Run ​

sh
npm run dev

Open Vite's printed URL, normally http://localhost:5173/. Both price fields should display positive numbers such as 65000.5. Tap Stop stream to unmount the price component and close its WebSocket. Start stream mounts a new component and creates a fresh subscription.

The effect ignores REST responses that arrive after unmount. Its cleanup closes the client before the effect runs again and when the component unmounts. This also handles StrictMode’s extra setup and cleanup cycle in development.

The entry module pauses the price component when the browser caches the page for Back or Forward navigation. Restoring the page resumes it without changing your Stop/Start choice. The module unmounts the React root when the page is discarded or Vite replaces the entry module. See React's effect lifecycle.

Build and preview the production app:

sh
npm run build
npm run preview

Troubleshooting ​

  • An events resolution error means the dependency or Vite config is missing. Copy the config exactly and restart Vite.
  • A brief extra connection in development is expected under StrictMode. If updates continue after Stop stream, check that the component cleanup closes the client and ignores late updates.
  • This example uses public market data only. Keep private keys and API credentials in a secure server-side environment, outside source files and browser bundles.
  • For network failures, inspect the browser's HTTPS and WSS requests to the exchange. Exchange CORS and regional restrictions apply. See Runtime compatibility for browser configuration and WebSocket subscriptions for subscription details.

Built by Siebly. Open source SDKs for exchange APIs.