Frameworks Integration
Use when asking about "Hono", "itty-router", "routing frameworks", "middleware", "API framework", "web framework for Workers", "request routing", "Express-like", or choosing between web frameworks for Cloudflare Workers.
What this skill does
# Web Frameworks for Workers
## Purpose
This skill provides guidance on web frameworks for Cloudflare Workers, with focus on Hono and itty-router—the two most popular choices. Use this when building API endpoints, adding middleware, or choosing between vanilla fetch handlers and framework-based routing.
## When to Use a Framework
**Use a framework when**:
- Multiple routes/endpoints (>3-4)
- Need middleware (auth, logging, CORS)
- Building a REST API
- Want type-safe routing
- Team is familiar with Express-like patterns
**Stay vanilla when**:
- Single endpoint or simple proxy
- Maximum performance critical
- Minimal dependencies desired
- Learning Workers fundamentals
## Framework Comparison
| Feature | Hono | itty-router | Vanilla |
|---------|------|-------------|---------|
| **Bundle size** | ~14KB | ~1KB | 0KB |
| **Type safety** | Excellent | Good | Manual |
| **Middleware** | Built-in system | Basic | Manual |
| **Learning curve** | Medium | Low | Low |
| **Documentation** | Extensive | Moderate | N/A |
| **Active development** | Very active | Active | N/A |
| **Best for** | Full APIs | Simple routing | Single endpoint |
## Hono
### Why Hono
- Express-like API, easy to learn
- Excellent TypeScript support
- Rich middleware ecosystem
- Built for edge runtimes
- Active community and development
### Basic Setup
```typescript
import { Hono } from 'hono';
type Bindings = {
DATABASE: D1Database;
AI: Ai;
CACHE: KVNamespace;
};
const app = new Hono<{ Bindings: Bindings }>();
// Routes
app.get('/', (c) => c.text('Hello from Hono!'));
app.get('/api/users', async (c) => {
const users = await c.env.DATABASE
.prepare('SELECT * FROM users')
.all();
return c.json(users.results);
});
app.post('/api/users', async (c) => {
const body = await c.req.json();
// Validate and create user
return c.json({ id: '123', ...body }, 201);
});
export default app;
```
### Middleware
```typescript
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { bearerAuth } from 'hono/bearer-auth';
const app = new Hono<{ Bindings: Bindings }>();
// Global middleware
app.use('*', logger());
app.use('*', cors({
origin: ['https://example.com'],
allowMethods: ['GET', 'POST', 'PUT', 'DELETE'],
}));
// Route-specific middleware
app.use('/api/*', bearerAuth({ token: 'secret' }));
// Or custom middleware
app.use('/api/*', async (c, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
c.header('X-Response-Time', `${ms}ms`);
});
```
### Route Groups
```typescript
const app = new Hono<{ Bindings: Bindings }>();
// API routes
const api = new Hono<{ Bindings: Bindings }>();
api.get('/users', usersHandler);
api.get('/users/:id', userByIdHandler);
api.post('/users', createUserHandler);
// Mount the group
app.route('/api', api);
// Or inline grouping
app.route('/api/v2', new Hono()
.get('/health', (c) => c.json({ status: 'ok' }))
.get('/version', (c) => c.json({ version: '2.0' }))
);
```
### Error Handling
```typescript
import { HTTPException } from 'hono/http-exception';
app.onError((err, c) => {
if (err instanceof HTTPException) {
return c.json({ error: err.message }, err.status);
}
console.error('Unhandled error:', err);
return c.json({ error: 'Internal server error' }, 500);
});
// Throwing HTTP exceptions
app.get('/api/users/:id', async (c) => {
const id = c.req.param('id');
const user = await getUser(id);
if (!user) {
throw new HTTPException(404, { message: 'User not found' });
}
return c.json(user);
});
```
### With Workers AI
```typescript
app.post('/api/chat', async (c) => {
const { message } = await c.req.json();
const response = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: message }
]
});
return c.json({ response: response.response });
});
// Streaming response
app.post('/api/chat/stream', async (c) => {
const { message } = await c.req.json();
const stream = await c.env.AI.run('@cf/meta/llama-3.1-8b-instruct', {
messages: [{ role: 'user', content: message }],
stream: true
});
return new Response(stream, {
headers: { 'Content-Type': 'text/event-stream' }
});
});
```
### Validation with Zod
```typescript
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
const createUserSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
age: z.number().positive().optional(),
});
app.post('/api/users',
zValidator('json', createUserSchema),
async (c) => {
const user = c.req.valid('json');
// user is typed and validated
return c.json({ id: '123', ...user }, 201);
}
);
```
## itty-router
### Why itty-router
- Extremely lightweight (~1KB)
- Dead simple API
- No build step required
- Good for simple APIs
- Easy to understand source code
### Basic Setup
```typescript
import { Router } from 'itty-router';
interface Env {
DATABASE: D1Database;
}
const router = Router();
router.get('/', () => new Response('Hello!'));
router.get('/api/users', async (request, env: Env) => {
const users = await env.DATABASE
.prepare('SELECT * FROM users')
.all();
return Response.json(users.results);
});
router.post('/api/users', async (request, env: Env) => {
const body = await request.json();
// Create user
return Response.json({ id: '123', ...body }, { status: 201 });
});
// 404 fallback
router.all('*', () => new Response('Not Found', { status: 404 }));
export default {
fetch: (request: Request, env: Env, ctx: ExecutionContext) =>
router.handle(request, env, ctx)
};
```
### With Middleware Pattern
```typescript
import { Router } from 'itty-router';
const router = Router();
// Simple auth middleware
const withAuth = async (request: Request, env: Env) => {
const token = request.headers.get('Authorization')?.replace('Bearer ', '');
if (!token || token !== env.API_KEY) {
return new Response('Unauthorized', { status: 401 });
}
// Don't return anything to continue to next handler
};
// Apply middleware to routes
router.get('/api/*', withAuth);
router.get('/api/data', (request, env) => Response.json({ data: 'secret' }));
```
### Route Parameters
```typescript
router.get('/api/users/:id', async (request, env) => {
const { id } = request.params;
const user = await env.DATABASE
.prepare('SELECT * FROM users WHERE id = ?')
.bind(id)
.first();
if (!user) {
return new Response('Not Found', { status: 404 });
}
return Response.json(user);
});
// Optional parameters
router.get('/api/posts/:id?', (request) => {
const { id } = request.params;
if (id) {
return Response.json({ post: id });
}
return Response.json({ posts: [] });
});
```
## Choosing Between Them
### Choose Hono When
- Building a substantial API (>10 endpoints)
- Need built-in middleware (CORS, auth, validation)
- Want excellent TypeScript integration
- Team comes from Express/Fastify background
- Building something that will grow
### Choose itty-router When
- Simple API with few endpoints
- Bundle size is critical
- Want minimal abstraction
- Quick prototype or proof of concept
- Learning Workers fundamentals
### Choose Vanilla When
- Single-purpose Worker (proxy, redirect, etc.)
- Maximum control needed
- Zero dependencies required
- Edge case the frameworks don't handle well
## Vanilla Fetch Handler Pattern
For comparison, here's the vanilla approach:
```typescript
interface Env {
DATABASE: D1Database;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
const path = url.pathname;
const method = request.method;
// Manual routing
if (path === '/' && method === 'GET') {
return new Response('Hello!');
}
if (path === '/api/users' && method === 'GET') {
const users =Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.