Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/tiagosiebler/kucoin-api/llms.txt

Use this file to discover all available pages before exploring further.

The kucoin-api SDK is designed to work in both Node.js and browser environments. In the browser, it replaces Node.js’s crypto module with the standardised Web Crypto API (globalThis.crypto.subtle) for HMAC-SHA256 request signing. A webpack configuration is included in the repository to produce a ready-to-use UMD bundle that any <script> tag or module bundler can consume.

How Browser Signing Works

In Node.js, HMAC signatures are traditionally computed with the built-in crypto module. Browsers do not expose require('crypto'), so the SDK implements the same signature logic through the Web Crypto API instead. The key function in src/lib/webCryptoAPI.ts looks like this:
export async function signMessage(
  message: string,
  secret: string,
  method: SignEncodeMethod,
  algorithm: SignAlgorithm,
): Promise<string> {
  const encoder = new TextEncoder();

  const key = await globalThis.crypto.subtle.importKey(
    'raw',
    encoder.encode(secret),
    { name: 'HMAC', hash: algorithm },
    false,
    ['sign'],
  );

  const buffer = await globalThis.crypto.subtle.sign(
    'HMAC',
    key,
    encoder.encode(message),
  );

  // Returns base64 or hex encoded result
  // ...
}
This function uses only globalThis.crypto, which is available in all modern browsers (Chrome, Firefox, Safari, Edge) as well as Node.js v18+ and Deno — no polyfill needed.
If you are on Node.js, the SDK checks for Web Crypto API availability at construction time when credentials are supplied. Node.js v18 reached end-of-life in April 2025. Use Node.js LTS (v22 or above) to ensure globalThis.crypto is available.

Node.js-only Features Excluded from Browser Builds

The https.Agent (used for the keepAlive REST option) is Node.js-only. The webpack configuration explicitly excludes it so the browser bundle remains clean:
// webpack/webpack.config.cjs
resolve: {
  fallback: {
    // Node.js core modules not available in browsers
    // The REST client's https.Agent (for keepAlive) is Node.js-only and won't work in browsers
    "http": false,
    "https": false,
  },
},
When you set keepAlive: true in a browser context, the SDK silently skips the https.Agent setup — browsers manage connection pooling automatically.

Building the Browser Bundle

The repository ships a webpack config that compiles the pre-built CJS output into a single UMD bundle suitable for direct <script> tag inclusion or integration into frontend projects.
1

Install dependencies

From the root of the kucoin-api repository, install all Node.js dependencies including the webpack build toolchain:
npm install
2

Compile TypeScript

Compile the TypeScript source to both ESM and CJS output in the dist/ directory:
npm run build
This runs tsc twice — once for ESM (dist/mjs/) and once for CJS (dist/cjs/) — then runs the post-build shell script.
3

Bundle with webpack

Run webpack to produce a single UMD bundle in dist/kucoinapi.js:
npm run pack
The webpack config (webpack/webpack.config.cjs) reads from dist/cjs/index.js as its entry point and outputs a kucoinapi UMD library:
// webpack/webpack.config.cjs (abridged)
module.exports = {
  entry: './dist/cjs/index.js',
  output: {
    path: path.resolve(__dirname, '../dist'),
    filename: 'kucoinapi.js',
    library: 'kucoinapi',
    libraryTarget: 'umd',
  },
  mode: 'production',
  // ...
};
4

Use the bundle

Include the bundle from dist/kucoinapi.js in your HTML or frontend build pipeline:
<script src="dist/kucoinapi.js"></script>
<script>
  const { SpotClient } = kucoinapi;

  const client = new SpotClient();

  client.getTicker({ symbol: 'BTC-USDT' }).then((ticker) => {
    console.log('BTC-USDT ticker:', ticker);
  });
</script>
When used as an ES module in a bundler (Vite, Rollup, webpack, etc.), import directly from the npm package — the exports map in package.json selects the correct ESM or CJS build automatically.

ESM and CJS Exports

The published npm package exposes both module formats via the exports field in package.json:
{
  "exports": {
    ".": {
      "import":  "./dist/mjs/index.js",
      "require": "./dist/cjs/index.js",
      "types":   "./dist/mjs/index.d.ts"
    }
  }
}
  • ESM (import): used by Vite, modern webpack, Rollup, and any type: "module" project.
  • CJS (require): used by legacy Node.js scripts and older toolchains.
No configuration is required on your side — your bundler or runtime picks the right format automatically.

Security: Never Expose API Keys in the Browser

Do not embed KuCoin API keys, secrets, or passphrases in client-side JavaScript. Browser code is fully visible to any user who opens DevTools. Anyone who reads your keys can place orders, withdraw funds, or cancel positions on your behalf.
The browser bundle is safe to use for public, unauthenticated endpoints — fetching tickers, order books, klines, and symbol lists — because those require no credentials. For anything that requires authentication, use a backend proxy pattern:

Safe in the browser

  • Market data (tickers, order books, klines)
  • Symbol lists and exchange info
  • Public WebSocket streams

Keep on the backend

  • Order placement and cancellation
  • Account balance queries
  • Private WebSocket streams
  • Any call that uses API key/secret
The recommended architecture for browser-based trading dashboards is to route authenticated calls through a server you control:
Browser ──(public market data)──► kucoin-api in browser ──► KuCoin REST API
Browser ──(place order)──────────► Your backend server ──────► kucoin-api in Node ──► KuCoin REST API
Your backend server holds the API credentials, validates user sessions, and forwards trading actions to KuCoin on behalf of your users. The browser never sees the raw API key or secret.

Using the Custom Sign Function for Performance

If you are running in a backend Node.js environment and need maximum signing throughput, you can optionally swap the Web Crypto API signer for Node’s faster native createHmac:
import { createHmac } from 'crypto';
import { SpotClient } from 'kucoin-api';

const client = new SpotClient({
  apiKey: process.env.API_KEY,
  apiSecret: process.env.API_SECRET,
  apiPassphrase: process.env.API_PASSPHRASE,
  customSignMessageFn: async (message, secret) => {
    return createHmac('sha256', secret).update(message).digest('hex');
  },
});
This optimisation is overkill for most applications. The Web Crypto API is fast enough for the vast majority of trading strategies. Only consider customSignMessageFn if you have measured a signing bottleneck in a latency-critical context.

Build docs developers (and LLMs) love