npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

express-auto-swagger

v2.0.0

Published

Automatically generate OpenAPI 3.0 specifications and serve Swagger UI for Express.js applications with zero configuration

Readme

express-auto-swagger

npm version License: MIT Node.js CI

Automatically generate OpenAPI 3.0 specifications and serve Swagger UI for Express.js applications with zero configuration. Just like Swagger works in .NET, but for Node.js!

✨ Features

  • 🚀 Zero Configuration - Works out of the box with sensible defaults
  • 🔄 Automatic Route Discovery - Intercepts all Express routes automatically
  • 📖 Interactive Documentation - Serves Swagger UI for testing APIs
  • 📄 OpenAPI 3.0 Compliant - Generates valid OpenAPI specifications
  • Real-time Updates - Documentation updates as you add routes
  • 🎛️ Configurable - Customize titles, versions, and endpoint paths
  • 🛡️ Error Resilient - Graceful handling of edge cases
  • 📦 Lightweight - Minimal dependencies and overhead
  • 🏷️ Route Grouping - Automatically groups routes by router
  • 📋 Model Support - Auto-load models for accurate request/response schemas
  • 🔗 Direct & Router Routes - Supports both app.get() and router-based routes
  • 🎯 Smart Schema Generation - Automatically generates schemas from models

🚀 Quick Start

Installation

npm install express-auto-swagger

Basic Usage

const express = require('express');
const autoSwagger = require('express-auto-swagger');

const app = express();

// Initialize express-auto-swagger (must be called before defining routes)
autoSwagger(app);

// Define your routes as usual
app.get('/users', (req, res) => {
    res.json([{ id: 1, name: 'John Doe' }]);
});

app.post('/users', (req, res) => {
    res.status(201).json({ id: 2, name: 'Jane Smith' });
});

app.get('/users/:id', (req, res) => {
    res.json({ id: req.params.id, name: 'User Name' });
});

app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
    console.log('📖 API Docs: http://localhost:3000/docs');
    console.log('📄 OpenAPI JSON: http://localhost:3000/openapi.json');
});

That's it! Your API documentation is now available at:

  • Swagger UI: http://localhost:3000/docs
  • OpenAPI JSON: http://localhost:3000/openapi.json

📖 Documentation

Configuration Options

const path = require('path');

const swagger = autoSwagger(app, {
    title: 'My API',                              // API title (default: "API Documentation")
    version: '1.0.0',                             // API version (default: "1.0.0")
    docsPath: '/api-docs',                        // Swagger UI path (default: "/docs")
    jsonPath: '/openapi.json',                    // OpenAPI JSON path (default: "/openapi.json")
    modelsPath: path.join(__dirname, 'models'),   // Path to models directory (optional)
    
    // Security configuration (optional)
    security: {
        jwt: true,                                // Enable JWT Bearer authentication
        // OR
        bearer: true,                             // Enable Bearer token authentication
        // OR
        apiKey: {                                 // Enable API Key authentication
            in: 'header',                         // 'header', 'query', or 'cookie'
            name: 'X-API-Key'                     // Header/query parameter name
        },
        // OR
        basic: true,                              // Enable Basic authentication
        // OR
        oauth2: {                                 // Enable OAuth2
            flows: {
                authorizationCode: {
                    authorizationUrl: 'https://example.com/oauth/authorize',
                    tokenUrl: 'https://example.com/oauth/token',
                    scopes: {
                        read: 'Read access',
                        write: 'Write access'
                    }
                }
            }
        }
    },
    
    // Server URLs (optional)
    servers: [
        {
            url: 'http://localhost:3000',
            description: 'Development server'
        },
        {
            url: 'https://api.example.com',
            description: 'Production server'
        }
    ]
});

Advanced Usage

The autoSwagger function returns an object with useful methods:

const swagger = autoSwagger(app, options);

// Access configuration
console.log(swagger.config);

// Get all discovered routes
console.log(swagger.getRoutes());

// Get routes grouped by router/tag
console.log(swagger.getRouteGroups());

// Get generated OpenAPI specification
console.log(swagger.getSpec());

// Add custom models programmatically
swagger.addModel('CustomModel', {
    type: 'object',
    properties: {
        id: { type: 'integer' },
        name: { type: 'string' }
    }
});

// Bind a model to a router
const userRouter = express.Router();
swagger.bindModel(userRouter, 'User');

// Set custom group name for a router
swagger.setGroup(userRouter, 'User Management');

Route Parameter Detection

