Nodejs Hono logo

Nodejs Hono

Community
j4flmao
nodejs-hono

Use this skill when building Hono applications — lightweight web framework, edge-ready, Zod validation, RPC client. This skill enforces: Hono app factory pattern, Zod validation middleware, RPC type-safe client, middleware composition, edge deployment readiness. Do NOT use for: Express.js apps, NestJS projects, or non-Hono frameworks.

Overview

Publisherj4flmao
Repositoryagent-skills
Skill namenodejs-hono
Stars
41
Forks
6
Bundled files
6
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 6 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by j4flmao on GitHub. Read the source before you install it.

Installation

Install the Nodejs Hono AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/nodejs/hono
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/nodejs/hono .claude/skills/nodejs-hono
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Nodejs Hono in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Nodejs Hono on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Nodejs Hono is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Node.js Hono

Purpose

Build Hono applications — lightweight, edge-ready web framework with Zod validation, RPC client, and cross-runtime (Node, Bun, Deno, Cloudflare Workers) support.

Agent Protocol

Trigger

User request includes: hono, hono app, hono middleware, hono rpc, hono zod, hono cloudflare, hono bun, ultralightweight, edge backend.

Input Context

  • Runtime (Node.js, Bun, Deno, Cloudflare Workers)
  • Hono version (4.x)
  • Validation (Zod, TypeBox)
  • Database (Drizzle, Prisma, D1)
  • Auth (JWT, session, OAuth)

Output Artifact

App setup, route patterns, middleware chain, RPC client config, validation setup.

Response Format

Produce artifact directly. No preamble, no postamble, no explanations.

Completion Criteria

  • Hono app created with correct runtime adapter
  • Routes with Zod validation middleware
  • RPC client configured for frontend type safety
  • Middleware pipeline ordered correctly
  • CORS and auth middleware registered

Max Response Length

4096 tokens

Architecture Decision Trees

Hono vs Express vs Fastify (for Node.js)

CriterionHonoExpressFastify
Performance~60k req/s~30k req/s~50k req/s
Bundle size~14KB~150KB~200KB
Edge supportCloudflare, Deno, Bun, LambdaNode onlyNode + AWS Lambda
RPC type safetyBuilt-in (hono/client)NoneNone
ValidationZod/TypeBox middlewareManualSchema-first
EcosystemSmall, growingLargestMedium

Decision: Edge deployment or ultra-light → Hono. Full ecosystem → Express. Performance + schema → Fastify.

Runtime Selection

RuntimeAdapterBest For
Node.js@hono/node-serverExisting Node ecosystem
Cloudflare Workershono (native)Edge compute, D1, KV
Bunhono (native)Fast startup, TypeScript native
Denohono (npm/JSR)Deno Deploy, permissions
Vercel@hono/vercelServerless, Next.js BFF
AWS Lambda@hono/aws-lambdaLambda + API Gateway

Workflow

Step 1: Project Bootstrap

typescript
// src/index.ts (Node.js)
import { serve } from '@hono/node-server';
import { createApp } from './app';

const app = createApp();
const port = parseInt(process.env.PORT || '3000');

serve({ fetch: app.fetch, port }, (info) => {
  console.log(`Server running on port ${info.port}`);
});

// src/app.ts
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { logger } from 'hono/logger';
import { secureHeaders } from 'hono/secure-headers';
import { userModule } from './modules/users';
import { errorHandler } from './middleware/error-handler';

export function createApp() {
  const app = new Hono();

  // Global middleware
  app.use('*', cors({ origin: process.env.CORS_ORIGIN }));
  app.use('*', logger());
  app.use('*', secureHeaders());
  app.use('*', errorHandler);

  // Routes
  app.route('/api/v1/users', userModule);

  // Health
  app.get('/health', (c) => c.json({ status: 'ok' }));

  return app;
}

Step 2: Module Routes with Zod Validation

typescript
// src/modules/users/index.ts
import { Hono } from 'hono';
import { z } from 'zod';
import { zValidator } from '@hono/zod-validator';
import * as userService from './service';

