nextjs-auto-swagger-gen
v1.0.1
Published
Zero-config, code-first API documentation generator for Next.js and Node.js
Downloads
198
Maintainers
Readme
nextjs-auto-swagger-gen
Zero-config, code-first API documentation generator for Next.js and Node.js
Write APIs normally. Docs generate themselves.
- ❌ NO manual Swagger files
- ❌ NO decorators everywhere
- ❌ NO YAML/JSON configs
- ❌ NO schema duplication
- ✅ Code is the source of truth
- ✅ TypeScript-first
- ✅ Zero or near-zero config
Installation
# Using npm
npm install nextjs-auto-swagger-gen
# Using yarn
yarn add nextjs-auto-swagger-gen
# Using pnpm
pnpm add nextjs-auto-swagger-genQuick Start
Option 1: CLI (Recommended for production builds)
# Initialize config (optional)
npx auto-swagger init
# Generate documentation
npx auto-swagger generate
# Start documentation server
npx auto-swagger serveOption 2: Runtime (Development mode)
// app/api-docs/route.ts
import { createDocsHandler } from 'nextjs-auto-swagger-gen';
export const { GET } = createDocsHandler();That's it! Visit /api-docs to see your documentation.
How It Works
nextjs-auto-swagger-gen automatically:
- Scans your project for API route files
- Parses TypeScript AST to understand your code
- Infers request/response schemas from types
- Generates OpenAPI 3.1 specification
- Serves interactive Swagger UI
Supported Patterns
Next.js App Router
app/
├── api/
│ ├── users/
│ │ ├── route.ts → /api/users
│ │ └── [id]/
│ │ └── route.ts → /api/users/{id}
│ └── posts/
│ └── route.ts → /api/postsNext.js Pages Router
pages/
└── api/
├── users/
│ ├── index.ts → /api/users
│ └── [id].ts → /api/users/{id}
└── posts.ts → /api/postsAPI Patterns
Basic Route Handler
// app/api/users/route.ts
export async function GET(request: Request) {
const users = await db.users.findMany();
return Response.json(users);
}
export async function POST(request: Request) {
const body = await request.json();
const user = await db.users.create(body);
return Response.json(user, { status: 201 });
}With TypeScript Types
// Types are automatically inferred
interface CreateUserInput {
email: string;
name: string;
role: 'admin' | 'user';
}
export async function POST(request: Request) {
const body = await request.json() as CreateUserInput;
// auto-swagger infers the request body schema
return Response.json({ success: true });
}With Zod Schemas
import { z } from 'zod';
const CreateUserSchema = z.object({
email: z.string().email(),
name: z.string().min(1).max(100),
role: z.enum(['admin', 'user']),
});
export async function POST(request: Request) {
const body = await request.json();
const validated = CreateUserSchema.parse(body);
// auto-swagger converts Zod schema to OpenAPI
return Response.json(validated);
}Comment-Based Hints
/**
* Get all users
* Returns a paginated list of users
*
* @tags users
* @auth bearer
* @rate-limit 100/min
*/
export async function GET(request: Request) {
// ...
}
/**
* Delete a user
* @deprecated Use soft delete instead
*/
export async function DELETE(request: Request, { params }) {
// ...
}Configuration
Create nextjs-auto-swagger-gen.config.js in your project root:
/** @type {import('nextjs-auto-swagger-gen').AutoSwaggerConfig} */
module.exports = {
// Scanner options
scanner: {
// Auto-detect framework (nextjs-app, nextjs-pages, express)
framework: 'auto',
// Custom include patterns
include: ['**/app/**/route.ts'],
// Exclude patterns
exclude: ['**/*.test.ts'],
},
// OpenAPI specification options
openapi: {
title: 'My API',
version: '1.0.0',
description: 'API documentation',
servers: [
{ url: 'http://localhost:3000', description: 'Development' },
{ url: 'https://api.example.com', description: 'Production' },
],
// Output format
outputFormat: 'both', // 'json' | 'yaml' | 'both'
outputPath: './docs',
},
// UI options
ui: {
enabled: true,
path: '/api-docs',
theme: 'auto', // 'light' | 'dark' | 'auto'
},
};CLI Commands
auto-swagger init
Initialize configuration file.
npx auto-swagger init
npx auto-swagger init --force # Overwrite existingauto-swagger generate
Generate OpenAPI specification and UI.
npx auto-swagger generate
npx auto-swagger generate --output ./docs
npx auto-swagger generate --json # Only JSON
npx auto-swagger generate --yaml # Only YAML
npx auto-swagger generate --no-ui # Skip UI
npx auto-swagger generate --verbose # Show detailsauto-swagger scan
Scan and display detected routes.
npx auto-swagger scan
npx auto-swagger scan --json # Output as JSONauto-swagger serve
Start a documentation server.
npx auto-swagger serve
npx auto-swagger serve --port 3001Programmatic API
import { generate, detectRoutes, generateOpenAPISpec } from 'auto-swagger';
// Simple generation
const result = await generate({
rootDir: process.cwd(),
output: './docs',
});
console.log(result.spec); // OpenAPI spec object
console.log(result.json); // JSON string
console.log(result.yaml); // YAML string
console.log(result.html); // Swagger UI HTML
// Advanced usage
const scanResult = await detectRoutes({
config: {
rootDir: process.cwd(),
framework: 'auto',
},
});
const spec = generateOpenAPISpec({
config: {
title: 'My API',
version: '1.0.0',
},
scanResult,
});Type Inference
auto-swagger infers types from multiple sources:
Priority Order
- Zod schemas - Highest fidelity, converts to JSON Schema
- TypeScript types - Type assertions and annotations
- Code analysis - Response.json() calls, status codes
- Smart defaults - Based on naming conventions
What's Inferred
| Pattern | Inferred As |
|---------|-------------|
| await req.json() as Type | Request body schema |
| Response.json(data) | Response schema |
| { status: 201 } | Response status code |
| [id] in path | Path parameter |
| @auth bearer comment | Security requirement |
| @deprecated comment | Deprecated flag |
| @tags name comment | Operation tags |
Supported Comment Hints
| Hint | Description | Example |
|------|-------------|---------|
| @tags | Operation tags | @tags users, admin |
| @auth | Auth requirement | @auth bearer |
| @deprecated | Mark as deprecated | @deprecated |
| @summary | Short description | @summary Get all users |
| @description | Long description | @description Returns... |
| @rate-limit | Rate limit info | @rate-limit 100/min |
Limitations
Current Limitations
- Express/Fastify support is planned but not yet available
- Complex TypeScript generics may not be fully resolved
- Runtime-only type information (like Prisma types) requires hints
- Dynamic routes with complex patterns need manual hints
Best Practices
- Use Zod for complex schemas - gives best inference
- Add type assertions - helps TypeScript inference
- Write JSDoc comments - provides descriptions
- Keep routes focused - one resource per route file
Examples
See the example directory for a complete Next.js application demonstrating all features.
Contributing
Contributions are welcome! Please read our contributing guide before submitting PRs.
License
MIT © auto-swagger