express-auto-swagger automatically detects route parameters and includes them in the OpenAPI specification:

// This route:
app.get('/users/:userId/posts/:postId', handler);

// Generates OpenAPI with parameters:
// - userId (path parameter, required)
// - postId (path parameter, required)

Supported HTTP Methods

All standard Express HTTP methods are supported:

  • GET
  • POST
  • PUT
  • DELETE
  • PATCH

Dynamic Route Registration

Routes added after initialization are automatically captured:

autoSwagger(app);

// Initial routes
app.get('/users', handler);

// Later in your application
setTimeout(() => {
    app.post('/posts', handler); // This will also be documented
}, 1000);

🎯 Examples

Basic REST API

const express = require('express');
const autoSwagger = require('express-auto-swagger');

const app = express();
app.use(express.json());

autoSwagger(app, {
    title: 'User Management API',
    version: '1.0.0'
});

// CRUD operations
app.get('/users', (req, res) => res.json(users));
app.post('/users', (req, res) => res.status(201).json(newUser));
app.get('/users/:id', (req, res) => res.json(user));
app.put('/users/:id', (req, res) => res.json(updatedUser));
app.delete('/users/:id', (req, res) => res.status(204).send());

app.listen(3000);

Custom Configuration

const express = require('express');
const autoSwagger = require('express-auto-swagger');

const app = express();

const swagger = autoSwagger(app, {
    title: 'My Custom API',
    version: '2.1.0',
    docsPath: '/documentation',
    jsonPath: '/api/spec.json'
});

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

app.listen(3000, () => {
    console.log(`Docs: http://localhost:3000${swagger.config.docsPath}`);
    console.log(`JSON: http://localhost:3000${swagger.config.jsonPath}`);
});

Router-Based Routes with Models

const express = require('express');
const path = require('path');
const autoSwagger = require('express-auto-swagger');

const app = express();
app.use(express.json());

// Initialize with models directory
const swagger = autoSwagger(app, {
    title: 'My API',
    version: '1.0.0',
    modelsPath: path.join(__dirname, 'models')
});

// Create a router and bind a model to it
const userRouter = express.Router();
swagger.bindModel(userRouter, 'User');
swagger.setGroup(userRouter, 'User Management');

// Define routes - they will automatically use the User model schema
userRouter.get('/', (req, res) => res.json(users));
userRouter.post('/', (req, res) => res.status(201).json(newUser));
userRouter.get('/:id', (req, res) => res.json(user));
userRouter.put('/:id', (req, res) => res.json(updatedUser));
userRouter.delete('/:id', (req, res) => res.status(204).send());

// Mount the router
app.use('/api/users', userRouter);

app.listen(3000);

Model Definition

Create a model file in your models directory (e.g., models/User.js):

module.exports = {
    schema: {
        type: 'object',
        required: ['name', 'email'],
        properties: {
            id: {
                type: 'integer',
                description: 'User ID',
                example: 1
            },
            name: {
                type: 'string',
                description: 'User full name',
                minLength: 2,
                maxLength: 100,
                example: 'John Doe'
            },
            email: {
                type: 'string',
                format: 'email',
                description: 'User email address',
                example: '[email protected]'
            },
            age: {
                type: 'integer',
                minimum: 0,
                maximum: 150,
                description: 'User age',
                example: 30
            }
        }
    }
};

Direct App Routes (Without Router)

const express = require('express');
const autoSwagger = require('express-auto-swagger');

const app = express();
app.use(express.json());

const swagger = autoSwagger(app);

// Direct routes on app - automatically grouped as "Direct Routes"
app.get('/health', (req, res) => {
    res.json({ status: 'ok' });
});

app.post('/auth/login', (req, res) => {
    res.json({ token: 'jwt-token' });
});

app.listen(3000);

Programmatic Model Registration

const swagger = autoSwagger(app);

// Add models programmatically
swagger.addModel('LoginRequest', {
    type: 'object',
    required: ['username', 'password'],
    properties: {
        username: { type: 'string', example: '[email protected]' },
        password: { type: 'string', format: 'password', example: 'password123' }
    }
});

