• Stars
    star
    375
  • Rank 114,096 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 3 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

This package reads your JSDoc-annotated source code on NextJS API route and generates an OpenAPI (Swagger) specification.

Welcome to next-swagger-doc πŸ‘‹

All Contributors

Version Downloads/week Prerequisite Documentation License: MIT Twitter: jellydn

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

🏠 Homepage

✨ Demo

Prerequisites

  • nextjs >= 9

Motivation

This package reads your JSDoc-annotated source code on NextJS API route and generates an OpenAPI (Swagger) specification.

nextjs + swagger-jsdoc = next-swagger-doc

Install

yarn add next-swagger-doc

Usage #1: next-swagger-doc with Next.js 13

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.

1. Create Swagger Spec

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.

import { createSwaggerSpec } from 'next-swagger-doc';

export const getApiDocs = async () => {
  const spec = createSwaggerSpec({
    apiFolder: 'app/api', // define api folder under app folder
    definition: {
      openapi: '3.0.0',
      info: {
        title: 'Next Swagger API Example',
        version: '1.0',
      },
      components: {
        securitySchemes: {
          BearerAuth: {
            type: 'http',
            scheme: 'bearer',
            bearerFormat: 'JWT',
          },
        },
      },
      security: [],
    },
  });
  return spec;
};

2. Create Swagger UI Component

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.

'use client';

import SwaggerUI from 'swagger-ui-react';
import 'swagger-ui-react/swagger-ui.css';

type Props = {
  spec: Record<string, any>,
};

function ReactSwagger({ spec }: Props) {
  return <SwaggerUI spec={spec} />;
}

export default ReactSwagger;

3. Create API Documentation Page

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.

import { getApiDocs } from '@/lib/swagger';
import ReactSwagger from './react-swagger';

export default async function IndexPage() {
  const spec = await getApiDocs();
  return (
    <section className="container">
      <ReactSwagger spec={spec} />
    </section>
  );
}

4. Add Swagger Comment to API Route

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.

/**
 * @swagger
 * /api/hello:
 *   get:
 *     description: Returns the hello world
 *     responses:
 *       200:
 *         description: Hello World!
 */
export async function GET(_request: Request) {
  // Do whatever you want
  return new Response('Hello World!', {
    status: 200,
  });
}

Now, navigate to localhost:3000/api-doc (or wherever you host your Next.js application), and you should see the swagger UI.

https://gyazo.com/6bfa919c4969b000615df6bb9cabcd02.gif

Usage #2: Create an single API document

yarn add next-swagger-doc swagger-ui-react
  • Create an live swagger page, e.g: pages/api-doc.tsx
import { GetStaticProps, InferGetStaticPropsType } from 'next';
import { createSwaggerSpec } from 'next-swagger-doc';
import dynamic from 'next/dynamic';
import 'swagger-ui-react/swagger-ui.css';

const SwaggerUI = dynamic<{
  spec: any;
}>(import('swagger-ui-react'), { ssr: false });

function ApiDoc({ spec }: InferGetStaticPropsType<typeof getStaticProps>) {
  return <SwaggerUI spec={spec} />;
}

export const getStaticProps: GetStaticProps = async () => {
  const spec: Record<string, any> = createSwaggerSpec({
    definition: {
      openapi: '3.0.0',
      info: {
        title: 'Next Swagger API Example',
        version: '1.0',
      },
    },
  });

  return {
    props: {
      spec,
    },
  };
};

export default ApiDoc;

https://gyazo.com/af250bab0d07f931c596ebc8c955ae2e.gif

Usage #3: Use NextJS API route to create Swagger JSON spec

  • Step 1: Create an api route on nextjs, e.g: pages/api/doc.ts
import { withSwagger } from 'next-swagger-doc';

const swaggerHandler = withSwagger({
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'NextJS Swagger',
      version: '0.1.0',
    },
  },
  apiFolder: 'pages/api',
});
export default swaggerHandler();
  • Step 2: Add JSdoc to any NextJS API routes, for example: pages/api/hello.ts
import { NextApiRequest, NextApiResponse } from 'next';

/**
 * @swagger
 * /api/hello:
 *   get:
 *     description: Returns the hello world
 *     responses:
 *       200:
 *         description: hello world
 */
const handler = (_req: NextApiRequest, res: NextApiResponse) => {
  res.status(200).json({
    result: 'hello world',
  });
};

export default handler;
  • Step 3: Access the Swagger API doc

