Building APIs with Cloudflare Workers and Hono.js
I've been messing around with Cloudflare Workers lately, and honestly, it's pretty cool. The whole "edge computing" thing sounded fancy at first, but after building a few APIs with it, I can see why people are hyped.
Why Cloudflare Workers?
The main thing that got me interested was the speed. Your code runs at the edge, close to users, which means low latency. Plus, the free tier is generous - 100,000 requests per day. That's enough for most side projects.
The pricing is also pretty straightforward. After the free tier, it's $5/month for 10 million requests. Not bad at all.
Enter Hono.js
I tried building a Worker with just the basic API at first, but it felt a bit verbose. Then I found Hono.js, and it made things way simpler. It's like Express but for the edge.
Here's a basic example:
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => {
return c.text('Hello from the edge!')
})
app.get('/api/users/:id', async (c) => {
const id = c.req.param('id')
// fetch user data
return c.json({ id, name: 'John' })
})
export default app
That's it. Super clean and easy to read.
What I Built
I made a simple API for a project that needed to:
- Handle user authentication
- Fetch data from a database
- Return JSON responses
With Hono, the routing is intuitive. You can use middleware, validate requests, and handle errors without much boilerplate.
// Middleware example
app.use('*', async (c, next) => {
const auth = c.req.header('Authorization')
if (!auth) {
return c.json({ error: 'Unauthorized' }, 401)
}
await next()
})
The Good Parts
- Fast cold starts - Workers start in milliseconds
- Global distribution - Your code runs everywhere automatically
- Simple deployment - Just
wrangler publishand you're done - TypeScript support - Works great out of the box
The Not-So-Good Parts
- Debugging can be tricky. The local dev server works, but sometimes things behave differently in production
- No file system access (obviously, it's serverless)
- Memory limits are tight (128MB), but usually enough
My Setup
I use Wrangler CLI for development:
npm install -g wrangler
wrangler init
wrangler dev # local development
wrangler publish # deploy
The wrangler.toml config is pretty simple:
name = "my-api"
main = "src/index.ts"
compatibility_date = "2024-01-01"
Real Talk
Is it worth it? For most APIs, probably. If you need something super complex with lots of dependencies, maybe not. But for simple REST APIs, it's perfect.
The combination of Workers + Hono.js gives you a fast, cheap way to build APIs that scale globally. Plus, it's fun to work with. Sometimes that's enough reason to use something.
I'm still learning, but so far it's been a solid choice for my projects. The docs are good, the community is helpful, and it just works.