unkey
  • BlogRead product updates and insights
  • Case studiesPractical results from real deployments
  • ChangelogTrack what shipped, improved, and fixed
  • GlossaryClear definitions for API terms
PricingDocs
Discord
LoginSign Up
  • BlogRead product updates and insights
  • Case studiesPractical results from real deployments
  • ChangelogTrack what shipped, improved, and fixed
  • GlossaryClear definitions for API terms
PricingDocsDiscord
LoginSign Up
  1. Glossary
  2. /API Key

What an API Key Is

Explore with AI
Open in ChatGPTOpen in ClaudeOpen in Perplexity

TL;DR

An API key is a secret a client sends with each request. The server looks the secret up, and possession of the string is what identifies the caller. Store only a hash, show the key once, and rotate with a grace period.

What it is

A secret the client sends

What it names

An integration rather than a person

How it is checked

A server-side lookup of a hash

An API key is a secret string a client sends with a request so the API can tell who is calling. The server compares that string with a record it issued. If the record is active, the request continues as that caller.

To add API keys to an API without writing your own key system, use a service that issues the keys, stores only a hash, and answers one verify call per request. Your server sends the key the client presented and gets back valid or not, plus the reason.

Possession of the string is the check. Anyone who copies the key can call the API until you revoke the record.

What an API key is

The key names an integration: one application, one service, or one customer project. It does not, by itself, name the person at a keyboard. The record behind the key can hold an owner, a scope, and an expiry. The secret should be random, at least 16 bytes (128 bits) from a cryptographic generator, so nobody can guess it. 32 bytes is plenty for the most sensitive uses.

A label in front of the secret, such as sk_live_, is not the secret. Scanners use the label to recognize a leaked string. The random bytes are what the server checks.

How a server checks a key

Store a hash of the secret, not the secret. Show the plaintext once, when the key is created, and do not write it to application logs.

A useful shape is a public id plus a secret, joined by one dot: key_01J0AB.example-secret. The id can be logged and indexed. The secret cannot. Encode the secret with base64url, which does not contain a dot, and split the token on the first dot only.

import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';

function createApiKey(id) {
  const secret = randomBytes(32).toString('base64url');

  return {
    id,
    plaintext: `${id}.${secret}`,
    hash: createHash('sha256').update(secret, 'utf8').digest(),
  };
}

function secretMatches(storedHash, presentedSecret) {
  const actual = createHash('sha256').update(presentedSecret, 'utf8').digest();

  if (actual.length !== storedHash.length) {
    return false;
  }

  return timingSafeEqual(actual, storedHash);
}

Persist id and hash. On a request, load the row by id and compare hashes. SHA-256 is appropriate when the secret is long and random. If a person chooses the secret, use a slow password hash such as scrypt. A fast hash of a short secret can be guessed offline.

timingSafeEqual throws when the two buffers have different lengths, so check the length first. A normal string compare can also leak information through timing. Compare the hashes, not the raw secrets.

That is the core. A production key system also needs expiry, revocation, per-key rate limits, usage tracking, rotation, and an audit trail.

How do you add API key authentication without building it yourself?

To add API key authentication without building it yourself, use a key management service or the key auth feature of an API gateway you already run. It issues keys, stores only a hash, and answers one verify call per request that checks expiry, revocation, scope, and limits.

What to check before you pick one:

  1. Hashing. The provider stores a hash, and shows the plaintext only once.
  2. One verify call. Expiry, revocation, permissions, and rate limits come back in a single answer, so the request path has one network hop.
  3. Customer link. Each key carries your customer id, so limits and usage roll up to the customer and not only the key.
  4. Rotation. You can issue a replacement and keep the old key working for a grace period.
  5. Status codes. You decide what to return. Missing or unknown keys get 401, a key without the permission gets 403, and a key over its limit gets 429.

A gateway check runs before the request reaches your code. A verify call from your handler works wherever the API is hosted.

What is the safest way to generate, store, and rotate API keys?

Generate the secret from a cryptographic random source, store only its hash, show it once, and rotate with an overlap. Each step closes a different leak.

  1. Generate. Use at least 16 random bytes from a cryptographic generator. A short prefix like sk_live helps people and scanners recognize the key.
  2. Store. Keep a hash, not the key. A leaked copy of the database then yields no working keys. If you truly need to show a key again later, keep an encrypted copy next to the hash and restrict who can decrypt it.
  3. Show once. Return the plaintext in the create response and nowhere else. If a customer loses it, issue a new key.
  4. Rotate with an overlap. Issue the replacement first, keep the old key working while clients move, then let it expire.

The replacement should copy the old key's owner, permissions, and limits, so rotation never changes what the client can do. Give the old key an expiry, such as 24 hours, instead of deleting it at once. After a leak, skip the overlap and revoke the old key right away.

API keys, passwords, and JWTs

