Package Exports
- hono-swagger-ui
- hono-swagger-ui/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (hono-swagger-ui) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Hono Swagger UI 📚
Automatic Swagger/OpenAPI documentation middleware for Hono applications. Generate beautiful, interactive API documentation without changing your existing code!
✨ Features
- 🚀 Zero Configuration - Works out of the box with your existing Hono routes
- 📖 Auto-Documentation - Automatically detects and documents your API routes
- 🎨 Beautiful UI - Integrates Swagger UI for interactive documentation
- 🔍 Zod Integration - Full support for
@hono/zod-validatorschemas - 🏷️ Custom Tags - Organize your endpoints with custom tags and descriptions
- 🔧 Flexible Configuration - Customize everything from route paths to API info
- 📱 Mobile Friendly - Responsive documentation that works on all devices
- 🎯 TypeScript - Full TypeScript support with type safety
🚀 Quick Start
Installation
npm install hono-swagger-ui
# or
yarn add hono-swagger-ui
# or
pnpm add hono-swagger-uiBasic Usage
import { Hono } from 'hono';
import { swagger } from 'hono-swagger-ui';
const app = new Hono();
// Initialize swagger
const swaggerUI = swagger(app, {
title: 'My API',
version: '1.0.0'
});
// Apply middleware
app.use('*', swaggerUI.init());
// Your existing routes work automatically!
app.get('/users/:id', (c) => {
return c.json({ id: c.req.param('id'), name: 'John' });
});
export default app;That's it! Visit /swagger-ui to see your interactive documentation.
📖 Documentation
Configuration Options
interface SwaggerOptions {
title?: string; // API title (default: 'API Documentation')
version?: string; // API version (default: '1.0.0')
description?: string; // API description
route?: string; // Swagger UI route (default: '/swagger-ui')
excludePaths?: string[]; // Paths to exclude from documentation
info?: {
title?: string;
version?: string;
description?: string;
contact?: {
name?: string;
email?: string;
url?: string;
};
license?: {
name?: string;
url?: string;
};
};
}Advanced Usage
import { Hono } from 'hono';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
import { swagger } from 'hono-swagger-ui';
const app = new Hono();
const swaggerUI = swagger(app, {
title: 'My Advanced API',
version: '2.0.0',
description: 'A comprehensive API with full documentation',
route: '/docs', // Custom route
excludePaths: ['/internal', '/health'], // Exclude internal routes
info: {
contact: {
name: 'API Support',
email: 'support@example.com',
url: 'https://example.com/support'
},
license: {
name: 'MIT',
url: 'https://opensource.org/licenses/MIT'
}
}
});
app.use('*', swaggerUI.init());
// Enhanced route documentation
const UserSchema = z.object({
id: z.string(),
name: z.string().min(1).max(100),
email: z.string().email(),
age: z.number().int().min(0).max(120).optional()
});
app.get('/api/users/:id',
zValidator('param', z.object({ id: z.string() })),
swaggerUI.documentRoute({
tags: ['Users'],
summary: 'Get user by ID',
description: 'Retrieve a single user by their unique identifier'
}),
(c) => {
const { id } = c.req.valid('param');
return c.json({ id, name: 'John Doe', email: 'john@example.com' });
}
);
app.post('/api/users',
zValidator('json', UserSchema.omit({ id: true })),
swaggerUI.documentRoute({
tags: ['Users'],
summary: 'Create user',
description: 'Create a new user with the provided data'
}),
async (c) => {
const userData = c.req.valid('json');
return c.json({ id: '123', ...userData }, 201);
}
);Manual Route Documentation
You can also manually add routes to documentation:
swaggerUI.addRoute({
method: 'get',
path: '/api/custom/{id}',
parameters: [
{
name: 'id',
in: 'path',
required: true,
schema: { type: 'string' }
}
],
responses: {
'200': {
description: 'Success',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
id: { type: 'string' },
data: { type: 'object' }
}
}
}
}
}
},
tags: ['Custom'],
summary: 'Custom endpoint'
});🔧 Integration Examples
With Bun
import { Hono } from 'hono';
import { swagger } from 'hono-swagger-ui';
const app = new Hono();
const swaggerUI = swagger(app);
app.use('*', swaggerUI.init());
// Your routes...
export default {
port: 3000,
fetch: app.fetch,
};With Node.js
import { Hono } from 'hono';
import { serve } from '@hono/node-server';
import { swagger } from 'hono-swagger-ui';
const app = new Hono();
const swaggerUI = swagger(app);
app.use('*', swaggerUI.init());
// Your routes...
const port = 3000;
console.log(`Server running at http://localhost:${port}/swagger-ui`);
serve({
fetch: app.fetch,
port
});With Cloudflare Workers
import { Hono } from 'hono';
import { swagger } from 'hono-swagger-ui';
const app = new Hono();
const swaggerUI = swagger(app);
app.use('*', swaggerUI.init());
// Your routes...
export default app;🎯 Zod Integration
The middleware automatically detects and converts Zod schemas to OpenAPI specifications:
import { z } from 'zod';
const CreateUserSchema = z.object({
name: z.string().min(1, 'Name is required'),
email: z.string().email('Invalid email format'),
age: z.number().int().min(18, 'Must be 18 or older').optional(),
role: z.enum(['user', 'admin']).default('user')
});
app.post('/users',
zValidator('json', CreateUserSchema),
(c) => {
const user = c.req.valid('json');
return c.json({ id: '123', ...user });
}
);This automatically generates proper OpenAPI schema with:
- Required fields
- Type validation
- Format validation (email, etc.)
- Min/max constraints
- Enum values
- Default values
🛠️ Development
# Clone the repository
git clone https://github.com/yourusername/hono-swagger-ui.git
cd hono-swagger-ui
# Install dependencies
npm install
# Build the package
npm run build
# Run tests
npm test
# Run example
cd example
npm install
npm run dev🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
Development Guidelines
- Fork the repository
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Make your changes
- Add tests for your changes
- Ensure all tests pass (
npm test) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Hono - The ultrafast web framework
- Swagger UI - Interactive API documentation
- Zod - TypeScript-first schema validation
⚡ Performance
This middleware is designed to be lightweight and performant:
- Routes are analyzed on-demand
- OpenAPI spec is cached and generated once
- Swagger UI assets are loaded from CDN
- Minimal runtime overhead
🔒 Security
- No sensitive information is exposed in documentation
- Configurable path exclusions for internal routes
- CORS headers properly handled
- No eval() or unsafe operations
📊 Roadmap
- Enhanced Zod schema conversion
- JSDoc comment parsing
- Custom theme support
- Authentication documentation
- Response example generation
- Postman collection export
- Multiple API version support
Made with ❤️ for the Hono community