How to Generate a Secure API Key

Published April 2025 · 4 min read

Node.js

const crypto = require('crypto');
const apiKey = crypto.randomBytes(32).toString('hex');
// "a1b2c3d4e5f6..."  (64 hex characters)

Python

import secrets
api_key = secrets.token_hex(32)
# "a1b2c3d4e5f6..."

Command Line

# Linux/Mac
openssl rand -hex 32

# Or
python3 -c "import secrets; print(secrets.token_urlsafe(32))"

Best Practices

  • Use at least 32 bytes (256 bits) of randomness
  • Use crypto-secure random generators (not Math.random)
  • Add a prefix for identification: sk_live_a1b2c3...
  • Store hashed in database, not plain text
  • Set expiration dates
  • Implement rate limiting per key

Quick Generate

Use our Password Generator with max length for a quick secure key.

Related