Skip to main content

Bun

Add API key authentication to your Bun server with Unkey. Verify keys on each request to protect your endpoints in a few lines of code.
2 min read

What you'll build#

A Bun HTTP server that requires a valid API key on every request. Invalid or missing keys get rejected with a 401.

Time to complete: ~3 minutes

Prerequisites#

Want to skip ahead?

Clone the complete example and run it locally.

Create a new Bun project#

Install the SDK#

Add your root key#

Create a .env file with your credentials from the Unkey dashboard:

.env

Create your server#

Replace the contents of index.ts:

index.ts

Run your server#

Test it#

Create a test key in your Unkey dashboard, then:

Test with valid key

You should see:

Try without a key:

Test without key

You'll get:

What's in data?#

After successful verification:

FieldTypeDescription
validbooleanWhether the key passed all checks
codestringStatus code (VALID, NOT_FOUND, RATE_LIMITED, etc.)
keyIdstringThe key's unique identifier
namestring?Human-readable name of the key
metaobject?Custom metadata associated with the key
expiresnumber?Unix timestamp (in milliseconds) when the key will expire. (if set)
creditsnumber?Remaining uses (if usage limits set)
enabledbooleanWhether the key is enabled
rolesstring[]?Permissions attached to the key
permissionsstring[]?Permissions attached to the key
identityobject?Identity info if externalId was set when creating the key
ratelimitsobject[]?Rate limit states (if rate limiting configured)

Adding routes#

Bun's built-in server uses a single fetch handler. For multiple routes, pattern match on the URL:

index.ts

Next steps#

Troubleshooting#

Getting 401 even with a valid key?
  • Ensure the key hasn't expired or been revoked - Verify the header format: Authorization: Bearer YOUR_KEY (note the space)
Environment variables not loading?

Bun automatically loads .env files. Make sure: - The .env file is in your project root - You're using Bun.env.VAR_NAME not process.env.VAR_NAME - Restart the server after changing .env

TypeScript errors?

Run bun init -y to ensure you have a proper tsconfig.json. Bun handles TypeScript natively, no extra setup needed.