Docs / Frameworks / Hono / Workers
Hono / Cloudflare Workers
In a Worker, create the client per-request from env bindings — globals don't persist across isolates the way they would on Node, and you want the request's cookie forwarded to the auth Worker anyway.
// src/index.ts
import { Hono } from "hono"
import { createFlarelink } from "@flarelink/client"
type Env = { FLARELINK_AUTH_URL: string; FLARELINK_SERVICE_KEY: string }
const app = new Hono<{ Bindings: Env }>()
app.get("/posts", async (c) => {
const flarelink = createFlarelink({
url: c.env.FLARELINK_AUTH_URL,
serviceKey: c.env.FLARELINK_SERVICE_KEY,
cookies: () => c.req.header("cookie") ?? "",
})
const { rows: posts } = await flarelink.from("posts").limit(20)
return c.json({ posts })
})
export default app
Protect a route
A requireUser middleware constructs the client, resolves the user, and stashes it on the context — protected handlers read c.var.user and scope every query to it.
// src/auth.ts
import { createFlarelink, type User } from "@flarelink/client"
import { createMiddleware } from "hono/factory"
export const requireUser = createMiddleware<{
Bindings: Env; Variables: { user: User; flarelink: ReturnType<typeof createFlarelink> }
}>(async (c, next) => {
const flarelink = createFlarelink({
url: c.env.FLARELINK_AUTH_URL,
serviceKey: c.env.FLARELINK_SERVICE_KEY,
cookies: () => c.req.header("cookie") ?? "",
})
const me = await flarelink.auth.getMe()
if (!me) return c.json({ error: "Unauthorized" }, 401)
c.set("user", me)
c.set("flarelink", flarelink)
await next()
})
// src/index.ts
app.get("/my/posts", requireUser, async (c) => {
const { rows } = await c.var.flarelink
.from("posts")
.where({ author_id: c.var.user.id }) // scope to the signed-in user
return c.json({ posts: rows })
})
# wrangler vars / .dev.vars
FLARELINK_AUTH_URL=https://myapp-auth.your-subdomain.workers.dev
FLARELINK_SERVICE_KEY=flarelink_sk_…
Something unclear or missing? [email protected]
llms-full.txt ↗