Skip to content

Node.js / TypeScript quickstart ​

Write a TypeScript script that reads a public BTC-USD price with coinbase-api, then compile and run it in Node.js. 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 TypeScript example on GitHub.

The SDK also works with plain JavaScript. TypeScript is optional, but we strongly recommend it for SDK integrations: checking the included types catches many invalid method names, parameters and response assumptions at build time. Keep a type check in CI even if your runtime can execute TypeScript directly; execution alone does not check types.

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-typescript-quickstart
cd coinbase-typescript-quickstart
npm init -y
npm install coinbase-api
npm install --save-dev typescript@6.0.3 @types/node@24.13.2

The install command adds the latest SDK release, which includes its own type definitions. The development dependencies supply the TypeScript compiler and Node.js types.

1. Create tsconfig.json ​

Enable strict type checking and compile the TypeScript programs into dist/.

json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "skipLibCheck": true,
    "outDir": "dist",
    "types": [
      "node"
    ]
  },
  "include": [
    "*.mts"
  ]
}

Read a price ​

Create price.mts. The SDK’s type definitions let TypeScript check the constructor options, request parameters and response types.

ts
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);

Check types, compile and run:

sh
npx tsc --noEmit
npx tsc
node dist/price.mjs
text
BTC-USD REST price: 65000.5

The .mts source compiles to .mjs. NodeNext compiler settings follow Node.js module resolution without changing the package’s default module format.

Stream a price (optional) ​

Create stream.mts to stream prices until Ctrl+C. Signal handlers close the client; exceptions and reconnections are logged without stopping it.

ts
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');

Compile and run it:

sh
npx tsc
node dist/stream.mjs
text
BTC-USD WebSocket price: 65001.2
WebSocket closed.

Troubleshooting ​

  • npx tsc --noEmit checks types without making exchange requests. Fix compiler errors before running the emitted JavaScript.
  • If Node cannot find dist/price.mjs or dist/stream.mjs, compile with npx tsc first.
  • If types cannot be resolved, check that both development dependencies installed successfully.
  • For network or API errors, see Troubleshooting and Runtime compatibility.

Built by Siebly. Open source SDKs for exchange APIs.