swagger.addModel('LoginResponse', {
    type: 'object',
    properties: {
        token: { type: 'string', example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' },
        user: { $ref: '#/components/schemas/User' }
    }
});

JWT Authentication Setup

const express = require('express');
const autoSwagger = require('express-auto-swagger');

const app = express();
app.use(express.json());

// Initialize with JWT authentication
const swagger = autoSwagger(app, {
    title: 'Secure API',
    version: '1.0.0',
    security: {
        jwt: true  // Adds JWT Bearer token authentication to Swagger UI
    }
});

// JWT middleware (example)
const authenticateJWT = (req, res, next) => {
    const authHeader = req.headers.authorization;
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return res.status(401).json({ error: 'Unauthorized' });
    }
    
    const token = authHeader.substring(7);
    // Verify token here (use jsonwebtoken library)
    // jwt.verify(token, SECRET_KEY, (err, user) => { ... });
    
    next();
};

// Public route
app.post('/auth/login', (req, res) => {
    // Validate credentials and generate token
    const token = 'your-jwt-token';
    res.json({ token });
});

// Protected routes
app.use('/api/users', authenticateJWT, userRoutes);

app.listen(3000);

Using JWT in Swagger UI:

  1. Open Swagger UI at /docs
  2. Click the "Authorize" button (🔓 lock icon)
  3. Enter your JWT token (without "Bearer" prefix)
  4. Click "Authorize" and "Close"
  5. All requests will now include the Authorization header

🔧 API Reference

autoSwagger(app, options)

Initializes express-auto-swagger for the given Express application.

Parameters:

  • app (Express Application) - The Express app instance
  • options (Object, optional) - Configuration options

Options:

  • title (string) - API documentation title (default: "API Documentation")
  • version (string) - API version (default: "1.0.0")
  • docsPath (string) - Swagger UI endpoint path (default: "/docs")
  • jsonPath (string) - OpenAPI JSON endpoint path (default: "/openapi.json")
  • modelsPath (string) - Path to models directory for auto-loading schemas (optional)

Returns:

  • registry - Route registry instance
  • config - Resolved configuration object
  • getRoutes() - Function to get all discovered routes
  • getRouteGroups() - Function to get routes grouped by router/tag
  • getSpec() - Function to get the generated OpenAPI specification
  • addModel(name, schema) - Function to add a model schema programmatically
  • bindModel(router, modelName) - Function to bind a model to a router
  • setGroup(router, groupName) - Function to set a custom group name for a router

Error Handling

express-auto-swagger is designed to be resilient and will not break your application:

  • Invalid route paths are skipped with warnings
  • Missing dependencies fall back gracefully
  • Configuration errors use safe defaults
  • Route registration errors are logged but don't stop the app

🛠️ Requirements

  • Node.js: 14.x or higher
  • Express: 4.x or higher
  • swagger-ui-express: 4.x or higher (automatically installed)

📦 Dependencies

express-auto-swagger has minimal dependencies:

  • swagger-ui-express - For serving the Swagger UI interface

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Development Setup

# Clone the repository
git clone https://github.com/shivomv/express-auto-swagger.git
cd express-auto-swagger

# Install dependencies
npm install

# Run tests
npm test

# Run examples
npm run example

Running Tests

# Run all tests
npm test

# Run specific test file
npm test -- test/specific-test.test.js

# Run tests with coverage
npm test -- --coverage

Running Examples

# Basic example
npm run example
# or
node example/app.js

# Advanced example
node example/advanced-example.js

# Minimal example
node example/minimal-example.js

📝 Changelog

v1.0.0

  • Initial release
  • Automatic route discovery
  • OpenAPI 3.0 specification generation
  • Swagger UI integration
  • Configurable endpoints and metadata
  • Comprehensive error handling
  • Full test coverage

🐛 Troubleshooting

Common Issues

Q: Swagger UI shows "Failed to load API definition" A: Make sure the OpenAPI JSON endpoint is accessible and returns valid JSON. Check the browser console for errors.

Q: Routes are not appearing in the documentation A: Ensure autoSwagger() is called before defining your routes. Routes defined before initialization won't be captured.

Q: Custom paths are not working A: Verify that custom paths start with / and don't conflict with existing routes.

Q: Getting "swagger-ui-express not found" warnings A: Install the peer dependency: npm install swagger-ui-express

Debug Mode

Enable debug logging by setting the environment variable:

DEBUG=express-auto-swagger node app.js

Getting Help

If you encounter issues:

  1. Check the examples directory for usage patterns
  2. Review the test files for expected behavior
  3. Search existing GitHub issues
  4. Create a new issue with a minimal reproduction case

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

  • Inspired by Swagger integration in .NET applications
  • Built on top of the excellent swagger-ui-express package
  • Thanks to the Express.js community for the robust framework

🔗 Related Projects


Made with ❤️ for the Node.js community