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 🙏

© 2025 – Pkg Stats / Ryan Hefner

auto-swagger-js

v1.0.3

Published

Auto Swagger UI generator for Express and REST APIs with zero config

Downloads

8

Readme

🧾 auto-swagger-js

🔥 Auto Swagger UI generator for Express.js REST APIs — with zero configuration.

NPM License Node


✨ Features

  • 📦 Zero-configuration — no need to write JSDoc or decorators
  • 🔍 Automatically detects all routes and HTTP methods
  • 🔗 Supports deeply nested routers with full path resolution
  • 🧠 Converts Express :param syntax to Swagger {param} format
  • 🏷️ Smart tag generation from route segments (skips API prefixes)
  • 🧾 Auto-generates request body schema for POST, PUT, and PATCH
  • 🚀 Serves interactive Swagger UI at /docs
  • 🔧 Compatible with Express 4.x
  • 📱 Interactive API testing directly in the browser

📦 Installation

npm install auto-swagger-js swagger-ui-express

🔧 swagger-ui-express is a required peer dependency.


🚀 Quick Start

Basic Usage

const express = require("express");
const autoSwagger = require("auto-swagger-js");

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

// Define your routes
app.get("/users/:id", (req, res) => {
    res.json({ id: req.params.id, name: "John Doe" });
});

app.post("/users", (req, res) => {
    res.json({ message: "User created", data: req.body });
});

// Generate Swagger docs AFTER defining routes
autoSwagger({
    app,
    title: "My API",
    version: "1.0.0",
});

app.listen(3000, () => {
    console.log("Server: http://localhost:3000");
    console.log("Docs: http://localhost:3000/docs");
});

With Modular Routes

const express = require("express");
const autoSwagger = require("auto-swagger-js");

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

// Import route modules
const userRoutes = require("./routes/users");
const productRoutes = require("./routes/products");

// Mount routes with prefixes
app.use("/api/v1/users", userRoutes);
app.use("/api/v1/products", productRoutes);

// Generate Swagger docs AFTER mounting routes
autoSwagger({
    app,
    title: "My E-commerce API",
    description:
        "A comprehensive e-commerce API with user and product management",
    version: "1.2.0",
    host: "api.mycompany.com",
    basePath: "/",
    schemes: ["https", "http"],
    securityDefinitions: {
        bearerAuth: {
            type: "http",
            scheme: "bearer",
            bearerFormat: "JWT",
        },
    },
});

app.listen(3000, () => {
    console.log("API docs available at http://localhost:3000/docs");
});

Advanced Configuration Example

const express = require("express");
const autoSwagger = require("auto-swagger-js");

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

// Your routes here...
app.use("/api/v1/auth", authRoutes);
app.use("/api/v1/users", userRoutes);
app.use("/api/v1/orders", orderRoutes);

// Full configuration example
autoSwagger({
    app,
    title: "Enterprise API",
    description:
        "Enterprise-grade API for managing users, orders, and authentication",
    version: "2.1.0",
    host: "enterprise-api.example.com",
    basePath: "/api/v1",
    schemes: ["https"],
    securityDefinitions: {
        ApiKeyAuth: {
            type: "apiKey",
            in: "header",
            name: "X-API-Key",
        },
        BearerAuth: {
            type: "http",
            scheme: "bearer",
            bearerFormat: "JWT",
        },
        OAuth2: {
            type: "oauth2",
            flows: {
                authorizationCode: {
                    authorizationUrl:
                        "https://auth.example.com/oauth/authorize",
                    tokenUrl: "https://auth.example.com/oauth/token",
                    scopes: {
                        read: "Read access",
                        write: "Write access",
                        admin: "Admin access",
                    },
                },
            },
        },
    },
    routePrefix: "/v1",
});

app.listen(443, () => {
    console.log("Secure API running on https://enterprise-api.example.com");
    console.log("Documentation: https://enterprise-api.example.com/docs");
});

📚 API Reference

Function Signature

autoSwagger(options: {
  app: Express.Application;
  title?: string;
  description?: string;
  version?: string;
  host?: string;
  basePath?: string;
  schemes?: string[];
  securityDefinitions?: object;
  routePrefix?: string;
}): void

Options

| Option | Type | Default | Description | | --------------------- | --------------------- | ------------------------------------ | --------------------------------------- | | app | Express.Application | (required) | Your Express application instance | | title | string | "Auto Swagger" | Title for the Swagger UI | | description | string | "Auto-generated API documentation" | Description of your API | | version | string | "1.0.0" | API version string | | host | string | "localhost:3000" | Host where the API is served | | basePath | string | "" | Base path for all API endpoints | | schemes | string[] | ["http"] | Transfer protocols (http, https) | | securityDefinitions | object | null | Security definitions for authentication | | routePrefix | string | "" | Prefix to add to all route paths |


