Skip to content

Vite (plain JavaScript) quickstart ​

Build a page that displays a public BTC-USD REST price and live WebSocket updates from coinbase-api. No API key is needed. Prices are BTC-USD last traded prices.

Use Node.js 24 and npm. You can also view the complete Coinbase Vite 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 the supplied Vite configuration. Run authenticated calls on your Node.js server. Browser REST access also depends on Coinbase CORS policy.

Create the project ​

sh
mkdir coinbase-vite-quickstart
cd coinbase-vite-quickstart

1. Create package.json ​

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

json
{
  "name": "coinbase-vite-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": {
    "coinbase-api": "latest",
    "events": "3.3.0"
  },
  "devDependencies": {
    "vite": "5.4.21"
  }
}

2. Install dependencies ​

Run this after saving package.json:

sh
npm install

3. Create vite.config.js ​

Configure the development server and production build.

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

// Public market data only. Coinbase's JWT helper imports Node crypto eagerly.
// Keep authenticated calls and private keys on a Node.js server.
const publicAuth = '\0coinbase-public-auth';
const sdkRoot = fileURLToPath(new URL('./node_modules/coinbase-api/', import.meta.url));
export default {
  // Keep SDK modules in Vite's transform pipeline so the JWT replacement also
  // applies during development. Prebundle its CommonJS browser dependencies.
  optimizeDeps: {
    exclude: ['coinbase-api'],
    include: ['events', 'coinbase-api > isomorphic-ws'],
  },
  resolve: {
    alias: {
      events: fileURLToPath(new URL('./node_modules/events/events.js', import.meta.url)),
    },
  },
  plugins: [{
    name: 'coinbase-public-market-data',
    enforce: 'pre',
    resolveId(source, importer) {
      if (source.endsWith('/jwtNode.js') && importer?.startsWith(sdkRoot)) {
        return publicAuth;
      }
    },
    load(id) {
      if (id === publicAuth) {
        return `export function signJWT() { throw new Error('JWT signing is server-only in this public market-data starter.'); }
export const signWSJWT = signJWT;`;
      }
    },
  }],
};

4. Create main.js ​

Read the REST price, show WebSocket updates and close the connection when the user clicks Stop stream.

js
import { CBAdvancedTradeClient, WebsocketClient } from 'coinbase-api';

const restOutput = document.querySelector('#rest');
const liveOutput = document.querySelector('#live');
const errorOutput = document.querySelector('#error');
const stopButton = document.querySelector('#stop');
let stopStream;
let userStopped = false;

function startStream() {
  const ws = new WebsocketClient();
  let stopped = false;
  liveOutput.textContent = 'Connecting';
  errorOutput.textContent = '';

  function showError(error) {
    console.error(error);
    if (!stopped) {
      errorOutput.textContent = 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 (!stopped) {
      restOutput.textContent = 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 (!stopped && price) {
      clearTimeout(timeout);
      liveOutput.textContent = String(price);
    }
  });
  ws.on('exception', showError);

  Promise.resolve().then(async () => {
    if (stopped) {
      return;
    }

    try {
      await Promise.resolve(ws.subscribe({ topic: 'ticker', payload: { product_ids: ['BTC-USD'] } }, 'advTradeMarketData'));
    } finally {
      if (stopped) {
        ws.closeAll();
      }
    }
  }).catch(showError);

  return function stop() {
    if (stopped) {
      return;
    }

    stopped = true;
    clearTimeout(timeout);
    ws.closeAll();
    liveOutput.textContent = 'Stopped';
  };
}

function start() {
  if (!stopStream && !userStopped) {
    stopStream = startStream();
  }
}

function stop() {
  stopStream?.();
  stopStream = undefined;
}

function stopByUser() {
  userStopped = true;
  stop();
}

function restore(event) {
  if (event.persisted) {
    start();
  }
}

stopButton.addEventListener('click', stopByUser);
window.addEventListener('pagehide', stop);
window.addEventListener('pageshow', restore);
start();

if (import.meta.hot) {
  import.meta.hot.dispose(() => {
    stopButton.removeEventListener('click', stopByUser);
    window.removeEventListener('pagehide', stop);
    window.removeEventListener('pageshow', restore);
    stop();
  });
}

5. 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>Live price</title>
  </head>
  <body>
    <h1>Live price</h1>
    <p>REST: <output id="rest">Loading</output></p>
    <p>WebSocket: <output id="live">Connecting</output></p>
    <p id="error" role="alert"></p>
    <button id="stop" type="button">Stop stream</button>
    <script type="module" src="/main.js"></script>
  </body>
</html>

Run ​

sh
npm run dev

Open the URL printed by Vite, normally http://localhost:5173/. The page shows a REST price and a changing WebSocket price. Click Stop stream to close the client. Leaving the page or replacing the module during Vite development also closes the connection. If Back or Forward navigation restores a cached page, it starts a new subscription unless you clicked Stop stream.

To check the production bundle:

sh
npm run build
npm run preview

Open the preview URL printed by Vite. Both price fields should contain positive numbers, such as 65000.5. REST and streaming prices may differ.

Troubleshooting ​

  • An events resolution error means the dependency or Vite config is missing. Copy the config exactly and restart Vite.
  • Run the page through Vite, rather than opening index.html directly. Check the browser network panel for blocked REST or WSS requests. The exchange must permit your origin and region; a successful bundle alone does not prove network access.
  • Keep private keys and API credentials in a secure server-side environment, outside source files and browser bundles. This page uses public market data. See WebSocket subscriptions for subscription details.

Built by Siebly. Open source SDKs for exchange APIs.