Quickstart
Bun
Authentication for Bun’s http server
Read more on bun’s http server here
Prerequisites
Creating a bun server
1
Install
For bun’s installation, refer to their documentation
Now install the @unkey/api
package
bun install @unkey/api
2
Creating the server
Create a file called server.ts
and add the following code
server.ts
import { verifyKey } from "@unkey/api";
Bun.serve({
async fetch(req) {
const key = req.headers.get("Authorization")?.replace("Bearer ", "");
if (!key) {
return new Response("Unauthorized", { status: 401 });
}
const { result, error } = await verifyKey(key);
if (error) {
// This may happen on network errors
// We already retry the request 5 times, but if it still fails, we return an error
console.error(error);
return Response.json("Internal Server Error", { status: 500 });
}
if (!result.valid) {
return new Response("Unauthorized", { status: 401 });
}
return Response.json(result);
},
port: 8000,
});
3
Running the server
bun run server.ts
4
Try it out
Go to https://app.unkey.com and create a new key. Then verify it with our new server:
curl http://localhost:8000 -H "Authorization: Bearer <KEY>"
It should return { "valid": true }
and potentially more information about the key, depending on what you set up in the dashboard.
Was this page helpful?