Skip to main content

What you’ll build

An Express server with a protected /secret route that requires a valid API key. Requests without a valid key get rejected with a 401. Time to complete: ~5 minutes

Prerequisites

Want to skip ahead?

Clone the complete example and run it locally.
1

Create your Express app

2

Add your root key

Get a root key from Settings → Root Keys and create a .env file:
.env
Never commit your .env file. Add it to .gitignore.
3

Create your server

Create index.js with a protected route:
index.js
4

Start your server

5

Test it

First, create a test key in your Unkey dashboard, then:
Test with valid key
You should see:
Now try without a key:
Test without key
You’ll get:

What’s in data?

After successful verification, data contains:

Using as middleware

For cleaner code, extract verification into middleware:
middleware/auth.js
Then use it on any route:

Next steps

Add rate limiting

Limit requests per key

Set usage limits

Cap total requests per key

Add permissions

Fine-grained access control

SDK Reference

Full TypeScript SDK docs

Troubleshooting

  • Ensure the key hasn’t expired or been revoked - Verify the Authorization header format: Bearer YOUR_KEY (note the space) - Check that your root key has the verify_key permission
  • Check that UNKEY_ROOT_KEY is set correctly in your .env - Make sure you’re calling require("dotenv").config() before using env vars - Check the Unkey dashboard for any service issues
The code above uses CommonJS. For TypeScript, install types and use imports:
Last modified on June 2, 2026