next-swagger-auto
v0.1.0
Published
FastAPI-style Swagger docs for Next.js
Maintainers
Readme
Next Swagger Auto
FastAPI-style Swagger docs for Next.js with zero manual route wiring. It scans your API routes, generates an OpenAPI 3 spec, and serves Swagger UI at /docs.
Features
- App Router and Pages Router support
- Auto-detects API routes
- Optional Zod schema extraction for request/response
- Swagger UI included (no React warnings)
- Works in dev and build with automatic regeneration
Quick Start
- Install the package.
npm i next-swagger-auto- Initialize in your Next.js project.
npx next-swagger-auto init- Install dependencies and run.
npm install
npm run dev- Open:
http://localhost:3000/docsWhat the Init CLI Creates
openapi.config.tslib/docs-page.tsxlib/next-swagger-auto.tsscripts/generate-openapi.tsscripts/watch-openapi.tsscripts/copy-swagger-ui.ts- Docs route (
app/docs/page.tsxorpages/docs.tsx) - OpenAPI route (
app/api/openapi/route.tsorpages/api/openapi.ts)
How Auto-Detection Works
App Router:
- Scans all
app/**/route.*files - Uses exported handlers (
GET,POST,PUT, etc.)
Pages Router:
- Scans
pages/api/** - Tries to infer methods by reading
req.methodchecks - Falls back to
defaultMethodsif inference fails
Optional Zod Schemas (No Wrapper Required)
If you want request/response schemas in Swagger, export Zod schemas with one of these names in your route file:
Request:
RequestSchemarequestSchemaBodySchemabodySchema
Response:
ResponseSchemaresponseSchemaOutputSchemaoutputSchema
Example:
import { z } from "zod";
import { NextResponse } from "next/server";
export const RequestSchema = z.object({
message: z.string()
});
export const ResponseSchema = z.object({
reply: z.string()
});
export async function POST(request: Request) {
const body = await request.json();
return NextResponse.json({ reply: `You said: ${body.message}` });
}Configuration
Edit openapi.config.ts:
export const openapiConfig = {
info: {
title: "My API",
version: "1.0.0",
description: "My service docs"
},
servers: [{ url: "http://localhost:3000" }],
includeUndocumented: true,
defaultMethods: ["get", "post"]
};Scripts Added
generate:openapigeneratesopenapi-spec.tsdev:docswatches and regeneratesprepare:swagger-uicopies Swagger UI assetspredevandprebuildrun generation automatically
Troubleshooting
No operations defined in spec:
- Ensure you have API routes in
app/**/route.*orpages/api/**. - If a
.jsroute contains TypeScript types, rename it to.ts.
Swagger UI is blank:
- Run
npm run prepare:swagger-uiand reload.
License
MIT
