Build ultra-fast edge applications with Hono on Cloudflare Workers in Google Antigravity
# Hono Edge Framework for Google Antigravity
Hono is a lightweight web framework optimized for edge runtimes. This guide covers patterns for Google Antigravity IDE and Gemini 3.
## Basic Application Setup
```typescript
// src/index.ts
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { prettyJSON } from 'hono/pretty-json';
import { secureHeaders } from 'hono/secure-headers';
import { jwt } from 'hono/jwt';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
type Bindings = {
DB: D1Database;
KV: KVNamespace;
JWT_SECRET: string;
};
const app = new Hono<{ Bindings: Bindings }>();
// Global middleware
app.use('*', logger());
app.use('*', secureHeaders());
app.use('*', prettyJSON());
app.use('/api/*', cors({ origin: ['https://example.com'], credentials: true }));
// Health check
app.get('/health', (c) => c.json({ status: 'ok', timestamp: Date.now() }));
// Protected routes
app.use('/api/protected/*', jwt({ secret: (c) => c.env.JWT_SECRET }));
export default app;
```
## Route Groups with Validation
```typescript
// src/routes/users.ts
import { Hono } from 'hono';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
const createUserSchema = z.object({
email: z.string().email(),
name: z.string().min(2).max(100),
password: z.string().min(8),
});
const updateUserSchema = createUserSchema.partial().omit({ password: true });
const users = new Hono<{ Bindings: Bindings }>();
users.get('/', async (c) => {
const { results } = await c.env.DB.prepare('SELECT id, email, name, created_at FROM users').all();
return c.json(results);
});
users.get('/:id', async (c) => {
const id = c.req.param('id');
const user = await c.env.DB.prepare('SELECT id, email, name, created_at FROM users WHERE id = ?').bind(id).first();
if (!user) return c.json({ error: 'User not found' }, 404);
return c.json(user);
});
users.post('/', zValidator('json', createUserSchema), async (c) => {
const data = c.req.valid('json');
const id = crypto.randomUUID();
const hashedPassword = await hashPassword(data.password);
await c.env.DB.prepare('INSERT INTO users (id, email, name, password) VALUES (?, ?, ?, ?)')
.bind(id, data.email, data.name, hashedPassword).run();
return c.json({ id, email: data.email, name: data.name }, 201);
});
users.put('/:id', zValidator('json', updateUserSchema), async (c) => {
const id = c.req.param('id');
const data = c.req.valid('json');
const sets = Object.entries(data).map(([k]) => `${k} = ?`).join(', ');
await c.env.DB.prepare(`UPDATE users SET ${sets} WHERE id = ?`)
.bind(...Object.values(data), id).run();
return c.json({ id, ...data });
});
users.delete('/:id', async (c) => {
const id = c.req.param('id');
await c.env.DB.prepare('DELETE FROM users WHERE id = ?').bind(id).run();
return c.body(null, 204);
});
export default users;
```
## Authentication Middleware
```typescript
// src/middleware/auth.ts
import { Context, Next } from 'hono';
import { sign, verify } from 'hono/jwt';
export const authMiddleware = async (c: Context, next: Next) => {
const token = c.req.header('Authorization')?.replace('Bearer ', '');
if (!token) return c.json({ error: 'Unauthorized' }, 401);
try {
const payload = await verify(token, c.env.JWT_SECRET);
c.set('user', payload);
await next();
} catch {
return c.json({ error: 'Invalid token' }, 401);
}
};
export const generateToken = async (user: { id: string; email: string }, secret: string) => {
return sign({ sub: user.id, email: user.email, exp: Math.floor(Date.now() / 1000) + 3600 }, secret);
};
```
## KV Caching
```typescript
// src/utils/cache.ts
export async function cached<T>(kv: KVNamespace, key: string, fetcher: () => Promise<T>, ttl = 3600): Promise<T> {
const cached = await kv.get(key, 'json');
if (cached) return cached as T;
const fresh = await fetcher();
await kv.put(key, JSON.stringify(fresh), { expirationTtl: ttl });
return fresh;
}
// Usage in route
app.get('/api/products/:id', async (c) => {
const id = c.req.param('id');
const product = await cached(c.env.KV, `product:${id}`, async () => {
return c.env.DB.prepare('SELECT * FROM products WHERE id = ?').bind(id).first();
});
if (!product) return c.json({ error: 'Not found' }, 404);
return c.json(product);
});
```
## Best Practices
1. **Type Safety**: Use Bindings type for environment
2. **Validation**: Zod validators for all inputs
3. **Caching**: Leverage KV for edge caching
4. **D1 Database**: Use D1 for SQLite at edge
5. **Middleware**: Compose reusable middleware
6. **Error Handling**: Consistent error responses
Google Antigravity's Gemini 3 understands Hono patterns and generates edge-optimized code.This Hono prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their hono implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For Hono projects, consider mentioning your framework version, coding style, and any specific libraries you're using.