@artonramadani/express-swagger-autogen
v1.2.4
Published
Automatic Swagger/OpenAPI documentation generator for Express.js with controller analysis and minimal-config setup
Maintainers
Readme
Express Swagger Autogen
🚀 Minimal-config automatic Swagger/OpenAPI documentation generator for Express.js
Automatically generates beautiful, interactive API documentation from your Express routes with minimal setup. No need to write extensive JSDoc comments or maintain separate documentation files!
Features
- ✅ Minimal Configuration - Works out of the box with sensible defaults
- ✅ Auto-Detection - Automatically discovers all Express routes
- ✅ Smart Middleware Detection - Automatically detects authentication and validation middleware
- ✅ Controller Analysis - Extracts parameters from your controllers
- ✅ JWT Support - Built-in Bearer token authentication
- ✅ Interactive UI - Beautiful Swagger UI with "Try it out" functionality
- ✅ Express 4 & 5 - Compatible with both major versions
- ✅ Manual Schemas - Override auto-detection for complex endpoints
- ✅ TypeScript Ready - Works with TypeScript projects
Installation
npm install @artonramadani/express-swagger-autogenQuick Start
const express = require('express');
const { initSwagger } = require('express-swagger-autogen');
const app = express();
// Your routes
app.use('/api/v1', require('./routes'));
// Initialize Swagger (AFTER routes are registered)
initSwagger(app, {
title: 'My API',
version: '1.0.0',
description: 'My awesome API documentation',
basePath: '/api/v1'
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
console.log('Swagger UI: http://localhost:3000/api-docs');
});That's it! Open http://localhost:3000/api-docs and see your documentation! 🎉
📚 Complete Example
Want to see a full working example? Check out the example directory which includes:
- Complete Express app with authentication
- JWT middleware (automatically detected)
- CRUD operations
- Request/response schemas
- Step-by-step guide
Quick start the example:
cd example
npm install
npm start
# Open http://localhost:3000/api-docsSee example/QUICKSTART.md for detailed instructions!
Configuration Options
initSwagger(app, {
// Basic Info
title: 'My API', // API title
version: '1.0.0', // API version
description: 'API Documentation', // API description
// Routing
basePath: '/api/v1', // Base path to filter routes
docsPath: '/api-docs', // Where Swagger UI is served
// Servers
servers: [
{
url: 'http://localhost:3000',
description: 'Development'
},
{
url: 'https://api.example.com',
description: 'Production'
}
],
// Security
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
description: 'Enter your JWT token'
}
},
// Manual Schemas - Option 1: Load from file (recommended)
manualSchemasPath: './swagger/manualSchemas.js',
// Manual Schemas - Option 2: Define inline
manualSchemas: {
'createOrderHandler': {
body: {
items: {
type: 'array',
description: 'Order items',
items: {
type: 'object',
required: ['productId', 'quantity'],
properties: {
productId: {
type: 'integer',
example: 123
},
quantity: {
type: 'integer',
example: 5
}
}
}
},
customerId: {
type: 'integer',
example: 456
}
}
}
},
// Swagger UI Options
swaggerUiOptions: {
explorer: true,
customCss: '.swagger-ui .topbar { display: none }'
}
});Manual Schemas
For complex endpoints with arrays or nested objects, you can provide manual schemas in two ways:
Option 1: External File (Recommended)
Create a separate file for your schemas to keep your code clean:
// swagger/manualSchemas.js
module.exports = {
// Key is the handler function name
'saveOrderHandler': {
body: {
items: {
type: 'array',
description: 'List of products',
items: {
type: 'object',
required: ['ItemID', 'Quantity'],
properties: {
ItemID: { type: 'integer', example: 123 },
Quantity: { type: 'integer', example: 5 }
}
},
example: [
{ ItemID: 123, Quantity: 5 },
{ ItemID: 456, Quantity: 3 }
]
},
CustomerID: { type: 'integer', example: 789 },
Notes: { type: 'string', example: 'Fast delivery' }
}
}
};// server.js
initSwagger(app, {
title: 'My API',
basePath: '/api/v1',
manualSchemasPath: './swagger/manualSchemas.js' // Load from file
});Option 2: Inline Definition
initSwagger(app, {
title: 'My API',
basePath: '/api/v1',
manualSchemas: {
'saveOrderHandler': {
body: {
items: { /* ... */ },
CustomerID: { type: 'integer', example: 789 }
}
}
}
});Note: You can use both approaches together. Inline schemas will override file-based schemas for the same handler.
Organizing Your Schemas
We recommend creating a dedicated directory for Swagger configuration:
your-project/
├── controllers/
├── routes/
├── middleware/
├── swagger/ # ← Swagger configuration
│ ├── manualSchemas.js # Schema definitions
│ └── README.md # Documentation
└── server.jsThis keeps your configuration organized and your server.js clean!
📖 See MANUAL_SCHEMAS_GUIDE.md for complete guide with examples and best practices.
Authentication
The library automatically detects JWT authentication middleware by analyzing your route middleware chain. Any middleware with names like verifyToken, authenticate, checkAuth, or containing JWT verification code will be automatically recognized.
Using Authentication in Swagger UI
- Call your login endpoint
- Copy the JWT token from the response
- Click the "Authorize" 🔒 button at the top
- Paste your token (without "Bearer" prefix)
- All subsequent requests will include the token automatically!
Supported Authentication Patterns
The middleware analyzer detects various authentication patterns:
// Pattern 1: Named middleware
const verifyToken = (req, res, next) => { /* JWT verification */ };
router.get('/protected', verifyToken, handler);
// Pattern 2: Inline middleware
router.get('/secure', authenticate, handler);
// Pattern 3: Custom auth middleware
const checkUserAuth = (req, res, next) => { /* auth logic */ };
router.post('/data', checkUserAuth, handler);All these patterns are automatically detected and documented with proper security requirements!
Advanced Usage
Custom Server URLs
initSwagger(app, {
title: 'My API',
servers: [
{
url: 'http://localhost:3000',
description: 'Local'
},
{
url: 'https://staging-api.example.com',
description: 'Staging'
},
{
url: 'https://api.example.com',
description: 'Production'
}
]
});Multiple Security Schemes
initSwagger(app, {
title: 'My API',
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT'
},
apiKey: {
type: 'apiKey',
in: 'header',
name: 'X-API-Key'
}
}
});Access Raw OpenAPI Spec
The OpenAPI specification is available as JSON at /api-docs.json (or ${docsPath}.json).
You can also access it programmatically:
const { spec } = initSwagger(app, options);
console.log(spec); // Full OpenAPI 3.0 spec objectMiddleware Detection Details
The library includes a sophisticated middleware analyzer that examines your code to understand its purpose:
What Gets Analyzed:
- Middleware function names
- Middleware file contents (if accessible)
- Code patterns and indicators
- Common library usage (express-validator, jsonwebtoken, etc.)
Authentication Detection Indicators:
- Function names:
auth,token,jwt,verify,authenticate,protected,secure,guard - Code patterns:
jwt.verify(),req.headers.authorization,Bearer, HTTP 401/403 responses - Automatically adds security requirements to endpoints
Validation Detection Indicators:
- Function names:
validat,check,sanitiz,rules - Code patterns:
express-validator,validationResult(),body(),param(),query() - Automatically documents validation errors
Example Middleware File Analysis:
// middleware/verifyToken.js
const jwt = require('jsonwebtoken');
const verifyToken = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ message: 'No token provided' });
}
try {
const decoded = jwt.verify(token, process.env.SECRET);
req.user = decoded;
next();
} catch (error) {
return res.status(403).json({ message: 'Invalid token' });
}
};
// ✅ This middleware will be automatically detected as authentication
// because it contains: jwt.verify, authorization header, 401/403 responsesThe analyzer looks for multiple indicators to ensure accurate detection!
How It Works
- Route Discovery: Scans your Express app's router stack to find all routes
- Middleware Analysis: Intelligently detects authentication and validation middleware by analyzing:
- Middleware function names (e.g.,
verifyToken,authenticate,checkAuth) - Middleware code patterns (JWT verification, token validation)
- Common authentication libraries (jsonwebtoken, passport, etc.)
- Middleware function names (e.g.,
- Parameter Extraction: Automatically identifies path, query, and body parameters
- Schema Generation: Creates OpenAPI schemas from your route definitions
- UI Generation: Serves interactive Swagger UI with all your endpoints
Middleware Detection
The library automatically detects middleware and applies appropriate security schemes:
Authentication Middleware - Automatically detected by:
- Function names containing:
auth,token,jwt,verify,authenticate,protected,secure,guard - Code patterns: JWT verification, authorization headers, bearer tokens
- Automatically adds 🔒 lock icon and security requirements in Swagger UI
Validation Middleware - Automatically detected by:
- Function names containing:
validat,check,sanitiz,rules - Express-validator usage patterns
- Automatically documents validation errors (400 responses)
Example:
// These middleware will be automatically detected
router.post('/users',
verifyToken, // ✅ Detected as auth middleware
validateUser(), // ✅ Detected as validation middleware
createUserHandler
);Minimal configuration needed - the library analyzes your middleware and generates appropriate documentation!
Requirements
- Node.js >= 14.0.0
- Express >= 4.0.0 or >= 5.0.0
License
MIT
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
Support
If you encounter any issues or have questions, please file an issue on GitHub.
Made with ❤️ for the Express.js community
