@bytedocs/hono
v1.0.1
Published
Alternative to Swagger with better design, auto-detection, and AI integration
Downloads
14
Maintainers
Readme
ByteDocs for Hono
ByteDocs is a modern alternative to Swagger with better design, auto-detection, and AI integration for Hono applications. It automatically generates beautiful API documentation from your routes with zero configuration required.
Features
- 🚀 Auto Route Detection - Automatically discovers routes, parameters, and data structures from your Hono app
- 🎨 Beautiful Modern UI - Clean, responsive interface with dark mode support
- 🤖 AI Integration - Built-in AI assistant (OpenAI, Gemini, Claude, OpenRouter) to help users understand your API
- 📱 Mobile Responsive - Works perfectly on all device sizes
- 🔍 Interactive Testing - Try out endpoints directly from the documentation
- 📊 OpenAPI Compatible - Exports standard OpenAPI 3.0.3 specification in JSON and YAML formats
- 🔐 Built-in Authentication - Support for Basic Auth, API Key, Bearer Token, and Session authentication
- ⚡ Zero Configuration - Works out of the box with sensible defaults
- 🌍 Environment Config - Full
.envfile support with validation - 📝 JSDoc Support - Extracts documentation from JSDoc comments
Quick Start
1. Install ByteDocs
npm install @bytedocs/hono2. Add One Line to Your Code
import { Hono } from 'hono';
import { setupByteDocs } from '@bytedocs/hono';
const app = new Hono();
// Your API routes
app.get('/api/users', (c) => {
return c.json({ users: [] });
});
app.post('/api/users', async (c) => {
const body = await c.req.json();
return c.json({ id: 1, ...body }, 201);
});
// Setup ByteDocs - that's it!
setupByteDocs(app, {
title: 'My API',
version: '1.0.0',
description: 'Auto-generated API documentation',
docsPath: '/docs',
autoDetect: true,
});
export default app;3. Visit Your Documentation
Open http://localhost:3000/docs and enjoy your auto-generated API documentation!
API Endpoints
Once installed, ByteDocs provides these endpoints:
GET /docs- Main documentation interface with beautiful UIGET /docs/api-data.json- Raw documentation dataGET /docs/openapi.json- OpenAPI 3.0.3 specification (JSON format)GET /docs/openapi.yaml- OpenAPI 3.0.3 specification (YAML format)POST /docs/chat- AI chat endpoint (if AI is enabled)GET /docs/login- Login page (if session auth enabled)POST /docs/login- Login handler (if session auth enabled)POST /docs/logout- Logout handler (if session auth enabled)
Configuration
Basic Configuration
setupByteDocs(app, {
title: 'My API Documentation',
version: '1.0.0',
description: 'Comprehensive API for my application',
docsPath: '/docs',
autoDetect: true,
baseURLs: [
{ name: 'Production', url: 'https://api.myapp.com' },
{ name: 'Staging', url: 'https://staging-api.myapp.com' },
{ name: 'Local', url: 'http://localhost:3000' },
],
});AI Integration
Enable AI assistance for your API documentation:
setupByteDocs(app, {
title: 'My API',
version: '1.0.0',
aiConfig: {
enabled: true,
provider: 'openai', // openai, gemini, claude, openrouter
apiKey: process.env.OPENAI_API_KEY,
features: {
chatEnabled: true,
docGenerationEnabled: false,
model: 'gpt-4o-mini',
maxTokens: 1000,
temperature: 0.7,
},
},
});Supported AI Providers:
OpenAI
aiConfig: {
enabled: true,
provider: 'openai',
apiKey: process.env.OPENAI_API_KEY,
features: {
model: 'gpt-4o-mini', // or gpt-4, gpt-3.5-turbo
},
}Google Gemini
aiConfig: {
enabled: true,
provider: 'gemini',
apiKey: process.env.GEMINI_API_KEY,
features: {
model: 'gemini-1.5-flash', // or gemini-1.5-pro
},
}Anthropic Claude
aiConfig: {
enabled: true,
provider: 'claude',
apiKey: process.env.ANTHROPIC_API_KEY,
features: {
model: 'claude-3-sonnet-20240229',
},
}OpenRouter
aiConfig: {
enabled: true,
provider: 'openrouter',
apiKey: process.env.OPENROUTER_API_KEY,
features: {
model: 'openai/gpt-4o-mini', // Any OpenRouter model
},
}Authentication
Protect your documentation with built-in authentication:
setupByteDocs(app, {
title: 'My API',
version: '1.0.0',
authConfig: {
enabled: true,
type: 'session', // basic, api_key, bearer, session
password: 'your-secret-password',
// Session-specific settings
sessionExpire: 1440, // minutes
ipBanEnabled: true,
ipBanMaxAttempts: 5,
ipBanDuration: 60, // minutes
adminWhitelistIPs: ['127.0.0.1', '::1'],
},
});Authentication Types:
basic- HTTP Basic Authenticationapi_key- API Key authentication via custom headerbearer- Bearer token authenticationsession- Session-based authentication with login page
Environment Configuration
Create a .env file for easy configuration:
# Basic Settings
BYTEDOCS_TITLE="My API Documentation"
BYTEDOCS_VERSION="1.0.0"
BYTEDOCS_DESCRIPTION="Comprehensive API for my application"
BYTEDOCS_DOCS_PATH="/docs"
BYTEDOCS_AUTO_DETECT=true
# Multiple Environment URLs
BYTEDOCS_PRODUCTION_URL="https://api.myapp.com"
BYTEDOCS_STAGING_URL="https://staging-api.myapp.com"
BYTEDOCS_LOCAL_URL="http://localhost:3000"
# Authentication
BYTEDOCS_AUTH_ENABLED=true
BYTEDOCS_AUTH_TYPE=session
BYTEDOCS_AUTH_PASSWORD=your-secret-password
BYTEDOCS_AUTH_SESSION_EXPIRE=1440
BYTEDOCS_AUTH_IP_BAN_ENABLED=true
BYTEDOCS_AUTH_IP_BAN_MAX_ATTEMPTS=5
BYTEDOCS_AUTH_IP_BAN_DURATION=60
BYTEDOCS_AUTH_ADMIN_WHITELIST_IPS=127.0.0.1,::1
# AI Configuration
BYTEDOCS_AI_ENABLED=true
BYTEDOCS_AI_PROVIDER=openai
BYTEDOCS_AI_API_KEY=sk-your-openai-key
BYTEDOCS_AI_MODEL=gpt-4o-mini
BYTEDOCS_AI_MAX_TOKENS=1000
BYTEDOCS_AI_TEMPERATURE=0.7Then load it in your code:
import { loadConfigFromEnv, validateConfig } from '@bytedocs/hono';
const config = loadConfigFromEnv();
// Validate configuration
const validation = validateConfig(config);
if (!validation.valid) {
console.error('Configuration errors:', validation.errors);
process.exit(1);
}
setupByteDocs(app, config);JSDoc Annotations
Enhance your documentation with JSDoc comments:
/**
* Get user by ID
* @summary Retrieve a specific user
* @tag Users
* @param id path string true "User ID to retrieve"
* @response 200 {object} User "User object"
* @response 404 {object} Error "User not found"
*/
app.get('/api/users/:id', (c) => {
const id = c.req.param('id');
const user = getUserById(id);
if (user) {
return c.json(user);
} else {
return c.json({ error: 'User not found' }, 404);
}
});
/**
* Create a new user
* @summary Create user
* @tag Users
* @description Creates a new user with the provided information
* @response 201 {object} User "Created user"
*/
app.post('/api/users', async (c) => {
const body = await c.req.json();
const user = createUser(body);
return c.json(user, 201);
});Advanced Usage
Manual Route Registration
import { ByteDocs } from '@bytedocs/hono';
const docs = new ByteDocs({
title: 'My API',
version: '1.0.0',
});
// Manually add route information
docs.addRoute({
method: 'GET',
path: '/api/custom-endpoint',
summary: 'Custom endpoint',
description: 'This is a manually registered endpoint',
parameters: [
{
name: 'id',
in: 'path',
schema: { type: 'integer' },
required: true,
description: 'Record ID',
},
],
handler: () => {},
});
// Generate documentation
docs.generate();Export OpenAPI Specifications
// Get OpenAPI JSON
const openAPIJSON = docs.getOpenAPISpec();
// Get OpenAPI YAML
import * as yaml from 'js-yaml';
const openAPIYAML = yaml.dump(openAPIJSON);
// Save to file
import { writeFileSync } from 'fs';
writeFileSync('openapi.yaml', openAPIYAML);Hono-Specific Features
ByteDocs for Hono leverages Hono's features:
Built-in Cookie Support
Hono has built-in cookie utilities, so no additional middleware is needed.
Context-Based Responses
Uses Hono's Context API for consistent response handling:
return c.json({ data }, 200);
return c.text('Hello', 200);
return c.html('<h1>Hello</h1>');Request Body Parsing
Hono automatically detects request body type:
const body = await c.req.json(); // JSON
const formData = await c.req.formData(); // Form data
const text = await c.req.text(); // Plain textRequirements
- Node.js 16 or higher
- Hono 3.x or 4.x
Development
Build from Source
# Clone the repository
git clone https://github.com/aibnuhibban/bytedocs-node.git
cd bytedocs-node/hono
# Install dependencies
npm install
# Build the package
npm run build
# Run example
npm run example
# Visit http://localhost:3000/docsDevelopment Mode
# Start development server with hot reload
npm run devExamples
Check out the examples/ directory for complete implementations:
- Basic:
examples/basic/- Simple setup with auto-detection - More examples coming soon!
Contributing
We welcome contributions! Please see CONTRIBUTING.md for guidelines.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
Credits
- Inspired by Scramble for Laravel
- Part of the ByteDocs project
- Built specifically for the Hono web framework
Made with ❤️ for the Hono community