https://gyazo.com/0bcf45f0e15778a5cb851b40526324f3.gif

Usage #4: Generate Swagger file from CLI

  • Step 1: create a JSON config file as next-swagger-doc.json
{
  "apiFolder": "pages/api",
  "schemaFolders": ["models"],
  "definition": {
    "openapi": "3.0.0",
    "info": {
      "title": "Next Swagger API Example",
      "version": "1.0"
    }
  }
}
  • Step 2: run cli for generating swagger file
yarn next-swagger-doc-cli next-swagger-doc.json

Run example app

gh repo clone jellydn/next-swagger-doc
cd example
yarn install
yarn dev

Then open http://localhost:3000/api-doc or http://localhost:3000/ on your browser ./example-screenshot.png

Linter

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:

yarn add -D eslint-plugin-jsdoc

Create the custom rule in your eslint configuration file:

{
    //...your configuration
    "overrides": [
        //...your overrides
        {
            // Force the setting of a swagger description on each api endpoint
            "files": ["pages/api/**/*.ts"],
            "plugins": ["jsdoc"],
            "rules": {
                "jsdoc/no-missing-syntax": [
                "error",
                {
                    "contexts": [
                    {
                        "comment": "JsdocBlock:has(JsdocTag[tag=swagger])",
                        "context": "any",
                        "message": "@swagger documentation is required on each API. Check this out for syntax info: https://github.com/jellydn/next-swagger-doc"
                    }
                    ]
                }
            ]
        }
    ]
}

Author

πŸ‘€ Huynh Duc Dung

Stargazers

Stargazers repo roster for @jellydn/next-swagger-doc

Show your support

kofi paypal buymeacoffee

Give a ⭐️ if this project helped you!

Contributors ✨

Thanks goes to these wonderful people (emoji key):

Dung Duc Huynh (Kaka)
Dung Duc Huynh (Kaka)

πŸ’» πŸ“–
tmirkovic
tmirkovic

πŸ“–
Matthew Holloway
Matthew Holloway

πŸ’»
leventemihaly
leventemihaly

πŸ“–
PAHRIZAL MA'RUP
PAHRIZAL MA'RUP

πŸ’»
Aris
Aris

πŸ“–
Valerio Ageno
Valerio Ageno

πŸ“–
cachho
cachho

πŸ’»

This project follows the all-contributors specification. Contributions of any kind welcome!

More Repositories

1

typescript-tips

A curated list of awesome πŸ”₯ TypeScript Tips πŸ”₯
403
star
2

dapp-starter

Opinionated Dapp Starter Template provides a solid foundation for building Ethereum-based applications. It incorporates various tools and frameworks such as React, Next.js, Hardhat, TypeChain, web3-react, daisyUI Tailwind CSS Components, and OpenZeppelin.
TypeScript
309
star
3

zed-101-setup

Your ultimate guide to setting up Zed with Vim mode, tailored settings, and key bindings for a seamless coding experience
TypeScript
247
star
4

nft-app

How to create your own NFT and mint NFT token
TypeScript
210
star
5

next-app-starter

Another awesome starter for your app base on nextjs + tailwind + react-query + zod + react-hook-form + next-auth + jotai
TypeScript
176
star
6

hurl.nvim

Hurl.nvim is a Neovim plugin designed to run HTTP requests directly from `.hurl` files. Elevate your API development workflow by executing and viewing responses without leaving your editor.
Lua
156
star
7

dapp-token-ico

How to do your first ICO smart contract
TypeScript
124
star
8

fastify-starter

Fastify starter template support RestAPI with Swagger and Graphql
TypeScript
108
star
9

gpt4free-demo

A slow guide on setting up a free OpenAI GPT-4 API on your local machine.
TypeScript
106
star
10

lazy-nvim-ide

My πŸ’€ LazyVim IDE config for Neovim
Lua
93
star
11

elysia-demo-app

A Real-World Example Using Bun, Docker, and Fly.io πŸš€
TypeScript
70
star
12

awesome-typesafe

A curated list of awesome πŸ”₯ TypeScript Typesafe LibrariesπŸ”₯
69
star
13

grpc-demo-monorepo

NodeJS/Go + gRPC/Connect + NextJS
TypeScript
51
star
14

react-dapp

Dapp Example with ERC20 Token and Simple Greeter Contract. Built with Hardhat + EthersJs + React + TypeScript.
TypeScript
47
star
15

next-validations

NextJS API Validations, support Zod, Yup, Fastest-Validator, Joi, and more
TypeScript
42
star
16

gpt4all-cli

By utilizing GPT4All-CLI, developers can effortlessly tap into the power of GPT4All and LLaMa without delving into the library's intricacies. Simply install the CLI tool, and you're prepared to explore the fascinating world of large language models directly from your command line!
TypeScript
33
star
17

new-web-app

Frontend app generator, built on top vitejs
TypeScript
29
star
18

twt-dl-cli

The easiest way to download any Twitter video from CLI
TypeScript
28
star
19

ts-inlay-hints

A guide on how to utilize TypeScript inlay hints in VS Code / Neovim with the TypeScript Language Server
TypeScript
27
star
20

typecheck.nvim

A Neovim plugin for seamless TypeScript type checking.
Lua
27
star
21

nvim-for-webdev

Starter Template for Web Developers
Lua
26
star
22

quick-code-runner.nvim

A simple and efficient code runner for Neovim.
Lua
22
star
23

trpc-demo

Monorepo for tRPC v9 Demo Apps
TypeScript
19
star
24

my-nvim-ide

My personal neovim configuration.
Lua
17
star
25

llama2-personal-ai

Build your personal AI with the llama2 model πŸ€–. Easy to use, and perfect for your development needs!
16
star
26

moleculer-typescript-template

This is a Moleculer-based microservices project
TypeScript
15
star
27

spinner.nvim

spinner.nvim is a single file, no-dependency plugin for Neovim
Lua
14
star
28

my-note.nvim

MyNote is a Neovim plugin that allows you to take notes in a floating window
Lua
13
star
29

auto-testgen-nodejs

How to use AI to generate unit tests
TypeScript
13
star
30

learn-nextjs14-dashboard

Learn NextJs 14 App
TypeScript
13
star
31

express-vercel-starter

Express.js v5 starter is a boilerplate for building and deploying Express.js applications to Vercel.
TypeScript
12
star
32

thirdweb-foundry-starter

Third Web Foundry Stater Template
Solidity
12
star
33

playwright-crawler-demo

This template is a production ready boilerplate for developing with `PlaywrightCrawler`. Use this to bootstrap your projects using the most up-to-date code.
Dockerfile
11
star
34

learn-vim-with-vscode

This project aims to guide you through setting up and learning Vim within Visual Studio Code using the VSCodeVim and VSCode-Neovim extensions.
Lua
10
star
35

modern-python-2024-demo

Modern development with Python in 2024
Python
10
star
36

cspell-tool

Keep your project's spelling in check with cspell-tool.
TypeScript
8
star
37

react-tips-2022-demo

Tips for ReactJs in 2022
TypeScript
8
star
38

mailwind-demo

Use Tailwind CSS to design HTML emails.
JavaScript
7
star
39

biome-interactive

Simple interactive to install biome to your project. Migrate from ESLint and Prettier with a single command
Go
7
star
40

vite-react-seo-demo

Simple SEO implement with React + React-Snap
TypeScript
7
star
41

svelte-kit-demo

Simple setup with Svelte-kit with tailwind,graphql, and deployment to Vercel/Firebase
Svelte
7
star
42

github-action-locally

How to run GitHub Action locally with act.
TypeScript
7
star
43

promise-should-be-fun

Collection of exercises designed to practice and improve your skills with async programming in JavaScript.
TypeScript
7
star
44

tx-revert-reason

Get the revert reason from an Ethereum transaction hash
TypeScript
6
star
45

ws-sockette

The little WebSocket wrapper for nodejs
TypeScript
5
star
46

vscode-like-pro

Make your VSCode Awesome! Minimalist, Productive, and Performance.
Lua
5
star
47

eslint-config-productsway

Enhance your code quality with XO's ESLint config, further augmented with TypeScript and Prettier support.
JavaScript
5
star
48

nvim-ide

Personal IDE config for Neovim
Lua
5
star
49

summary-chatbot-demo

πŸ€– Build an intelligent Summary ChatBot with AI technologies. Simplify content extraction and make summarisation easy.
TypeScript
5
star
50

moleculer-connect

A command-line interface for connecting to Moleculer microservices
TypeScript
5
star
51

wallet-connect-app

The best way to connect a wallet
TypeScript
5
star
52

use-wait-for-transaction-hash

Simple hook for getting transaction status from the ETH network.
TypeScript
5
star
53

vite-react-recoil

Simple demo for react + recoil + react-hook-form
TypeScript
5
star
54

learn-tdd-with-katas

a monorepo that demonstrates Test-Driven Development (TDD) using Turbo, pnpm, Moleculer (a microservices framework), and TypeORM (an ORM for TypeScript and JavaScript)
TypeScript
5
star
55

platformatic-starter

Platformatic starter template
TypeScript
4
star
56

typescript-starter

Typescript starter project
TypeScript
4
star
57

chatbot-starter-app

Develop chatbot with zero configuration using typescript
TypeScript
4
star
58

react-18-demo

TypeScript
4
star
59

hono-minimal-app

This is a minimal project with honojs
TypeScript
4
star
60

itman-channel

My weekly video on IT Man Channel
TypeScript
4
star
61

edge-network-demo

Edge Network Demo
TypeScript
4
star
62

react-email-starter

React Email Starter
TypeScript
4
star
63

copilot-tips

Learn how to improve your code with Github Copilot
JavaScript
4
star
64

typechain-demo-app

How to use Typechain with Ethers V5
TypeScript
4
star
65

bnb-testnet-auto-faucet

TypeScript
4
star
66

next-demo-app

The real example app with nextjs (NextJS + Tailwind + Form + Data fetching ...)
TypeScript
4
star
67

hyperstack-demo-app

HTML
4
star
68

huma-demo

A modern, simple, fast & flexible micro framework for building HTTP REST/RPC APIs in Golang backed by OpenAPI 3 and JSON Schema.
Go
4
star
69

hapi-demo

A simple Hapi server for demonstration purposes, designed to work with Hurl for testing HTTP requests.
TypeScript
3
star
70

lens-demo-app

Lens Demo App
TypeScript
3
star
71

demo-chat-bot

Develop chatbots with zero configuration using typescript
TypeScript
3
star
72

tempora-saga-demo

Saga pattern demo
TypeScript
3
star
73

go-react-blog-app

TypeScript
3
star
74

arch-linux-on-m2

How to install Arch Linux on a Macbook Pro M2
Shell
3
star
75

waku-rsc-async-demo

TypeScript
3
star
76

untypeable-wretch-demo

This is a demo project that showcases how to use the Untypeable library with Wretch to make API requests to JsonPlaceholder and display the data on a webpage.
TypeScript
3
star
77

eth-cli

How to test smart contract in CLI like a PRO
Solidity
3
star
78

react-18-migration-demo

How to Upgrade to React 18
TypeScript
3
star
79

fresh-deno-app

A fresh (deno) app
TypeScript
3
star
80

dotfiles

A set of vim, zsh, git configuration files and tools.
Shell
3
star
81

sharing-btn

Sharing Button - Web Component using Stencil
TypeScript
3
star
82

remix-spa-demo

How to use Biome with Bun.js and Remix to create a Single Page Application
TypeScript
3
star
83

nestjs-7day-journey

NestJourney: Embark on a 7-day journey through the realm of Nest.js. This journey is designed for experienced developers looking to boost their Node.js skills with Nest.js.
TypeScript
3
star
84

hono-sst-demo

Hono on Cloudflare with SST
TypeScript
3
star
85

flutter-apprentice

Dart
2
star
86

typescript-mini-starter

A streamlined and efficient TypeScript starter kit, supporting both ESM and CJS, for quick and versatile project setups.
TypeScript
2
star
87

better-async-demo

Easy to handle the async await without try catch
TypeScript
2
star
88

modern-nodejs-2024

Master the 2024 Node.js Development: Key Updates & Features from 18 to 22
2
star
89

deno-pkg-starter

Publish your Typescript library to NPM and Deno
TypeScript
2
star
90

react-lib-starter

React Lib Starter Template
TypeScript
2
star
91

floating-promise-demo

How to handle floating promises in JavaScript
TypeScript
2
star
92

stepci-demo

A slow guide to set up continuous integration for a Fastify using StepCI.
TypeScript
2
star
93

jellydn

TypeScript
2
star
94

ts-pattern-demo-app

A state reducer example with ts-pattern with React App
TypeScript
2
star
95

ethers-bignumber-demo

How to convert to BigNumber's ethers.js without error.
TypeScript
2
star
96

indie-stack-simple-notes

Remix Indie Stack - Simple notes app
TypeScript
2
star
97

wattpm-express-demo

Watt Quick Start
TypeScript
2
star
98

i18n-react-app

TypeScript
2
star
99

pkg-cli-simple-app

Demo pkg app
TypeScript
2
star
100

StickerSmash

A hands-on demo project utilizing Expo for app development.
TypeScript
2
star