Build lightning-fast edge APIs with Hono and Google Antigravity IDE
# Hono Edge API Patterns for Google Antigravity IDE
Create blazing-fast edge APIs with Hono using Google Antigravity IDE's Gemini 3 assistance. This guide covers routing patterns, middleware composition, type-safe validators, and multi-runtime deployment for Cloudflare Workers, Deno, and Bun.
## Core API Setup
```typescript
// src/index.ts
import { Hono } from "hono";
import { cors } from "hono/cors";
import { logger } from "hono/logger";
import { secureHeaders } from "hono/secure-headers";
import { timing } from "hono/timing";
import { prettyJSON } from "hono/pretty-json";
import { validator } from "hono/validator";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
// Type-safe environment bindings
type Bindings = {
DATABASE_URL: string;
JWT_SECRET: string;
KV: KVNamespace;
R2: R2Bucket;
};
type Variables = {
user: { id: string; email: string; role: string };
requestId: string;
};
const app = new Hono<{ Bindings: Bindings; Variables: Variables }>();
// Global middleware stack
app.use("*", timing());
app.use("*", logger());
app.use("*", secureHeaders());
app.use("*", prettyJSON());
app.use("*", cors({
origin: ["https://example.com"],
credentials: true,
}));
// Request ID middleware
app.use("*", async (c, next) => {
c.set("requestId", crypto.randomUUID());
c.header("X-Request-Id", c.get("requestId"));
await next();
});
// Schema definitions
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 });
// Routes with validation
app.post(
"/api/users",
zValidator("json", CreateUserSchema),
async (c) => {
const data = c.req.valid("json");
const db = createDbClient(c.env.DATABASE_URL);
const user = await db.user.create({
data: {
...data,
password: await hashPassword(data.password),
},
});
return c.json({ user: omit(user, ["password"]) }, 201);
}
);
app.get("/api/users/:id", async (c) => {
const id = c.req.param("id");
const cached = await c.env.KV.get(`user:${id}`, "json");
if (cached) {
return c.json({ user: cached, cached: true });
}
const db = createDbClient(c.env.DATABASE_URL);
const user = await db.user.findUnique({ where: { id } });
if (!user) {
return c.json({ error: "User not found" }, 404);
}
// Cache for 5 minutes
await c.env.KV.put(`user:${id}`, JSON.stringify(user), {
expirationTtl: 300,
});
return c.json({ user });
});
```
## Modular Route Groups
```typescript
// src/routes/auth.ts
import { Hono } from "hono";
import { jwt } from "hono/jwt";
import { setCookie, getCookie } from "hono/cookie";
const auth = new Hono<{ Bindings: Bindings; Variables: Variables }>();
// Public routes
auth.post("/login", zValidator("json", LoginSchema), async (c) => {
const { email, password } = c.req.valid("json");
const db = createDbClient(c.env.DATABASE_URL);
const user = await db.user.findUnique({ where: { email } });
if (!user || !await verifyPassword(password, user.password)) {
return c.json({ error: "Invalid credentials" }, 401);
}
const token = await createJWT(
{ sub: user.id, email: user.email, role: user.role },
c.env.JWT_SECRET
);
setCookie(c, "token", token, {
httpOnly: true,
secure: true,
sameSite: "Strict",
maxAge: 60 * 60 * 24 * 7, // 1 week
});
return c.json({ user: omit(user, ["password"]) });
});
// Protected routes
auth.use("/me", jwt({ secret: (c) => c.env.JWT_SECRET }));
auth.get("/me", async (c) => {
const payload = c.get("jwtPayload");
return c.json({ user: payload });
});
export default auth;
```
## Error Handling
```typescript
// src/middleware/error-handler.ts
import { HTTPException } from "hono/http-exception";
app.onError((err, c) => {
const requestId = c.get("requestId");
if (err instanceof HTTPException) {
return c.json({
error: err.message,
requestId,
}, err.status);
}
console.error(`[${requestId}] Unhandled error:`, err);
return c.json({
error: "Internal server error",
requestId,
}, 500);
});
app.notFound((c) => {
return c.json({ error: "Not found" }, 404);
});
```
## Best Practices for Google Antigravity IDE
When building Hono APIs with Google Antigravity, use type-safe bindings for environment variables. Leverage Zod validators for request validation. Implement caching with KV or R2 storage. Use route groups for modular organization. Add timing middleware for performance monitoring. Let Gemini 3 generate OpenAPI specs from your Hono routes.
Google Antigravity excels at scaffolding complete Hono APIs with proper middleware chains and error handling.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.