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

nextjs-auto-swagger-gen

v1.0.1

Published

Zero-config, code-first API documentation generator for Next.js and Node.js

Downloads

198

Readme

nextjs-auto-swagger-gen

Zero-config, code-first API documentation generator for Next.js and Node.js

npm version License: MIT GitHub

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-gen

Quick 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 serve

Option 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:

  1. Scans your project for API route files
  2. Parses TypeScript AST to understand your code
  3. Infers request/response schemas from types
  4. Generates OpenAPI 3.1 specification
  5. 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/posts

Next.js Pages Router

pages/
└── api/
    ├── users/
    │   ├── index.ts          → /api/users
    │   └── [id].ts           → /api/users/{id}
    └── posts.ts              → /api/posts

API 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 existing

auto-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 details

auto-swagger scan

Scan and display detected routes.

npx auto-swagger scan
npx auto-swagger scan --json  # Output as JSON

auto-swagger serve

Start a documentation server.

npx auto-swagger serve
npx auto-swagger serve --port 3001

Programmatic 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

  1. Zod schemas - Highest fidelity, converts to JSON Schema
  2. TypeScript types - Type assertions and annotations
  3. Code analysis - Response.json() calls, status codes
  4. 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

  1. Use Zod for complex schemas - gives best inference
  2. Add type assertions - helps TypeScript inference
  3. Write JSDoc comments - provides descriptions
  4. 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