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#
- Unkey account (free)
- Keyspace created in your Unkey dashboard
- Bun installed
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:
Create your server#
Replace the contents of index.ts:
Run your server#
Test it#
Create a test key in your Unkey dashboard, then:
You should see:
Try without a key:
You'll get:
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 single fetch handler. For multiple routes, pattern match on the URL:
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.