export const userModule = new Hono()
  .get('/', zValidator('query', z.object({
    page: z.coerce.number().optional().default(1),
    limit: z.coerce.number().optional().default(20),
  })), async (c) => {
    const { page, limit } = c.req.valid('query');
    const result = await userService.findAll(page, limit);
    return c.json(result);
  })
  .get('/:id', async (c) => {
    const id = c.req.param('id');
    const user = await userService.findById(id);
    if (!user) return c.json({ error: 'Not found' }, 404);
    return c.json({ data: user });
  })
  .post('/', zValidator('json', z.object({
    name: z.string().min(2),
    email: z.string().email(),
  })), async (c) => {
    const body = c.req.valid('json');
    const user = await userService.create(body);
    return c.json({ data: user }, 201);
  })
  .put('/:id', zValidator('json', z.object({
    name: z.string().min(2).optional(),
    email: z.string().email().optional(),
  })), async (c) => {
    const id = c.req.param('id');
    const body = c.req.valid('json');
    const user = await userService.update(id, body);
    return c.json({ data: user });
  })
  .delete('/:id', async (c) => {
    const id = c.req.param('id');
    await userService.delete(id);
    return c.body(null, 204);
  });

Step 3: Auth Middleware (JWT)

typescript
// src/middleware/auth.ts
import { Hono, Context, Next } from 'hono';
import { getCookie } from 'hono/cookie';
import { verify } from 'hono/jwt';
import { HTTPException } from 'hono/http-exception';

// Type augmentation for context
declare module 'hono' {
  interface ContextVariableMap {
    userId: string;
    userRole: string;
  }
}

export async function authMiddleware(c: Context, next: Next) {
  const authHeader = c.req.header('Authorization');
  const token = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : getCookie(c, 'token');

  if (!token) throw new HTTPException(401, { message: 'Unauthorized' });

  try {
    const payload = await verify(token, process.env.JWT_SECRET!);
    c.set('userId', payload.sub as string);
    c.set('userRole', payload.role as string);
    await next();
  } catch {
    throw new HTTPException(401, { message: 'Invalid token' });
  }
}

// Usage
app.use('/api/v1/admin/*', authMiddleware);
app.get('/api/v1/admin/users', authMiddleware, async (c) => {
  const userId = c.get('userId');
  return c.json({ userId });
});

Step 4: Error Handler

typescript
// src/middleware/error-handler.ts
import { Context, ErrorHandler } from 'hono';
import { HTTPException } from 'hono/http-exception';
import { ZodError } from 'zod';

export const errorHandler: ErrorHandler = (err: Error, c: Context) => {
  console.error(`[${c.req.method}] ${c.req.url}:`, err.message);

  if (err instanceof HTTPException) {
    return c.json({
      success: false,
      error: { code: err.status, message: err.message },
    }, err.status);
  }

  if (err instanceof ZodError) {
    return c.json({
      success: false,
      error: {
        code: 400,
        message: 'Validation Error',
        details: err.issues.map(i => ({ path: i.path.join('.'), message: i.message })),
      },
    }, 400);
  }

  return c.json({
    success: false,
    error: { code: 500, message: 'Internal Server Error' },
  }, 500);
};

Step 5: RPC Client

typescript
// src/client.ts (frontend or BFF)
import { hc } from 'hono/client';
import type { AppType } from '../server/app';

const client = hc<AppType>('http://localhost:3000');

// Type-safe API calls
async function getUsers() {
  const res = await client.api.v1.users.$get({
    query: { page: '1', limit: '10' },
  });
  if (res.ok) {
    const data = await res.json();
    return data;
  }
  throw new Error('Failed to fetch');
}

// Export for frontend usage
export { client };

// Server-side RPC export
// app.ts
export type AppType = typeof app;

Step 6: Static File Serving

typescript
import { serveStatic } from '@hono/node-server/serve-static';

// Production static file serving
app.use('/static/*', serveStatic({ root: './public' }));

// In development, use:
// import { serveStatic } from 'hono/serve-static'

Implementation Patterns

Pattern: Scoped Middleware Group