A password proves a person, once, at login. An API key proves an integration on every call. Replacing a person's password should not be how you cut off one misbehaving service.

A JWT is a signed set of claims. Services that hold the verification key can trust the claims without a shared key database. The token remains valid until exp unless every verifier also checks a revocation list. An API key forces a lookup. That lookup is how you revoke it immediately, and it is also a request the key database has to answer.

Use a key when a service needs a stable credential you can disable on the next call. Use a short-lived JWT when many services need to verify a user and you accept that early revoke is a separate problem.

Should you use API keys or OAuth for a public API?

Use API keys when developers call your API from their own servers, as themselves. Use OAuth when a third-party app acts for one of your users and that user has to consent. Many public APIs offer both.

API keys are simpler for the developer. They copy a key and send it in a header. They fit server-to-server calls, usage-based plans, and per-customer rate limits, because the key already names the customer. OAuth adds a consent screen, redirects, and token refresh. That cost is worth it when the question is "may this app read my data", not "which customer is calling". A JWT is a token format, not a choice between the two. OAuth servers often issue JWTs as access tokens.

How do you give AI agents secure, scoped access to an API?

Give each agent its own API key with only the permissions it needs, an expiry, a rate limit, and a usage cap. Then one agent going wrong is one key to revoke, not an outage.

Scope the key to the calls the agent makes, such as reading tickets and posting comments, and check that permission in the route. Set the expiry to the length of the job. A usage cap is an exact count of calls, so an agent stuck in a loop stops when the balance runs out. The rate limit keeps it from spending that balance in one burst.

Where to send the key

Send the key in a header, and only over TLS. RFC 6750 defines Authorization: Bearer for bearer tokens. An API key is one kind of bearer token: the string itself is the credential. A custom header such as X-API-Key is also common. Pick one place and document it.

GET /v1/orders HTTP/1.1
Host: api.example.com
Authorization: Bearer key_01J0AB.example-secret
Accept: application/json

The secret in that example is a placeholder. A real secret is random bytes from a cryptographic generator, not a word.

Do not put the key in the query string. URLs are copied into access logs, browser history, and Referer headers when the client loads another site. The OWASP REST Security Cheat Sheet treats that as a credential leak.

On plain HTTP the key is visible to anything on the path. Require TLS.

Scope and expiry

A key should allow only the calls that client needs. A reporting job with a read-only key cannot delete data if the key leaks. A key used by two unrelated services cannot be revoked for one of them without breaking the other. Issue separate keys.

Set an expiry when the client can refresh. A key with no expiry works until someone notices it leaked.

The key names the caller. A rate limit decides how many calls that caller may make. They are separate controls. A valid key can still be over its limit.

Common mistakes

Shipping the key to a browser or a mobile app. Anything in the client can be extracted. Keep the key on a server you run, or give the end user a short-lived credential of their own.

Logging the header. An access log that stores Authorization stores the secret. Log the key id if you need a correlation id.

Comparing the plaintext with ===. Hash first, check the lengths, then use a constant-time compare.

Treating the key as a user id. The record names the integration. If the API has to know the person, that person needs their own login. Do not share one project key across every user of a product.

One key for every environment. A key that works in production and in a laptop app will leak from the laptop. Use a different key, and a different scope, for each environment.

API keys with Unkey

Unkey issues and verifies API keys as a service. keys.createKey returns the key once, and by default Unkey stores only a hash. Your server calls keys.verifyKey with the key the client sent, and that one call checks expiry, permissions, rate limits, and credits. keys.rerollKey rotates a key and keeps the old one working for a grace period. The verifying keys docs list every check.

Questions & Answers about API Key

An API key is a secret string a client sends so the API can tell which integration is calling. The server compares it with a record it issued. If that record is active, the request continues as that caller. Anyone who copies the string can use it until the record is revoked.

On this page

  1. What an API key is
  2. How a server checks a key
  3. How do you add API key authentication without building it yourself?
  4. What is the safest way to generate, store, and rotate API keys?
  5. API keys, passwords, and JWTs
  6. Should you use API keys or OAuth for a public API?
  7. How do you give AI agents secure, scoped access to an API?
  8. Where to send the key
  9. Scope and expiry
  10. Common mistakes
  11. API keys with Unkey

Turn your API stack into one workflow. Start for free, integrate in minutes, and scale when you need to.

Start for free
unkey

Build better APIs faster

© 2026 Unkey Inc. All rights reserved.

SOC 2 Type II Certified

Company

  • About
  • Careers
  • Status Page
  • Roadmap

Resources

  • Blog
  • Case Studies
  • Changelog
  • Docs
  • Glossary
  • Feature Request
  • Archive

Connect

  • X (Twitter)
  • Discord
  • Book a Call

Legal

  • Terms of Service
  • Privacy Policy
  • Trust Center