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 minutesPrerequisites
- Unkey account (free)
- Keyspace created in your Unkey dashboard
- Bun installed
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:You should see:Try without a key:You’ll get:
Test with valid key
Test without key
What’s in data?
After successful verification:
Adding routes
Bun’s built-in server uses a singlefetch 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
Getting 401 even with a valid key?
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?
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 .envTypeScript errors?
TypeScript errors?
Run
bun init -y to ensure you have a proper tsconfig.json. Bun handles
TypeScript natively, no extra setup needed.