How to add API key authentication to your API
Issue, verify, rotate, and revoke API keys for your customers with Unkey, with working Express and Next.js code and the status code to return for each result.

Your API just landed its first paying customer, and they want an API key. You can build the keys table, the hashing, the lookup, the rotation flow, and an admin screen to manage it all. Or you can make two API calls: one when a customer asks for a key, and one on every request.
This guide takes the two-call route with Unkey. You'll issue a key, verify it in Express and Next.js, return the right status code for each failure, and rotate and revoke keys. The later sections cover scoped keys for AI agents and when to use OAuth instead.
How to add API key authentication without writing your own key system
Use Unkey. Create keys with keys.createKey, then call keys.verifyKey on every request. Unkey stores only a hash of each key, and that one verify call also checks expiry, permissions, rate limits, and credits.
A key system is more than a table of keys. It needs random secrets, hashed storage, a show-once flow, expiry, revocation, rotation with a grace period, per-key rate limits, usage limits, and an audit trail of who verified what. Each piece is easy to build. Together they're a product you have to maintain forever.
Step 1: Create a keyspace and a root key
You need two things before you write any code. A keyspace is the container your keys live in. A root key is the credential your backend uses to create and verify them.
Start with the root key. In the Unkey dashboard, open Root Keys and create one that can create keyspaces, write keys, and verify keys. Store it as UNKEY_ROOT_KEY on your server. It should never end up in a browser or a mobile app.
Then create the keyspace, either in the dashboard or with one call:
Save the apiId from the response as UNKEY_API_ID. You need it every time you create a key.
Step 2: Issue a key when a customer asks for one
When a customer asks for a key, call keys.createKey from your backend. You get two things back: the key itself, which you show the customer exactly once, and a keyId, which you keep.
The key comes out as sk_live_ followed by 16 random bytes encoded in base58. The prefix lets people and secret scanners spot a leaked key. externalId ties the key to your customer, so every verification tells you who's calling. meta also comes back on every verification, so you can read the plan from the response without a database lookup.
Unkey keeps only a hash of the key, unless you create it as a recoverable key. So if a customer loses theirs, you can't look it up for them. Issue a new one.
Step 3: Verify the key in Express middleware
The middleware pulls the key out of the Authorization header, calls keys.verifyKey, and stops the request if the result isn't valid.
Two details in that code are easy to get wrong.
First, next() sits outside the try on purpose. Put it inside and an error thrown in a route handler lands in the catch and comes back as a 503. Then you go looking for the bug in the wrong place.
Second, keys.verifyKey returns HTTP 200 for every outcome, including an invalid key. A successful call doesn't mean a valid key. You have to read data.valid and data.code, then send the status yourself.
Step 4: Verify the key in a Next.js route handler
Next.js is less work, because @unkey/nextjs wraps an App Router route handler for you. It reads the bearer token, calls keys.verifyKey, and returns a 401 if the key is missing or invalid. Your code only runs when the key is good.
To require a permission, pass permissions: 'items.write' in the options. If you'd rather send a 429 or 403 than the default 401, set handleInvalidKey and branch on result.data.code.
What status to return for each verification result
This table maps each data.code to an HTTP status.
The checks run in order and stop at the first failure, so a failed check never spends anything further down the list. A key without the permission doesn't spend rate limit or credits, and a rate limited request doesn't spend credits.
How to generate, store, and rotate API keys safely
Unkey generates each API key from random bytes, stores only the hash, and shows the key to your customer once. To rotate API keys, use keys.rerollKey. It issues a new key and keeps the old one working for a grace period, so clients have time to switch.
expiration is how long the old key keeps working, in milliseconds from now. Here that's 24 hours. The new key copies everything from the old one: name, metadata, identity, expiry, credits, permissions, roles, and rate limits. Send the new key to the customer, and the old one stops working on schedule. The dashboard's Rotate key action does the same thing.
A leak is the one case where you don't want the overlap. Pass expiration: 0 and the old key is revoked immediately.
How to revoke or suspend an API key
You can disable a key or delete it. Pick based on whether the key is coming back.
If it might, disable it. Call keys.updateKey with enabled: false. From then on verifications return DISABLED, and they don't use up rate limits or credits. Set enabled: true to bring the key back, for example after a failed payment clears.
If it's gone for good, delete it with keys.deleteKey.
Either way, the change applies to the next request, because every request is a lookup. A signed token is different. It stays valid until it expires, whatever you do.
How to give AI agents secure, scoped API keys
Give each AI agent its own Unkey API key, scoped to only what it needs: specific permissions, an expiry, a rate limit, and a credit balance. An agent can make thousands of bad calls before anyone notices. When one goes wrong, you revoke one key and nothing else breaks.
expires is a Unix timestamp in milliseconds, and once it passes the key returns EXPIRED. The rate limit and the credits cover different failures. The rate limit stops a burst. Credits are an exact count, so an agent stuck in a loop stops with USAGE_EXCEEDED the moment the balance hits zero. If a route needs more than one permission, the permissions query on keys.verifyKey accepts AND and OR, as in tickets.read AND tickets.comment.
Should you use API keys or OAuth for a public API?
It depends on who's making the call. 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. Plenty of public APIs offer both, and Unkey handles the API key side.
Keys are simpler. A developer copies one and sends it in a header. They suit server-to-server calls, usage-based plans, and per-customer rate limits, because the key already names the customer.
OAuth brings a consent screen, redirects, and token refresh. That overhead is worth it when the question is "may this app read my data?" and not "which customer is calling?". A JWT is a token format, not a third option. OAuth servers often issue JWTs as access tokens.
API keys, rate limits, and usage tracking without building them in house
All three come from the same Unkey call. keys.verifyKey checks the key, its rate limits, and its credits together, and Unkey records each verification, so you can query usage per key or per customer with SQL.
Rate limits can sit on the key or on the customer's identity. Put them on the identity and every key that customer holds shares one number. How to rate limit an API per customer or per API key walks through that setup. Credits are how you do monthly quotas, with a refill each month. To query the verification records, analytics has to be on for your workspace, so ask Unkey support to enable it. The analytics docs list the tables.
Checking API keys at the gateway when Unkey hosts the API
If your API runs on Unkey Compute, you can let the gateway check the API key before the request reaches your code. Add a Key Auth policy to the app and choose the keyspace. Hosting, API keys, and rate limiting then live in one Unkey setup.
Keys behave the same at the gateway as they do with keys.verifyKey. A bad key gets a 401, 403, or 429 and your app never sees the request. A good key arrives with the caller's details in a header your app can read. The API key authentication policy docs list the settings.
