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)
- API created in your Unkey dashboard
- Bun installed
Want to skip ahead?
Clone the complete example and run it locally.
Add your root key
Create a
.env file with your credentials from the Unkey dashboard:.env
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:
| Field | Type | Description |
|---|---|---|
valid | boolean | Whether the key passed all checks |
code | string | Status code (VALID, NOT_FOUND, RATE_LIMITED, etc.) |
keyId | string | The key’s unique identifier |
name | string? | Human-readable name of the key |
meta | object? | Custom metadata associated with the key |
expires | number? | Unix timestamp (in milliseconds) when the key will expire. (if set) |
credits | number? | Remaining uses (if usage limits set) |
enabled | boolean | Whether the key is enabled |
roles | string[]? | Permissions attached to the key |
permissions | string[]? | Permissions attached to the key |
identity | object? | Identity info if externalId was set when creating the key |
ratelimits | object[]? | Rate limit states (if rate limiting configured) |
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
.envfile is in your project root - You’re using
Bun.env.VAR_NAMEnotprocess.env.VAR_NAME - Restart the server after changing
.env
TypeScript errors?
TypeScript errors?
Run
bun init -y to ensure you have a proper tsconfig.json. Bun handles TypeScript natively, no extra setup needed.
