Hono is a small, fast, web standards-based framework that runs on Cloudflare Workers, Deno, Bun, and Node.js. Its edge-first design makes UUID v7 an excellent default for all identifiers — the embedded timestamp enables time-range queries without a separate created_at index, and the random bits prevent collisions across concurrent edge invocations. See UUID in Edge Functions for the broader edge runtime context.
Setup
npm create hono@latest my-app
# Select: cloudflare-workers (or bun, deno, nodejs)
npm install uuid
// src/index.ts
import { Hono } from 'hono';
import { v7 as uuidv7 } from 'uuid';
const app = new Hono();
export default app;
UUID v7 trace ID middleware
import { Hono } from 'hono';
import { v7 as uuidv7 } from 'uuid';
const app = new Hono();
// Inject UUID v7 trace ID for every request
app.use('*', async (c, next) => {
const traceId = c.req.header('x-trace-id') ?? uuidv7();
c.set('traceId', traceId);
await next();
c.res.headers.set('x-trace-id', traceId);
});
// Access in any handler
app.get('/orders', (c) => {
const traceId = c.get('traceId');
console.log({ traceId, method: 'GET /orders' });
return c.json({ traceId });
});
UUID v7 trace IDs sort chronologically in log aggregators. See UUID v7 in Microservices.
Cloudflare D1 with UUID v7 primary keys
import { Hono } from 'hono';
import { v7 as uuidv7 } from 'uuid';
type Env = { Bindings: { DB: D1Database } };
const app = new Hono<Env>();
// POST /orders — UUID v7 primary key
app.post('/orders', async (c) => {
const body = await c.req.json<{ customerId: string; total: number }>();
const order = { id: uuidv7(), ...body };
await c.env.DB.prepare(
'INSERT INTO orders (id, customer_id, total) VALUES (?, ?, ?)'
)
.bind(order.id, order.customerId, order.total)
.run();
return c.json(order, 201);
});
// GET /orders — cursor pagination with UUID v7
app.get('/orders', async (c) => {
const cursor = c.req.query('cursor');
const limit = Number(c.req.query('limit') ?? 20);
const stmt = cursor
? c.env.DB.prepare(
'SELECT id, customer_id, total FROM orders WHERE id > ? ORDER BY id LIMIT ?'
).bind(cursor, limit)
: c.env.DB.prepare(
'SELECT id, customer_id, total FROM orders ORDER BY id LIMIT ?'
).bind(limit);
const { results } = await stmt.all();
const nextCursor = results.length === limit ? results[results.length - 1].id : null;
return c.json({ results, nextCursor });
});
D1 is SQLite — UUID v7 strings compare lexicographically in chronological order. See UUID in SQLite.
Cloudflare KV with UUID v7 keys
type Env = { Bindings: { KV: KVNamespace } };
const app = new Hono<Env>();
// Store session with UUID v7 key
app.post('/sessions', async (c) => {
const body = await c.req.json<{ userId: string }>();
const sessionId = uuidv7();
await c.env.KV.put(
`session:${sessionId}`,
JSON.stringify({ userId: body.userId, createdAt: new Date().toISOString() }),
{ expirationTtl: 86400 } // 24 hours
);
return c.json({ sessionId }, 201);
});
KV keys are strings — UUID v7 as a KV key provides natural time ordering for listing sessions. See UUID in Redis for the equivalent Redis pattern.
Zod schema validation with UUID
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
const createOrderSchema = z.object({
customerId: z.string().uuid(), // validates UUID v4 or v7 format
total: z.number().positive(),
});
app.post('/orders',
zValidator('json', createOrderSchema),
async (c) => {
const { customerId, total } = c.req.valid('json');
const order = { id: uuidv7(), customerId, total };
// ...
return c.json(order, 201);
}
);
Idempotency key handling
import { validate } from 'uuid';
app.post('/payments', async (c) => {
const idempotencyKey = c.req.header('idempotency-key');
if (!idempotencyKey || !validate(idempotencyKey)) {
return c.json({ error: 'Valid UUID Idempotency-Key header required' }, 400);
}
const cached = await c.env.KV.get(`idem:${idempotencyKey}`);
if (cached) {
return c.json(JSON.parse(cached), 200); // replay cached response
}
// ... process payment
const result = { paymentId: uuidv7(), status: 'success' };
await c.env.KV.put(`idem:${idempotencyKey}`, JSON.stringify(result), { expirationTtl: 86400 });
return c.json(result, 201);
});
Further reading
- UUID in Edge Functions — Cloudflare Workers, Vercel, Deno
- UUID in SQLite
- UUID as Idempotency Keys
- UUID v7 in Microservices — trace IDs
- UUID in JavaScript — full guide
External references
Frequently asked questions
How do I generate UUID v7 in Hono?
Hono runs on runtimes that provide crypto.getRandomValues() (Cloudflare Workers, Deno, Bun, Node.js 19+). Import the uuid npm package and use v7 as uuidv7. For Cloudflare Workers, Hono's bundler (esbuild) tree-shakes uuid to ~2KB. See UUID in Edge Functions.
Does Hono work with Cloudflare D1 and UUID v7?
Yes. Cloudflare D1 is SQLite-compatible. UUID v7 strings sort correctly in SQLite's lexicographic text comparison, so ORDER BY id on a TEXT UUID v7 column produces chronological order. See UUID in SQLite.
Can I use UUID v7 for Hono middleware trace IDs?
Yes. Add a middleware that generates a UUID v7 for each request, sets it in the context, and adds it as an X-Trace-Id response header. Because UUID v7 embeds a millisecond timestamp, log lines with the trace ID are inherently time-sortable. See UUID v7 in Microservices.