Skip to content

Node.js / JavaScript quickstart ​

Read a public BTC-USD price with coinbase-api. No API key or TypeScript compiler is needed. Prices are BTC-USD last traded prices.

Use Node.js 24 and npm. If you prefer to start from a finished project, view the complete Coinbase Node.js example on GitHub.

This project uses Advanced Trade public market data. Keep credentialed account and trading calls in a server-side application.

Create the project ​

sh
mkdir coinbase-node-quickstart
cd coinbase-node-quickstart
npm init -y
npm install coinbase-api

npm init creates package.json; npm install adds the current SDK release. You do not need to edit the package file for these examples.

Read a price ​

For a new project, create price.mjs with import. If your project uses require, choose price.cjs instead. Create one file; both request the price directly.

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

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

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

console.log('BTC-USD REST price:', price);
js
const { CBAdvancedTradeClient } = require('coinbase-api');

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

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

  console.log('BTC-USD REST price:', price);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Run the file you created:

sh
node price.mjs
sh
node price.cjs

The result is a price string, for example:

text
BTC-USD REST price: 65000.5

Stream a price (optional) ​

For a new project, create stream.mjs with import. If your project uses require, choose stream.cjs instead. Create one stream file; it streams prices until you press Ctrl+C. Exceptions and reconnections are logged without stopping the client.

js
import { WebsocketClient } from 'coinbase-api';
import process from 'node:process';

const ws = new WebsocketClient();

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 (price) {
    console.log('BTC-USD WebSocket price:', String(price));
  }
});

ws.on('response', (message) => {
  console.log('WebSocket response:', message);
});
ws.on('exception', (error) => {
  console.error('WebSocket exception:', error);
});
ws.on('reconnect', (event) => {
  console.log('WebSocket reconnecting:', event);
});
ws.on('reconnected', (event) => {
  console.log('WebSocket reconnected:', event);
});

function stop() {
  ws.closeAll();
  console.log('WebSocket closed.');
}

process.once('SIGINT', stop);
process.once('SIGTERM', stop);

ws.subscribe({ topic: 'ticker', payload: { product_ids: ['BTC-USD'] } }, 'advTradeMarketData');
js
const { WebsocketClient } = require('coinbase-api');
const process = require('node:process');

const ws = new WebsocketClient();

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 (price) {
    console.log('BTC-USD WebSocket price:', String(price));
  }
});

ws.on('response', (message) => {
  console.log('WebSocket response:', message);
});
ws.on('exception', (error) => {
  console.error('WebSocket exception:', error);
});
ws.on('reconnect', (event) => {
  console.log('WebSocket reconnecting:', event);
});
ws.on('reconnected', (event) => {
  console.log('WebSocket reconnected:', event);
});

function stop() {
  ws.closeAll();
  console.log('WebSocket closed.');
}

process.once('SIGINT', stop);
process.once('SIGTERM', stop);

ws.subscribe({ topic: 'ticker', payload: { product_ids: ['BTC-USD'] } }, 'advTradeMarketData');

Run the matching file:

sh
node stream.mjs
sh
node stream.cjs

The script keeps streaming until Ctrl+C. Exceptions and reconnections are logged; signal handlers close the client. SDK connection logs may also appear:

text
BTC-USD WebSocket price: 65001.2
WebSocket closed.

Troubleshooting ​

  • Use .mjs for import and .cjs for require. These Node.js module rules let you choose either format without configuring "type" in package.json.
  • If the SDK cannot be resolved, run the install command from the directory containing your program and package.json.
  • If a request fails or no stream updates arrive, check HTTPS and WSS access to the exchange from your network and region.
  • See Runtime setup for the other project recipes and WebSocket subscriptions for continuous subscriptions.

Built by Siebly. Open source SDKs for exchange APIs.