A Binance API key is what lets your code read a Binance account and place orders. This guide is for JavaScript and TypeScript developers who want a key that works the first time: which key type to choose, how to make an Ed25519 key pair with Node.js alone, which permissions to switch on, and how to check the key with the Siebly Binance JavaScript SDK (the binance npm package) before you build anything on top of it.
Every error message on this page comes from Binance Spot Testnet or Demo Trading with made-up keys, so the text is exactly what Binance returns. Nothing here uses a real key or real funds.
When you need a Binance API key
Public market data needs no key. Prices, order books, candles and exchange information come from public endpoints, and the SDK calls them without credentials. You need a key as soon as a request touches your account: balances, open orders, order placement, trade history, transfers.
Binance also issues keys per environment. A live key, a Spot Testnet key and a Demo Trading key are three different keys. A key from one is rejected by the others with -2015.
Binance API key types: HMAC, Ed25519 and RSA
Binance’s How to Create API Keys on Binance FAQ describes the steps on the website: go to Profile, then Account, open API Management and click Create API. Before the button works, the account needs two-factor authentication, identity verification and a deposit of any amount to the Spot account. You then pick one of two key types:
- System-generated: an HMAC key. Binance shows you an API key and a secret key. The same secret signs your requests and verifies them on Binance’s side.
- Self-generated: an Ed25519 or RSA key. You create a key pair yourself and paste only the public key into Binance. Binance returns an API key. The private key stays with you and never goes to Binance.
Binance’s developer page on API key types recommends Ed25519 and describes HMAC keys as deprecated. There is a practical reason too: the WebSocket API’s session.logon, which authenticates a connection once instead of signing every request, only supports Ed25519 keys.
The FAQ also notes a restriction on HMAC keys: a system-generated HMAC key with no IP restriction cannot have any permission other than reading. To enable trading on an HMAC key you have to add trusted IP addresses. Self-generated keys are listed as one of the alternatives.
So for new code, choose Self-generated with an Ed25519 key.
Create an Ed25519 key pair with Node.js
Binance offers a desktop key generator, but Node.js can make the pair itself with the built-in crypto module. No extra package is needed:
import { generateKeyPairSync } from 'node:crypto';
import { writeFileSync } from 'node:fs';
// Ed25519 key pair in the PEM formats Binance and the SDK expect.
const { publicKey, privateKey } = generateKeyPairSync('ed25519', {
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
});
// Paste the public key into Binance. The private key never leaves your server.
writeFileSync('binance-ed25519-public.pem', publicKey);
writeFileSync('binance-ed25519-private.pem', privateKey, { mode: 0o600 });
console.log(publicKey);
console.log(`private key saved to binance-ed25519-private.pem (${privateKey.length} characters)`);
Run it with Node.js 24, which runs TypeScript files directly:
node keypair.ts
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEA6YC8bkYP31vr1uzYAY/fFvA4qm4JjpoWNTrBil8BqR0=
-----END PUBLIC KEY-----
private key saved to binance-ed25519-private.pem (119 characters)
That public key is from a throwaway pair made for this article. Paste your own public key, including the BEGIN and END lines, into the box Binance shows after you choose Self-generated, give the key a name and complete the 2FA check. Binance then shows the API key.
Two details matter later:
- The private key file is written with mode
0600, so only your user can read it. Keep it out of the repository: add*.pemto.gitignore. - The private key PEM is 119 characters long. The SDK uses length to tell Ed25519 from RSA (more on that below), and an Ed25519 key is well under its limit.
Choose permissions for a Binance API key
Start with the smallest set of permissions and add more only when the code needs them:
- Read only first. Get the account check below working before you enable anything else.
- Trading only when you place orders, and only for the product you trade. Spot and futures trading are separate permissions.
- Withdrawals off. Trading code never needs to move funds off the exchange.
- Restrict the key to trusted IPs. Binance’s guidance on securing API keys recommends an IP whitelist on every key, whatever its permissions. For an HMAC key it is a requirement for trading anyway.
- One key per application, so you can revoke one without breaking the others.
- Secrets stay on the server. A secret or private key in a browser bundle, a mobile app or a public repository is a leaked key.
The longer checklist, including rotation and logging, is in API key security best practices for crypto exchanges and trading bots.
Use the key with the binance SDK
npm install binance
The SDK takes the same two options for every key type: api_key and api_secret. For an HMAC key, api_secret is the secret key. For an Ed25519 or RSA key, it is the private key PEM. The SDK reads the string and picks the signing method itself. In version 3.6.15 the rule is:
- no
PRIVATE KEYin the string: HMAC-SHA256, hex signature RSA PRIVATE KEYin the string: RSA, base64 signature- any other
PRIVATE KEYof 150 characters or fewer: Ed25519, base64 signature - longer than that: RSA
A PEM is safest in its own file rather than inside .env, where quotes and line breaks get mangled (the -1022 section shows what each kind of damage does). This helper reads a key path or a plain secret and sets the environment flag:
import { readFileSync } from 'node:fs';
export type BinanceEnv = 'testnet' | 'demo' | 'live';
export interface BinanceKeyConfig {
env: BinanceEnv;
api_key: string;
api_secret: string;
testnet?: true;
demoTrading?: true;
}
// Reads the key from the environment. For an Ed25519 or RSA key, point
// BINANCE_PRIVATE_KEY_PATH at the PEM file instead of pasting it into .env.
export function loadBinanceKey(): BinanceKeyConfig {
const env = (process.env.BINANCE_ENV ?? 'testnet') as BinanceEnv;
if (!['testnet', 'demo', 'live'].includes(env)) {
throw new Error(`BINANCE_ENV must be testnet, demo or live, not "${env}"`);
}
const api_key = process.env.BINANCE_API_KEY;
const keyPath = process.env.BINANCE_PRIVATE_KEY_PATH;
const api_secret = keyPath ? readFileSync(keyPath, 'utf8') : process.env.BINANCE_API_SECRET;
if (!api_key || !api_secret) {
throw new Error('Set BINANCE_API_KEY and either BINANCE_PRIVATE_KEY_PATH or BINANCE_API_SECRET');
}
// One flag at most: testnet and demo keys are different keys on different hosts.
if (env === 'testnet') return { env, api_key, api_secret, testnet: true };
if (env === 'demo') return { env, api_key, api_secret, demoTrading: true };
return { env, api_key, api_secret };
}
With a matching .env:
# testnet (Spot Testnet), demo (Demo Trading) or live
BINANCE_ENV=testnet
BINANCE_API_KEY=
# Ed25519 or RSA key: path to the private key PEM
BINANCE_PRIVATE_KEY_PATH=./binance-ed25519-private.pem
# HMAC key: the secret instead of a path
# BINANCE_API_SECRET=
Creating a client does not contact Binance, so it proves nothing about the key. A private read does. getAccountInformation() calls GET /api/v3/account, which needs only the reading permission:
import { MainClient } from 'binance';
import { loadBinanceKey } from './binance-env.ts';
const { env, ...options } = loadBinanceKey();
const client = new MainClient(options);
try {
const account = await client.getAccountInformation({ omitZeroBalances: true });
console.log(`${env}: key accepted`);
console.log({ canTrade: account.canTrade, canWithdraw: account.canWithdraw, permissions: account.permissions });
console.log(`non-zero balances: ${account.balances.length}`);
// /sapi endpoints exist only on the live API, not on Spot Testnet or Demo Trading.
if (env === 'live') {
const restrictions = await client.getApiKeyPermissions();
console.log({
ipRestrict: restrictions.ipRestrict,
enableReading: restrictions.enableReading,
enableSpotAndMarginTrading: restrictions.enableSpotAndMarginTrading,
enableFutures: restrictions.enableFutures,
enableWithdrawals: restrictions.enableWithdrawals,
});
}
} catch (err) {
const { code, message } = err as { code?: number; message?: string };
console.error(`${env}: rejected with ${code}: ${message}`);
process.exitCode = 1;
}
On a live key, getApiKeyPermissions() (GET /sapi/v1/account/apiRestrictions) reports what the key is allowed to do, including whether withdrawals are enabled and whether it is IP restricted. It is a good check to run once after creating the key. The /sapi paths do not exist on Spot Testnet or Demo Trading: the Spot Testnet FAQ says only /api endpoints are available, and both hosts return HTTP 404 for this path. That is why the script only calls it for live.
Futures use a different client and a different account endpoint. The same key works on USDMClient as long as it has the futures permission:
import { USDMClient } from 'binance';
import { loadBinanceKey } from './binance-env.ts';
const { env, ...options } = loadBinanceKey();
const client = new USDMClient(options);
try {
const account = await client.getAccountInformationV3();
console.log(`${env}: futures key accepted, canTrade=${account.canTrade}`);
} catch (err) {
const { code, message } = err as { code?: number; message?: string };
console.error(`${env}: rejected with ${code}: ${message}`);
process.exitCode = 1;
}
Here is the output with a random 64 character API key and the throwaway Ed25519 private key. Binance never saw that key, so -2015 is the correct answer. With your registered key the scripts print key accepted followed by the account flags.
$ BINANCE_ENV=testnet node --env-file=.env check-key.ts
testnet: rejected with -2015: Invalid API-key, IP, or permissions for action.
$ BINANCE_ENV=demo node --env-file=.env check-key.ts
demo: rejected with -2015: Invalid API-key, IP, or permissions for action.
$ BINANCE_ENV=demo node --env-file=.env check-futures-key.ts
demo: rejected with -2015: Invalid API-key, IP, or permissions for action
$ BINANCE_ENV=testnet BINANCE_API_KEY=abc node --env-file=.env check-key.ts
testnet: rejected with -2014: API-key format invalid.
Variables given on the command line take precedence over --env-file in Node.js, which is how the last run swaps in a malformed key. Note the trailing full stop: the Spot API message ends with one and the USD-M futures message does not, so match on code, never on the text.
Binance testnet and demo API keys are separate
Binance has two practice environments, and each issues its own keys:
- Spot Testnet at testnet.binance.vision. Log in there and generate a key. In the SDK, set
testnet: true. Requests go tohttps://testnet.binance.vision. - Demo Trading. Binance’s Demo Mode documentation says to open Binance Demo Trading after logging in and create the key on its API Key Management page. In the SDK, set
demoTrading: true. Spot requests go tohttps://demo-api.binance.com, USD-M futures requests tohttps://demo-fapi.binance.com.
For futures, the Siebly guide to Binance Testnet and demo trading recommends demoTrading: true with a Demo Trading key, because Binance’s futures documentation calls its demo host a testnet.
Set one flag, never both. With both set, MainClient refuses to build a URL and throws on the first request:
Error: Demo trading is currently not supported for the product group "spottest". If demo trading should be available here, please open an issue on GitHub.
Binance API key errors: -2014, -2015, -1022 and -1021
Four error codes point at the key itself. The messages match Binance’s Spot API error codes page, and -2014, -2015 and -1021 are reproduced on this page with made-up keys.
-2014 “API-key format invalid.”
The string in api_key is not shaped like a Binance key. Reproduced with abc, with a 64 character key wrapped in double quotes, and with a key pasted twice (128 characters). A key cut short to 40 characters, or one with a trailing space, got -2015 instead. Either way, print the key’s length and compare it with the value Binance shows.
-2015 “Invalid API-key, IP, or permissions for action.”
Binance does not accept the key for this request. Reproduced with a random key on both environments. The usual causes are a key from another environment (live key on testnet or the reverse), a request from an IP that is not on the key’s whitelist, or a missing permission such as futures. The full list is in the -2015 checklist for Node.js.
-1022 “Signature for this request is not valid.”
Binance knows the key but the signature does not verify. With an HMAC key that usually means the wrong secret. With an Ed25519 key, the private key does not belong to the public key you registered. This one cannot be reproduced without a registered key, because an unknown key fails with -2015 first.
A PEM that lost its line breaks is often blamed for -1022. The SDK repairs that case: its constructor turns a literal \n back into a line break and strips whitespace before decoding the key, so a PEM squeezed onto one line still signs correctly. Here is what each kind of damage does in 3.6.15, using the throwaway private key from earlier:
private PEM, intact: request sent, signature 88 chars -> -2015 Invalid API-key, IP, or permissions for action.
private PEM on one line: request sent, signature 88 chars -> -2015 Invalid API-key, IP, or permissions for action.
private PEM with literal \n: request sent, signature 88 chars -> -2015 Invalid API-key, IP, or permissions for action.
private PEM wrapped in quotes: thrown before sending -> InvalidCharacterError: Invalid character
private PEM missing a character: thrown before sending -> DataError: Invalid keyData
public PEM by mistake: request sent, signature 64 chars -> -2015 Invalid API-key, IP, or permissions for action.
- One line and
\nescapes are fine: the request goes out with the same 88 character Ed25519 signature as the intact key. - Quotes kept around the value, or a key with characters missing, fail locally before any request, with
InvalidCharacterErrororDataError. Search for those names, not for-1022. - The public key pasted into
api_secretraises no local error at all. It has noPRIVATE KEYheader, so the SDK treats it as an HMAC secret and sends a 64 character hex signature that Binance cannot verify against your registered key.
-1021 “Timestamp for this request is outside of the recvWindow.”
Every signed request carries a timestamp, and Binance rejects it when it is too far from server time. The default receive window is 5000 ms. This script reproduces the error on Spot Testnet by telling the client its clock is two minutes slow:
import { randomBytes } from 'node:crypto';
import { MainClient } from 'binance';
// Throwaway key on Spot Testnet. Binance checks the timestamp before the key.
const client = new MainClient({
api_key: randomBytes(32).toString('hex'),
api_secret: randomBytes(32).toString('hex'),
testnet: true,
});
// Pretend the local clock runs 120 seconds behind Binance.
client.setTimeOffset(-120_000);
try {
await client.getAccountInformation();
} catch (err) {
const { code, message } = err as { code?: number; message?: string };
console.log(`${code}: ${message}`);
}
-1021: Timestamp for this request is outside of the recvWindow.
The key here is random too, and Binance still answers with -1021 rather than -2015: it checks the timestamp first. Fix the host clock (NTP) before anything else. Time sync in the SDK is off by default in 3.6.15; set disableTimeSync: false to have the client measure its offset from Binance at start-up and every syncIntervalMs (one hour by default). The -1021 guide for Node.js covers recvWindow and clock drift in detail, and Binance API error codes in JavaScript covers the rest of the list.
Next steps
- The Binance API key setup guide in the Siebly docs is the short reference version of this page.
- The Binance JavaScript SDK tutorial goes from a working key to market data, orders and WebSocket streams.
- TradingView Binance alerts to USD-M orders puts a demo key to work behind a webhook.
The binance package is one of the Siebly SDKs, which have over 4.8 million npm downloads across 10+ SDKs.
Versions: binance 3.6.15, Node.js 24.22.1, TypeScript 7.0.2.
