apikeys.do
Cloudflare Worker & Durable Object for API Key Management
Because the ID of a Durable Object is itself a hash, we don’t have worry about managing hashes seperately.
When a new key is generated, a Durable Object is created using idFromName:
const apiKey = Crypto.randomUUID()
const id = APIKEYS.idFromName(apiKey)
Note, the apiKey is never persisted, and because the ID of the Durable Object is a hash, it cannot be used to recalculate the apiKey.
export class ApiKeys {
constructor(state, env) {
this.state = state
state.blockConcurrencyWhile(async () => {
this.profile = await state.storage.get('profile')
this.stats = await state.storage.list({ prefix: 'stats' })
})
}
async fetch(req) {
const url = req.url
const { origin, method, hostname, pathname, search, hash } = new URL(url)
const id = req.headers.get('cf-ray') + '-' + req.cf.colo
const ts = Date.now()
// Update Stats
this.data[id] = { id, ts, origin, method, hostname, pathname, search, hash }
// Record request
this.state.storage.put('req:' + id, { id, ts, origin, method, hostname, pathname, search, hash }, { allowUnconfirmed: true })
return new Response(
JSON.stringify(
{
profile: this.profile,
stats: this.stats,
},
null,
2
),
{ headers: { 'content-type': 'application/json' } }
)
}
}
Which then returns:
{
"profile": {
"name": "John Developer",
"email": "[email protected]",
"image": "https://github.io/profile/pic.jpg"
},
"stats": {
"totalCalls": 1000,
"monthlyCalls": 100,
"dailyCalls": 10
}
}
🚀 We’re hiring!
Driv.ly is simple APIs to buy & sell cars online, funded by some of the biggest names in automotive and finance & insurance
We’re building our entire infrastructure on Cloudflare Workers, Durable Objects, KV, R2, and PubSub. If you’re as passionate about these transformational technologies as we are, we’d love for you to join our rapidly-growing team.