Skip to main content

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.
1

Create a new Bun project

2

Install the SDK

3

Add your root key

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

Create your server

Replace the contents of index.ts:
index.ts
5

Run your server

6

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:

Adding routes

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

Next steps

Add rate limiting

Protect endpoints from abuse

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 header format: Authorization: Bearer YOUR_KEY (note the space)
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
Run bun init -y to ensure you have a proper tsconfig.json. Bun handles TypeScript natively, no extra setup needed.
Last modified on June 2, 2026