Gathering detailed insights and metrics for auto-nextjs-swagger-doc
Gathering detailed insights and metrics for auto-nextjs-swagger-doc
Gathering detailed insights and metrics for auto-nextjs-swagger-doc
Gathering detailed insights and metrics for auto-nextjs-swagger-doc
npm install auto-nextjs-swagger-doc
Typescript
Module System
Min. Node Version
Node Version
NPM Version
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
0
Compared to previous week
Last Month
0%
0
Compared to previous month
Last Year
0%
0
Compared to previous year
4
1
23
Generate Swagger JSON API from NextJS Api Routes
If you enjoy working with next-swagger-doc, you will love next-validations: NextJS API Validations, support Zod, Yup, Fastest-Validator, Joi, and more
This package reads your JSDoc-annotated source code on NextJS API route and generates an OpenAPI (Swagger) specification.
nextjs + swagger-jsdoc = next-swagger-doc
1yarn add next-swagger-doc
To incorporate next-swagger-doc
with your Next.js 13 project, follow these steps. This setup will generate Swagger documentation for your API based on your code and provide a built-in Swagger UI for viewing the documentation.
Next, create a new file lib/swagger.ts
. This file uses the next-swagger-doc
library to create a Swagger specification based on the API routes in your Next.js project.
1import { createSwaggerSpec } from 'next-swagger-doc'; 2 3export const getApiDocs = async () => { 4 const spec = createSwaggerSpec({ 5 apiFolder: 'app/api', // define api folder under app folder 6 definition: { 7 openapi: '3.0.0', 8 info: { 9 title: 'Next Swagger API Example', 10 version: '1.0', 11 }, 12 components: { 13 securitySchemes: { 14 BearerAuth: { 15 type: 'http', 16 scheme: 'bearer', 17 bearerFormat: 'JWT', 18 }, 19 }, 20 }, 21 security: [], 22 }, 23 }); 24 return spec; 25};
Create a new file app/api-doc/react-swagger.tsx
. This file exports a React component that uses swagger-ui-react
to display the Swagger UI based on the given spec.
1'use client'; 2 3import SwaggerUI from 'swagger-ui-react'; 4import 'swagger-ui-react/swagger-ui.css'; 5 6type Props = { 7 spec: Record<string, any>, 8}; 9 10function ReactSwagger({ spec }: Props) { 11 return <SwaggerUI spec={spec} />; 12} 13 14export default ReactSwagger;
Create a new file app/api-doc/page.tsx
. This page imports the Swagger spec and the Swagger UI component to display the Swagger documentation.
1import { getApiDocs } from '@/lib/swagger'; 2import ReactSwagger from './react-swagger'; 3 4export default async function IndexPage() { 5 const spec = await getApiDocs(); 6 return ( 7 <section className="container"> 8 <ReactSwagger spec={spec} /> 9 </section> 10 ); 11}
Lastly, add a Swagger comment to your API route in app/api/hello/route.ts
. This comment includes metadata about the API endpoint which will be read by next-swagger-doc
and included in the Swagger spec.
1/** 2 * @swagger 3 * /api/hello: 4 * get: 5 * description: Returns the hello world 6 * responses: 7 * 200: 8 * description: Hello World! 9 */ 10export async function GET(_request: Request) { 11 // Do whatever you want 12 return new Response('Hello World!', { 13 status: 200, 14 }); 15}
Now, navigate to localhost:3000/api-doc
(or wherever you host your Next.js application), and you should see the swagger UI.
1yarn add next-swagger-doc swagger-ui-react
pages/api-doc.tsx
1import { GetStaticProps, InferGetStaticPropsType } from 'next'; 2import { createSwaggerSpec } from 'next-swagger-doc'; 3import dynamic from 'next/dynamic'; 4import 'swagger-ui-react/swagger-ui.css'; 5 6const SwaggerUI = dynamic<{ 7 spec: any; 8}>(import('swagger-ui-react'), { ssr: false }); 9 10function ApiDoc({ spec }: InferGetStaticPropsType<typeof getStaticProps>) { 11 return <SwaggerUI spec={spec} />; 12} 13 14export const getStaticProps: GetStaticProps = async () => { 15 const spec: Record<string, any> = createSwaggerSpec({ 16 apiFolder: 'pages/api' // or 'src/pages/api', 17 definition: { 18 openapi: '3.0.0', 19 info: { 20 title: 'Next Swagger API Example', 21 version: '1.0', 22 }, 23 }, 24 }); 25 26 return { 27 props: { 28 spec, 29 }, 30 }; 31}; 32 33export default ApiDoc;
pages/api/doc.ts
1import { withSwagger } from 'next-swagger-doc'; 2 3const swaggerHandler = withSwagger({ 4 definition: { 5 openapi: '3.0.0', 6 info: { 7 title: 'NextJS Swagger', 8 version: '0.1.0', 9 }, 10 }, 11 apiFolder: 'pages/api', 12}); 13export default swaggerHandler();
pages/api/hello.ts
1import { NextApiRequest, NextApiResponse } from 'next'; 2 3/** 4 * @swagger 5 * /api/hello: 6 * get: 7 * description: Returns the hello world 8 * responses: 9 * 200: 10 * description: hello world 11 */ 12const handler = (_req: NextApiRequest, res: NextApiResponse) => { 13 res.status(200).json({ 14 result: 'hello world', 15 }); 16}; 17 18export default handler;
next-swagger-doc.json
1{ 2 "apiFolder": "pages/api", 3 "schemaFolders": ["models"], 4 "definition": { 5 "openapi": "3.0.0", 6 "info": { 7 "title": "Next Swagger API Example", 8 "version": "1.0" 9 } 10 } 11}
1yarn next-swagger-doc-cli next-swagger-doc.json
1gh repo clone jellydn/next-swagger-doc 2cd example 3yarn install 4yarn dev
Then open http://localhost:3000/api-doc or http://localhost:3000/ on your browser
In order to set an eslint rule that checks that all the APIs actually have a swagger JsDoc description we can use the following settings:
Install the JsDoc eslint plugin:
1yarn add -D eslint-plugin-jsdoc
Create the custom rule in your eslint configuration file:
1{ 2 //...your configuration 3 "overrides": [ 4 //...your overrides 5 { 6 // Force the setting of a swagger description on each api endpoint 7 "files": ["pages/api/**/*.ts"], 8 "plugins": ["jsdoc"], 9 "rules": { 10 "jsdoc/no-missing-syntax": [ 11 "error", 12 { 13 "contexts": [ 14 { 15 "comment": "JsdocBlock:has(JsdocTag[tag=swagger])", 16 "context": "any", 17 "message": "@swagger documentation is required on each API. Check this out for syntax info: https://github.com/jellydn/next-swagger-doc" 18 } 19 ] 20 } 21 ] 22 } 23 ] 24}
👤 Huynh Duc Dung
Give a ⭐️ if this project helped you!
Thanks goes to these wonderful people (emoji key):
Dung Duc Huynh (Kaka) 💻 📖 | tmirkovic 📖 | Matthew Holloway 💻 | leventemihaly 📖 | PAHRIZAL MA'RUP 💻 | Aris 📖 | Valerio Ageno 📖 |
cachho 💻 |
This project follows the all-contributors specification. Contributions of any kind welcome!
No vulnerabilities found.
No security vulnerabilities found.