Skip to content

Coinbase API with Cloudflare Workers ​

Use the Coinbase JavaScript SDK in a Worker request handler. Start with a public BTC-USD price, then add a separate authenticated order handler when needed. No hard-coded exchange URL or custom HTTP adapter is required.

Browse the complete Coinbase Workers starter or download the runnable project.

Create the project ​

Use Node.js 24 and npm. Create an empty directory:

sh
mkdir sdk-worker
cd sdk-worker

Create package.json:

json
{
  "name": "coinbase-cloudflare-workers-quickstart",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "wrangler dev",
    "dev:orders": "wrangler dev src/order.js"
  },
  "dependencies": {
    "coinbase-api": "latest"
  },
  "devDependencies": {
    "wrangler": "4.161.0"
  }
}

Install dependencies:

sh
npm install

Create wrangler.jsonc:

js
{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "coinbase-market-data",
  "main": "src/index.js",
  "compatibility_date": "2026-11-01"
}

Compatibility dates from 2026-08-04 enable Node.js compatibility by default. Dates from 2024-09-23 through 2026-08-03 need "compatibility_flags": ["nodejs_compat"]. Use the date above for this recipe; no extra browser polyfills are needed.

Read a public price ​

Create the src directory and src/index.js:

sh
mkdir src
js
import { CBAdvancedTradeClient } from 'coinbase-api';

export default {
  async fetch() {
    const client = new CBAdvancedTradeClient(
      {},
      { fetchOptions: { cache: 'no-store' } },
    );
    const ticker = await client.getPublicProduct({ product_id: 'BTC-USD' });
    const price = ticker.price;
    return Response.json({ symbol: 'BTC-USD', price });
  },
};

Run npm run dev, then open the local URL Wrangler prints. Each incoming request reads a price through the SDK and returns JSON.

Request cache configuration ​

The second constructor argument sets fetchOptions.cache to no-store, a cache mode Workers supports. Axios 1.20.0 otherwise requests default, which Workers rejects. Keep this option while using that affected version. Axios 1.21.0 fixes this default cache behavior. SDK dependency upgrades follow Siebly’s security policy, which generally includes at least 30 days of review. This does not guarantee a release date. You do not need to override the SDK dependency.

Submit an order ​

This separate handler submits a limit buy on Coinbase Advanced Trade production. Review the symbol, price, quantity, exchange filters and key permissions before sending a request. The example uses production credentials and submits a live order.

Create src/order.js:

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

export default {
  async fetch(request, env) {
    if (new URL(request.url).pathname !== '/order') {
      return new Response('Not found', { status: 404 });
    }
    if (request.method !== 'POST') {
      return new Response('Use POST', { status: 405 });
    }
    if (
      !env.ORDER_TOKEN ||
      request.headers.get('Authorization') !== 'Bearer ' + env.ORDER_TOKEN
    ) {
      return new Response('Unauthorized', { status: 401 });
    }

    const { price, quantity, clientOrderId } = await request.json();

    const positiveDecimal = (value) =>
      typeof value === 'string' &&
      /^\d+(\.\d+)?$/.test(value) &&
      Number(value) > 0 &&
      Number.isFinite(Number(value));
    if (!positiveDecimal(price) || !positiveDecimal(quantity)) {
      return new Response(
        'Use positive decimal strings for price and quantity',
        { status: 400 },
      );
    }
    if (typeof clientOrderId !== 'string' || !clientOrderId.trim()) {
      return new Response('Provide your persisted clientOrderId', {
        status: 400,
      });
    }
    if (!env.COINBASE_API_KEY || !env.COINBASE_API_SECRET) {
      return new Response('Missing exchange credentials', { status: 503 });
    }

    const client = new CBAdvancedTradeClient(
      {
        apiKey: env.COINBASE_API_KEY,
        apiSecret: env.COINBASE_API_SECRET,
      },
      { fetchOptions: { cache: 'no-store' } },
    );

    const result = await client.submitOrder({
      client_order_id: clientOrderId,
      product_id: 'BTC-USD',
      side: 'BUY',
      order_configuration: {
        limit_limit_gtc: {
          base_size: quantity,
          limit_price: price,
          post_only: true,
        },
      },
    });

    return Response.json(result);
  },
};

Use Worker secrets for the exchange credentials and a separate strong ORDER_TOKEN:

sh
npx wrangler secret put ORDER_TOKEN
npx wrangler secret put COINBASE_API_KEY
npx wrangler secret put COINBASE_API_SECRET

For local development, put those same names in an untracked .dev.vars file. Keep it out of source control. ORDER_TOKEN protects your application endpoint; it is not your exchange API key. Do not expose it in a public browser app. See authentication for your SDK’s credential format.

Run npm run dev:orders to select the private handler. The public default entrypoint does not accept orders. Send POST /order with Authorization: Bearer <your ORDER_TOKEN> and a JSON body containing price and quantity as positive decimal strings to submit one order. Starting the server does not submit anything. Also supply clientOrderId: generate a unique ID in your calling application and persist it before sending. Use that same ID to resolve an uncertain order outcome before submitting another order.

Inspect the exchange’s response, including per-order rejection fields. Acknowledgement is not a fill. Use account authentication and order management for account events and order state. If a request times out, resolve its outcome before retrying; do not blindly resubmit.

WebSocket lifecycle and production use ​

A request handler is not an always-running Node.js process. Do not open a background subscription and assume it continues after the response. waitUntil() extends work only for a limited time. For persistent streams, choose a service that can keep the connection open and handle reconnects. Outgoing WebSockets in Durable Objects do not support hibernation.

See WebSocket subscriptions, authentication, and production usage. Exchange region restrictions still apply to your Worker’s outbound requests.

Built by Siebly. Open source SDKs for exchange APIs.