typescript
// Admin routes with auth + audit middleware
const admin = new Hono()
  .use('*', authMiddleware)
  .use('*', auditMiddleware)
  .get('/users', async (c) => {
    const users = await adminService.listUsers();
    return c.json(users);
  })
  .post('/config', async (c) => {
    const body = await c.req.json();
    await adminService.updateConfig(body);
    return c.json({ success: true });
  });

app.route('/api/admin', admin);

Pattern: Bearer Auth Helper

typescript
import { bearerAuth } from 'hono/bearer-auth';

const token = process.env.API_TOKEN!;
app.use('/api/admin/*', bearerAuth({ token }));

Production Considerations

Edge Deployment (Cloudflare Workers)

typescript
// src/worker.ts
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { etag } from 'hono/etag';

const app = new Hono();

app.use('*', etag());
app.use('*', cors());

// D1 database binding
app.get('/users', async (c) => {
  const db = c.env.DB as D1Database;
  const result = await db.prepare('SELECT * FROM users').all();
  return c.json(result.results);
});

export default app;

Performance

  • Hono's c.json() auto-sets Content-Type for JSON strings
  • Use c.newResponse() for custom headers and streaming
  • Streaming: c.stream() for SSE and large responses
  • Avoid await c.req.parseBody() in hot paths — use zValidator('form') instead

Anti-Patterns

Anti-PatternWhyFix
Missing validation middlewareManual parsing, security riskUse zValidator on every mutation route
RPC without exported typesClient has no type inferenceExport AppType from app entry point
Heavy sync initializationBlocks startup, hurts cold startLazy init or c.env bindings
c.req.json() + separate validationDuplicate parsingSingle zValidator('json', schema)
Direct c.env access (non-CF)Not portable between runtimesAbstract behind adapter/service

Security Considerations

  • Hono's secureHeaders() sets CSP, HSTS, X-Frame-Options, X-Content-Type-Options
  • Auth via bearerAuth or custom JWT middleware
  • Zod validation strips unknown properties (.strip() by default)
  • CORS with explicit origin — never * in production
  • CSRF protection via token in headers for cookie-based auth
  • Rate limiting at gateway/CDN for edge deployments

Testing Strategies

typescript
import { Hono } from 'hono';
import { test, describe, expect } from 'vitest';

const app = createApp();

test('POST /api/v1/users creates user', async () => {
  const res = await app.request('/api/v1/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'Test', email: 'test@test.com' }),
  });
  expect(res.status).toBe(201);
  const body = await res.json();
  expect(body.data.name).toBe('Test');
});

test('GET /api/v1/users/:id returns 404', async () => {
  const res = await app.request('/api/v1/users/nonexistent');
  expect(res.status).toBe(404);
});

Use app.request() for HTTP testing without a server — works in Node, Bun, Deno, Workers. Use vitest with happy-dom for edge runtime tests.

Rules

  • App factory pattern: createApp() returns Hono instance — testable without server.
  • Every mutation route uses zValidator for input validation.
  • Error handler registered globally via app.onError().
  • Auth middleware uses c.set() / c.get() for typed context variables.
  • RPC client uses hc<AppType> for full type inference.
  • Module routes created with new Hono() and app.route() on the main app.
  • Middleware registered with '*' pattern for global, or specific path prefix.
  • No app.use on individual route handlers — compose in module or use middleware function.

References

  • references/hono-custom-middleware.md — Custom Middleware
  • references/hono-deployment.md — Deployment Guide
  • references/hono-middleware.md — Middleware Reference
  • references/hono-rpc.md — RPC Client
  • references/hono-setup.md — Setup Guide
  • references/hono-testing.md — Testing Patterns

Handoff

Hand off to backend/nodejs/drizzle/SKILL.md for Drizzle ORM or backend/nodejs/patterns/SKILL.md for advanced Node patterns.

Implementation Patterns

Pattern: Hono Middleware Chain

typescript
import { Hono, MiddlewareHandler } from 'hono';
import { getCookie, setCookie } from 'hono/cookie';
import { cors } from 'hono/cors';
import { jwt } from 'hono/jwt';

const app = new Hono();

app.use('/*', cors());
app.use('/api/*', jwt({ secret: Bun.env.JWT_SECRET! }));

