OKX API with Cloudflare Workers
Use the OKX JavaScript SDK in a Worker request handler. Start with a public BTC-USDT price, then add a separate authenticated order handler when needed. No hard-coded exchange URL or custom HTTP adapter is required.
Browse the complete OKX Workers starter or download the runnable project.
Create the project
Use Node.js 24 and npm. Create an empty directory:
mkdir sdk-worker
cd sdk-workerCreate package.json:
{
"name": "okx-cloudflare-workers-quickstart",
"private": true,
"type": "module",
"scripts": {
"dev": "wrangler dev",
"dev:orders": "wrangler dev src/order.js"
},
"dependencies": {
"okx-api": "latest"
},
"devDependencies": {
"wrangler": "4.161.0"
}
}Install dependencies:
npm installCreate wrangler.jsonc:
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "okx-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:
mkdir srcimport { RestClient } from 'okx-api';
export default {
async fetch() {
const client = new RestClient({}, { fetchOptions: { cache: 'no-store' } });
const tickers = await client.getTicker({ instId: 'BTC-USDT' });
const price = tickers[0]?.last;
return Response.json({ symbol: 'BTC-USDT', 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 OKX 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:
import { RestClient } from 'okx-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 } = 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 (!env.OKX_API_KEY || !env.OKX_API_SECRET || !env.OKX_API_PASSPHRASE) {
return new Response('Missing exchange credentials', { status: 503 });
}
const client = new RestClient(
{
apiKey: env.OKX_API_KEY,
apiSecret: env.OKX_API_SECRET,
apiPass: env.OKX_API_PASSPHRASE,
},
{ fetchOptions: { cache: 'no-store' } },
);
const result = await client.submitOrder({
instId: 'BTC-USDT',
tdMode: 'cash',
side: 'buy',
ordType: 'post_only',
px: price,
sz: quantity,
});
return Response.json(result);
},
};Use Worker secrets for the exchange credentials and a separate strong ORDER_TOKEN:
npx wrangler secret put ORDER_TOKEN
npx wrangler secret put OKX_API_KEY
npx wrangler secret put OKX_API_SECRET
npx wrangler secret put OKX_API_PASSPHRASEFor 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.
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.