• Stars
    star
    375
  • Rank 110,366 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created about 3 years ago
  • Updated 25 days 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 πŸ”₯
385
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

nft-app

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

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
5

dapp-token-ico

How to do your first ICO smart contract
TypeScript
124
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
91
star
7

fastify-starter

Fastify starter template support RestAPI with Swagger and Graphql
TypeScript
87
star
8

gpt4free-demo

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

lazy-nvim-ide

My πŸ’€ LazyVim IDE config for Neovim
Lua
56
star
10

awesome-typesafe

A curated list of awesome πŸ”₯ TypeScript Typesafe LibrariesπŸ”₯
49
star
11

react-dapp

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

next-validations

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

grpc-demo-monorepo

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

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
15

new-web-app

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

elysia-demo-app

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

nvim-for-webdev

Starter Template for Web Developers
Lua
25
star
18

twt-dl-cli

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

llama2-personal-ai

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

trpc-demo

Monorepo for tRPC v9 Demo Apps
TypeScript
16
star
21

moleculer-typescript-template

This is a Moleculer-based microservices project
TypeScript
12
star
22

auto-testgen-nodejs

How to use AI to generate unit tests
TypeScript
11
star
23

thirdweb-foundry-starter

Third Web Foundry Stater Template
Solidity
11
star
24

ts-inlay-hints

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

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
10
star
26

learn-nextjs14-dashboard

Learn NextJs 14 App
TypeScript
9
star
27

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
8
star
28

react-tips-2022-demo

Tips for ReactJs in 2022
TypeScript
8
star
29

mailwind-demo

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

vite-react-seo-demo

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

svelte-kit-demo

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

promise-should-be-fun

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

my-note.nvim

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

tx-revert-reason

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

github-action-locally

How to run GitHub Action locally with act.
TypeScript
6
star
36

quick-code-runner.nvim

A simple and efficient code runner for Neovim.
Lua
6
star
37

ws-sockette

The little WebSocket wrapper for nodejs
TypeScript
5
star
38

eslint-config-productsway

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

nvim-ide

Personal IDE config for Neovim
Lua
5
star
40

summary-chatbot-demo

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

cspell-tool

Keep your project's spelling in check with cspell-tool.
TypeScript
5
star
42

express-vercel-starter

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

wallet-connect-app

The best way to connect a wallet
TypeScript
5
star
44

vite-react-recoil

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

use-wait-for-transaction-hash

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

platformatic-starter

Platformatic starter template
TypeScript
4
star
47

hono-minimal-app

This is a minimal project with honojs
TypeScript
4
star
48

react-18-demo

TypeScript
4
star
49

edge-network-demo

Edge Network Demo
TypeScript
4
star
50

itman-channel

My weekly video on IT Man Channel
TypeScript
4
star
51

react-email-starter

React Email Starter
TypeScript
4
star
52

copilot-tips

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

typechain-demo-app

How to use Typechain with Ethers V5
TypeScript
4
star
54

bnb-testnet-auto-faucet

TypeScript
4
star
55

next-demo-app

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

hyperstack-demo-app

HTML
4
star
57

modern-python-2024-demo

Modern development with Python in 2024
Python
4
star
58

lens-demo-app

Lens Demo App
TypeScript
3
star
59

demo-chat-bot

Develop chatbots with zero configuration using typescript
TypeScript
3
star
60

typescript-starter

Typescript starter project
TypeScript
3
star
61

chatbot-starter-app

Develop chatbot with zero configuration using typescript
TypeScript
3
star
62

go-react-blog-app

TypeScript
3
star
63

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
64

eth-cli

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

react-18-migration-demo

How to Upgrade to React 18
TypeScript
3
star
66

fresh-deno-app

A fresh (deno) app
TypeScript
3
star
67

dotfiles

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

typecheck.nvim

A Neovim plugin for seamless TypeScript type checking.
Lua
3
star
69

sharing-btn

Sharing Button - Web Component using Stencil
TypeScript
3
star
70

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
3
star
71

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
72

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
3
star
73

hapi-demo

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

flutter-apprentice

Dart
2
star
75

typescript-mini-starter

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

better-async-demo

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

ts-pattern-demo-app

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

deno-pkg-starter

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

moleculer-connect

A command-line interface for connecting to Moleculer microservices
TypeScript
2
star
80

react-lib-starter

React Lib Starter Template
TypeScript
2
star
81

waku-rsc-async-demo

TypeScript
2
star
82

floating-promise-demo

How to handle floating promises in JavaScript
TypeScript
2
star
83

stepci-demo

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

jellydn

TypeScript
2
star
85

justext

Program jusText is a tool for removing boilerplate content, such as navigation links, headers, and footers from HTML pages.
JavaScript
2
star
86

ethers-bignumber-demo

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

indie-stack-simple-notes

Remix Indie Stack - Simple notes app
TypeScript
2
star
88

i18n-react-app

TypeScript
2
star
89

pkg-cli-simple-app

Demo pkg app
TypeScript
2
star
90

remix-spa-demo

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

spinner.nvim

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

firebolt-grit-demo

Quickly build high performance, efficient, full-stack apps on the web.
JavaScript
2
star
93

encore-demo-app

Encore Demo App
Go
1
star
94

laravel-demo-app

Exploring the cutting edge of PHP development on MacOSX in 2023
PHP
1
star
95

xata-astro

Astro Blog with Xata
Astro
1
star
96

hello-near-app

JavaScript
1
star
97

bun-dx-tips

Embark on a streamlined journey with Bun, unraveling a collection of simple yet impactful tips to elevate your development experience
TypeScript
1
star
98

blog

My personal blog
TypeScript
1
star
99

react-users-crud-demo

Simple SPA for users management with ReactJS
JavaScript
1
star
100

preact-signal-demo

Simple demo with Preact Signal for react app
TypeScript
1
star