const logger: MiddlewareHandler = async (c, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${c.req.method} ${c.req.url} ${c.res.status} ${ms}ms`);
};

app.use('*', logger);

Pattern: Validation with Zod

typescript
import { z } from 'zod';
import { zValidator } from '@hono/zod-validator';

const userSchema = z.object({
  name: z.string().min(2).max(100),
  email: z.string().email(),
  age: z.number().int().positive().optional(),
});

app.post('/users', zValidator('json', userSchema), async (c) => {
  const data = c.req.valid('json');
  const user = await createUser(data);
  return c.json(user, 201);
});

// Query params validation
const querySchema = z.object({
  page: z.coerce.number().int().positive().default(1),
  limit: z.coerce.number().int().max(100).default(20),
});

app.get('/users', zValidator('query', querySchema), async (c) => {
  const { page, limit } = c.req.valid('query');
  const users = await listUsers(page, limit);
  return c.json(users);
});

Production Considerations

  • Runtime: Hono runs on Bun, Deno, Node.js. Bun preferred for cold start < 50ms.
  • Middleware order: security middleware first (CORS, auth, rate-limit). Logger last.
  • Error handling: global app.onError handler. Return structured error responses.
  • Body size limits: app.use('*', bodyLimit({ maxSize: 1024 * 1024 })).
  • Compression: hono/compress middleware for text responses.
  • Timeouts: hono/timeout for route groups. Stale request termination.
  • Rate limiting: hono/rate-limiter with in-memory or Redis storage.
  • Health checks: dedicated /health route. Light probe. No middleware.

Anti-Patterns

Anti-PatternWhy It HurtsFix
Heavy middleware on every routeUnnecessary compute on static assets.Apply middleware selectively. app.use('/api/*').
Catching all errors genericallyLost context. Hard to debug.Specific error handlers. Zod validation errors separate.
Routes without typingPotential parameter mismatch.c.req.param() typed via route template.
No request IDCan't trace across services.Add request ID middleware. Pass to downstream calls.
Mixing sync and async middlewareMissed error handling.All middleware either sync or async. Be consistent.

Performance Optimization

  • Hono is already sub-1ms overhead. Avoid wrapping in unnecessary abstractions.
  • Use c.json() and c.text() directly. Avoid Express-style res.send() wrappers.
  • Static files: serve via CDN or Bun's Bun.file(). Not through Hono in production.
  • Streaming: c.stream() for large responses. No buffering in memory.
  • c.notFound() returns early. Avoid middleware chain for unmatched routes.
  • Route grouping with app.route('/api', api) for logical separation.
  • JWT validation: cache public key. Verify only on mutating endpoints.
  • Edge deployment: Hono on Cloudflare Workers. Minify bundle under 1MB.

Security Considerations

  • JWT: hono/jwt middleware. Short expiry. Validate audience and issuer.
  • CORS: hono/cors with specific origin. No Access-Control-Allow-Origin: * in prod.
  • CSRF: double-submit cookie pattern for cookie-based auth.
  • Rate limiting: per-IP token bucket. Stricter limits for auth endpoints.
  • Input validation: Zod on all input sources (json, query, param, form).
  • Headers: hono/secure-headers for CSP, HSTS, X-Frame-Options, X-Content-Type-Options.
  • Sensitive data: never log request/response bodies. Mask in structured logs.

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Nodejs Hono AI skill do?

Use this skill when building Hono applications — lightweight web framework, edge-ready, Zod validation, RPC client. This skill enforces: Hono app factory pattern, Zod validation middleware, RPC type-safe client, middleware composition, edge deployment readiness. Do NOT use for: Express.js apps, NestJS projects, or non-Hono frameworks.

Why use Nodejs Hono on TypingMind?

Because you install it once and use it with any model. Nodejs Hono is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Nodejs Hono in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/j4flmao/agent-skills/tree/main/skills/backend/nodejs/hono. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Nodejs Hono?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Nodejs Hono?

As many as you like. As long as a model supports skills, you can use Nodejs Hono with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Nodejs Hono AI skill free?

Yes. It is published on GitHub by j4flmao under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