Random String & Nano ID Generator · Tutorial

How to generate a secure API key or secret token

6 min readintermediateUpdated

API keys, webhook secrets and session tokens must be impossible to guess. You will generate a key with a prefix such as sk_live_, confirm it has well over 128 bits of randomness, and learn how to store it so a database leak does not expose it.

What you need

Steps

  1. Choose a large alphabet and length

    Set Characters to Letters and numbers and Length to 40. Each character adds almost 6 bits, so the key has about 238 bits of randomness, far beyond what anyone could guess.

  2. Add a prefix

    Type sk_live_ in Prefix. A prefix makes keys easy to recognise in logs and lets secret scanners such as GitHub’s spot a leaked key. Use a different prefix for test keys.

    sk_live_Xq3T9vLmA27pZcKe8RwYbN4uHs6JdF0gQiOt5VyE
  3. Generate one key

    Set How many to 1 and press Generate new. Copy the key straight into your secret manager or show it to the user once.

  4. Store a hash, not the key

    Treat keys like passwords: save a SHA-256 hash of the key in the database, plus the first few characters to help users tell keys apart. When a request arrives, hash the key it sends and look for that hash.

Try it yourself

Opens the Random String & Nano ID Generator with this tutorial's sample loaded.

Try it now

Common mistakes

Choosing a short key
Under 128 bits, a determined attacker with many machines can start to make progress. The strength summary tells you where you are.
Committing keys to a repository
Put keys in environment variables or a secret manager, and add .env files to your .gitignore.

Next steps

Go back to the Random String & Nano ID Generator, or keep going with one of these:

FAQ

Is a UUID good enough as an API key?

A v4 UUID has 122 random bits, which is borderline. A 40-character random string is stronger and lets you add a prefix.