🧪 Example Output

Input Routes

// routes/users.js
const router = express.Router();

router.get("/", (req, res) => {
    res.json({ message: "Get all users" });
});

router.get("/:id", (req, res) => {
    res.json({ id: req.params.id });
});

router.post("/", (req, res) => {
    res.json({ message: "User created" });
});

module.exports = router;

// main app
app.use("/api/v1/users", userRoutes);

Generated Swagger Spec

/api/v1/users:
    get:
        summary: GET /api/v1/users
        tags:
            - users
        responses:
            200:
                description: Success
    post:
        summary: POST /api/v1/users
        tags:
            - users
        requestBody:
            content:
                application/json:
                    schema:
                        type: object
                        properties: {}
        responses:
            200:
                description: Success

/api/v1/users/{id}:
    get:
        summary: GET /api/v1/users/:id
        tags:
            - users
        parameters:
            - in: path
              name: id
              required: true
              schema:
                  type: string
        responses:
            200:
                description: Success

🏷️ Smart Tag Generation

Auto-swagger-js intelligently generates tags by:

  1. Extracting meaningful segments from route paths
  2. Skipping common API prefixes like api, v1, v2, etc.
  3. Using the first meaningful segment as the tag name

Examples:

| Route Path | Generated Tag | | ------------------ | ------------- | | /api/v1/users | users | | /api/v2/products | products | | /v1/orders | orders | | /admin/settings | admin |


🔧 Advanced Features

Automatic Parameter Detection

Express route parameters like :id, :userId are automatically converted to Swagger path parameters:

// Express route
app.get("/users/:userId/posts/:postId", handler);

// Becomes Swagger path
("/users/{userId}/posts/{postId}");

Request Body Schema Generation

For POST, PUT, and PATCH methods, auto-swagger-js automatically adds a basic JSON request body schema:

requestBody:
    content:
        application/json:
            schema:
                type: object
                properties: {}

Nested Router Support

Supports complex nested routing structures:

const apiRouter = express.Router();
const v1Router = express.Router();
const userRouter = express.Router();

userRouter.get("/:id", handler);
v1Router.use("/users", userRouter);
apiRouter.use("/v1", v1Router);
app.use("/api", apiRouter);

// Results in: /api/v1/users/{id}

📁 Project Structure

auto-swagger-js/
├── index.js               # Main entry point
├── package.json           # Package configuration
├── README.md             # This file
└── lib/
    ├── scanRoutes.js      # Route extraction from Express stack
    ├── extractParams.js   # Parameter conversion (:id → {id})
    ├── buildSwaggerSpec.js # OpenAPI specification builder
    └── serveSwaggerUI.js  # Swagger UI server setup

🔨 Requirements

  • Node.js: 14.x or higher
  • Express: 4.x (Express 5.x not supported yet)
  • swagger-ui-express: 4.x or 5.x

📄 Endpoints

Auto-swagger-js automatically creates these endpoints:

  • GET /docs - Interactive Swagger UI
  • GET /docs-json - Raw OpenAPI JSON specification

🐛 Troubleshooting

Routes Not Detected

Problem: Swagger shows "No operations defined in spec!"

Solutions:

  1. Ensure you call autoSwagger() after defining/mounting all routes
  2. Make sure you're using Express 4.x (not 5.x)
  3. Check that route paths start with / (e.g., router.get("/users", ...))

Missing Tags

Problem: All routes show under same tag

Solution: Ensure your route structure has meaningful segments after API prefixes:

// Good: Will generate "users" tag
app.use("/api/v1/users", userRouter);

// Bad: Will generate "api" tag
app.use("/api", userRouter);

Path Parameter Issues

Problem: Parameters showing as :id instead of {id}

Solution: This is handled automatically. If you see this, please file an issue.


🤝 Contributing

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

Development Setup

git clone https://github.com/Operaconga14/auto-swagger-js.git
cd auto-swagger-js
npm install

Running Tests

npm test

📝 License

MIT License - see LICENSE file for details.


🧑‍💻 Author

Amire Joseph


🔮 Roadmap

  • [ ] Express 5.x compatibility
  • [ ] Custom tag configuration
  • [ ] JSON schema auto-detection from middleware
  • [ ] CLI tool for exporting OpenAPI specs
  • [ ] Koa.js and Fastify support
  • [ ] Custom response schema definition
  • [ ] Authentication scheme detection

Made with ❤️ for the Express.js community