Giter Site home page Giter Site logo

jellydn / next-swagger-doc Goto Github PK

View Code? Open in Web Editor NEW
394.0 4.0 31.0 8.7 MB

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

Home Page: https://next-swagger-doc-demo.productsway.com/api-doc

License: MIT License

TypeScript 100.00%
nextjs swagger next-swagger next-swagger-doc hacktoberfest

next-swagger-doc's Introduction

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

Demo

Prerequisites

  • Nextjs >= 9
  • Node >= 18

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

Generate a new file named app/api-doc/react-swagger.tsx. In this file, create and export a React component that utilizes the swagger-ui-react library to render the Swagger UI according to the provided specification.

For demonstration purposes, here is an example using swagger-ui-react

Feel free to employ any alternative swagger UI library, such as stoplightio/elements. I have added an example using this library in the example folder.

'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({
    apiFolder: 'pages/api' // or 'src/pages/api',
    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 examples/next14-app
pnpm install
pnm run 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"
                    }
                    ]
                }
            ]
        }
    ]
}

Pre-commit hook

This project uses pre-commit to enforce code quality. To install pre-commit hooks, run:

pre-commit install

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!

next-swagger-doc's People

Contributors

aamorozov avatar ariskk avatar cachho avatar dependabot[bot] avatar eyu-dev avatar jellydn avatar leventemihaly avatar pahrizal avatar renovate-bot avatar renovate[bot] avatar tmirkovic avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

next-swagger-doc's Issues

Compatibility issues with NodeJS 16+ (version 19.7.0 / 16.19.1) on Windows, Ubuntu, and Heroku

Describe the bug

Hello,

I encountered some issues with your package that resulted in problems for my project. Specifically, there seem to be some implicit dependencies that aren't working correctly. While the previous version of the package worked somewhat, I've noticed that tree-sitter no longer compiles on NodeJS 18+.

I'm also seeing some warnings that appear to be related to your package or swagger-ui-react, and they don't show up when your package isn't included.

Thank you for your attention to this matter.

$ yarn add next-swagger-doc swagger-ui-react
➤ YN0000: ┌ Resolution step
➤ YN0061: │ querystring@npm:0.2.0 is deprecated: The querystring API is considered Legacy. new code should use the
URLSearchParams API instead.
➤ YN0032: │ @swagger-api/apidom-parser-adapter-json@npm:0.69.0: Implicit dependencies on node-gyp are discouraged
➤ YN0032: │ tree-sitter-json@npm:0.20.0: Implicit dependencies on node-gyp are discouraged
➤ YN0032: │ tree-sitter@npm:0.20.1: Implicit dependencies on node-gyp are discouraged
➤ YN0032: │ @swagger-api/apidom-parser-adapter-yaml-1-2@npm:0.69.0: Implicit dependencies on node-gyp are discourag
ed
➤ YN0032: │ tree-sitter-yaml@npm:0.5.0: Implicit dependencies on node-gyp are discouraged
➤ YN0002: │ swagger-parser@npm:10.0.2 doesn't provide openapi-types (p8111f), requested by @apidevtools/swagger-par
ser
➤ YN0000: │ Some peer dependencies are incorrectly met; run yarn explain peer-requirements <hash> for details, wher
e <hash> is the six-letter p-prefixed code
➤ YN0000: └ Completed in 1s 449ms
➤ YN0000: ┌ Fetch step
➤ YN0013: │ prismjs@npm:1.29.0 can't be found in the cache and will be fetched from the remote registry
➤ YN0013: │ react-redux@npm:7.2.9 can't be found in the cache and will be fetched from the remote registry
➤ YN0013: │ traverse@npm:0.6.7 can't be found in the cache and will be fetched from the remote registry
➤ YN0013: │ validator@npm:13.9.0 can't be found in the cache and will be fetched from the remote registry
➤ YN0013: │ web-streams-polyfill@npm:4.0.0-beta.3 can't be found in the cache and will be fetched from the remote
➤ YN0000: └ Completed in 0s 479ms
➤ YN0000: ┌ Link step
➤ YN0007: │ core-js-pure@npm:3.29.0 must be built because it never has been before or the last one failed
➤ YN0007: │ tree-sitter-json@npm:0.20.0 must be built because it never has been before or the last one failed
➤ YN0007: │ tree-sitter@npm:0.20.1 must be built because it never has been before or the last one failed
➤ YN0007: │ tree-sitter-yaml@npm:0.5.0 must be built because it never has been before or the last one failed
➤ YN0009: │ tree-sitter@npm:0.20.1 couldn't be built successfully (exit code 1, logs can be found here: \Temp\xfs-6bfa80e4\build.log)
➤ YN0000: └ Completed in 11s 476ms
➤ YN0000: Done with warnings in 13s 531ms

And for completeness, a yarn install without these packages:

$ yarn remove next-swagger-doc swagger-ui-react && yarn install
➤ YN0000: ┌ Resolution step
➤ YN0000: └ Completed
➤ YN0000: ┌ Fetch step
➤ YN0000: └ Completed in 0s 283ms
➤ YN0000: ┌ Link step
➤ YN0000: └ Completed in 0s 290ms
➤ YN0000: Done in 0s 775ms

Yes, I have already tried nuking node_modules and yarn.lock to no avail.

Reproduction

yarn add next-swagger-doc swagger-ui-react

System Info

System:
    OS: Windows 10 10.0.19045
    CPU: (32) x64 AMD Ryzen 9 5950X 16-Core Processor
    Memory: 27.14 GB / 63.92 GB
  Binaries:
    Node: 19.7.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 4.0.0-rc.37 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
    npm: 9.5.0 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Spartan (44.19041.1266.0)

---

  System:
    OS: Linux 4.4 Ubuntu 18.04.6 LTS (Bionic Beaver)
    CPU: (8) x64 unknown
    Memory: 661.32 MB / 1.00 GB
    Shell: 4.4.20 - /bin/bash
  Binaries:
    Node: 16.19.1 - /layers/heroku_nodejs-engine/nodejs/bin/node
    Yarn: 4.0.0-rc.37 - /layers/heroku_nodejs-engine/yarn/bin/yarn
    npm: 8.19.3 - /layers/heroku_nodejs-engine/nodejs/bin/npm

Used Package Manager

yarn

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Swagger Specs Never Read

Describe the bug

The api swagger docs are never read, so there is no api information generated. To recreate the repro:

  1. npx create-next-app
  2. pnpm i next-swagger-doc swagger-ui-react
  3. follow the instructions here: https://www.npmjs.com/package/next-swagger-doc

I tried to identify the issue by piecemealing elements from the next 13/14 examples, but couldn't identify the root cause.

Reproduction

https://github.com/jersmart/next-swagger-doc-repro

System Info

System:
    OS: Linux 5.15 Ubuntu 22.04.2 LTS 22.04.2 LTS (Jammy Jellyfish)
    CPU: (16) x64 Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz
    Memory: 5.68 GB / 15.59 GB
    Container: Yes
    Shell: 5.1.16 - /bin/bash
  Binaries:
    Node: 20.3.1 - ~/.nvm/versions/node/v20.3.1/bin/node
    npm: 9.6.7 - ~/.nvm/versions/node/v20.3.1/bin/npm
    pnpm: 8.6.3 - ~/.nvm/versions/node/v20.3.1/bin/pnpm

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Error after upgrading to [email protected]

Hey!

Really love this project, you can see it in production here for the habit tracking web app I've been working on in my off time!

You can see my code for the documentation page generation here

Currently I'm starting to look at upgrading my application to [email protected] and I noticed that when I go to documentation page after upgrading versions I get the following error

./node_modules/swagger-ui-react/swagger-ui.js:2:305499
Module not found: Can't resolve 'isarray'

Import trace for requested module:
./node_modules/swagger-ui-react/index.js
./pages/documentation.tsx

https://nextjs.org/docs/messages/module-not-found

This reads like a problem in swagger-ui-react so not sure if there's anything to do here but I figured I'd open up this issue to start getting the ball rolling on next@12 support!

channels unevaluated property makes my openapi validation fail.

Hello @jellydn Super awesome work, it's been a pleasure to be able to add our swagger docs to our codebase, using your plugin.

I'm having a weird issue, and I'm not sure where it's coming from, but I thought it would be worth to ask here.

When I want to use my openapi spec elswhere, all external validations fail due to an extra "channels": {}, value that my openapi spec has, I've no idea where it's coming from as I'm not adding it that I know of.

Any ideas what I might be missing? This is my first time using OpenAPI and I already had to learn between differences between v2 and v3, but I can't find nothing about this "channels" property anywhere on google/stack overflow/openapi spec repo

Any help much appreciated!

Best regards and have a nice weekend,
Agusti

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/codeql-analysis.yml
  • actions/checkout v4
  • github/codeql-action v3
  • github/codeql-action v3
  • github/codeql-action v3
.github/workflows/codesee-arch-diagram.yml
  • Codesee-io/codesee-action v2
npm
package.json
  • @types/swagger-jsdoc 6.0.4
  • cleye 1.3.2
  • isarray 2.0.5
  • swagger-jsdoc 6.2.8
  • @biomejs/biome 1.7.3
  • @skypack/package-check 0.2.2
  • @types/node 20.12.12
  • @vitest/coverage-v8 1.6.0
  • @vitest/ui 1.6.0
  • all-contributors-cli 6.26.1
  • c8 9.1.0
  • next 14.2.3
  • pkgroll 2.0.2
  • size-limit 11.1.3
  • sort-package-json 2.10.0
  • tslib 2.6.2
  • typedoc 0.25.13
  • typescript 5.4.5
  • vite 5.2.11
  • vitest 1.6.0
  • next >=9
  • node >=18
  • pnpm 9.1.1
nvm
.nvmrc

  • Check this box to trigger a request for Renovate to run again on this repository

Minor problem in Documentation causes "Error: error: Expected '>', got 'spec'" for SwaggerUI component in next.js

I just started with the example and created a file "api-doc.ts" and copied the code from the npm page. This causes the following problem:

Error: error: Expected '>', got 'spec'
 
  |
8 |   return <SwaggerUI spec={ spec } />
  |                     ^^^^

Caused by:
    0: failed to process js file
    1: Syntax Error

After a little googling I found out that the file should be called "api-doc.tsx" (using the extension "tsx" not "ts") and then it will compile.

Issue when using different directory such as src

Bug descrition

#When default root path is set to src

"paths": {
      "@/*": [
        "./src/*"
      ]
    },

Swagger does not load the api routes even when annotated but when i move my code out of src directory then swagger does display

Reproduction

use src directory as main file directory for the apis

System Info

macos ventura 13.2

Used Package Manager

npm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Example or Docs required to explain how to specify params?

Discussed in https://github.com/jellydn/next-swagger-doc/discussions/527

Originally posted by oespn November 3, 2022
I'm playing with a trivial example where there is a single param of the 'id' of the person.

If I use the path template in the open api spec v3 https://swagger.io/docs/specification/paths-and-operations/ the swagger docs won't generate.

*     parameters:
*       - in: path
*         name: id
*         type: integer
*         required: true
*         description: Numeric ID of the person to get.

I've fiddled a little and can get the {id} to appear in the path but do not know how to have the lib identify the params and create the relevant front-end control or even list the name, description, type of the param.

here's my code:

/**
 * @swagger
 * /api/people/{id}:
 *   get:
 *     description: Returns the person matching Id
 *     parameters:
 *         name: id
 *         description: Numeric ID of the person to get.
 *     responses:
 *       200:
 *         description: data of Id 
 *       404: 
 *         description: Id not found.
 */
export default function personHandler(
  req: NextApiRequest,
  res: NextApiResponse<Person | ResponseError>
) {
  const { query } = req
  const { id } = query
  const filtered = people.filter((p) => p.id === id)

  // User with id exists
  return filtered.length > 0
    ? res.status(200).json(filtered[0])
    : res.status(404).json({ message: `User with id: ${id} not found.` })
}

Is the lib able to handle parameters? If so, how?

Error on build - Next.js 14 - TypeError: Class extends value undefined is not a constructor or null

Describe the bug

Context

I am unable to successfully build my Next.js app with next 14 and next swagger doc.

It works fine when running locally but I am unable to build locally and in the ci.

I have noticed the same thing happens when building the example next 14 app

Package versions

  • Next.js: 14.1.0
  • next-swagger-doc: 0.4.0
  • swagger-ui-react: 5.11.8
  • @types/swagger-ui-react: 4.18.3

Package Manager

yarn

Console output

yarn run v1.22.21
$ next build
▲ Next.js 14.1.0

- Environments: .env

Creating an optimized production build ...
✓ Compiled successfully

✓ Linting and checking validity of types  
 ✓ Collecting page data  
 Generating static pages (0/6) [= ]Error fetching data from Jira API: Dynamic server usage: Page couldn't be rendered statically because it used `nextUrl.searchParams`. See more info here: https://nextjs.org/docs/messages/dynamic-server-error
TypeError: Class extends value undefined is not a constructor or null
    at /Users/x/my-app/.next/server/app/api-doc/page.js:6:106284
    at /Users/x/my-app/.next/server/app/api-doc/page.js:12:320862
    at 8499 (/Users/x/my-app/.next/server/app/api-doc/page.js:12:320878)
    at t (/Users/x/my-app/.next/server/webpack-runtime.js:1:142)
    at 95728 (/Users/x/my-app/.next/server/app/api-doc/page.js:12:322350)
    at t (/Users/x/my-app/.next/server/webpack-runtime.js:1:142)
    at F (/Users/x/my-app/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:94693)
    at j (/Users/x/my-app/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:93244)
    at rP (/Users/x/my-app/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:33905)
    at nN (/Users/x/my-app/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:62423)

Error occurred prerendering page "/api-doc". Read more: https://nextjs.org/docs/messages/prerender-error

TypeError: Class extends value undefined is not a constructor or null
    at /Users/x/my-app/.next/server/app/api-doc/page.js:6:106284
    at /Users/x/my-app/.next/server/app/api-doc/page.js:12:320862
    at 8499 (/Users/x/my-app/.next/server/app/api-doc/page.js:12:320878)
    at t (/Users/x/my-app/.next/server/webpack-runtime.js:1:142)
    at 95728 (/Users/x/my-app/.next/server/app/api-doc/page.js:12:322350)
    at t (/Users/x/my-app/.next/server/webpack-runtime.js:1:142)
    at F (/Users/x/my-app/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:94693)
    at j (/Users/x/my-app/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:93244)
    at rP (/Users/x/my-app/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:33905)
    at nN (/Users/x/my-app/node_modules/next/dist/compiled/next-server/app-page.runtime.prod.js:12:62423)
✓ Generating static pages (6/6)

> Export encountered errors on following paths:

        /api-doc/page: /api-doc

error Command failed with exit code 1.

App snippets

/api-doc/page

import { getApiDocs } from "@/lib/swagger";
import { ReactSwagger } from "@/components/ReactSwagger";

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

Reproduction

run yarn build from /examples/next14-app

System Info

System:
    OS: macOS 14.3.1
    CPU: (10) arm64 Apple M1 Pro
    Memory: 107.69 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.18.0 - ~/.nvm/versions/node/v18.18.0/bin/node
    Yarn: 1.22.21 - ~/.nvm/versions/node/v18.18.0/bin/yarn
    npm: 9.8.1 - ~/.nvm/versions/node/v18.18.0/bin/npm
  Browsers:
    Chrome: 122.0.6261.129
    Safari: 17.3.1

Used Package Manager

yarn

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

add support for dynamic routing

Fantastic tool so far!

I'm able to generate documentation for dynamic routes but it doesn't seem to allow the user to substitute values for the dynamic part of the route.

For example, for the following route:

pages/api/github/[repo]/repos

The user should be able to specify the repo name.

NextJS docs for reference.

Am I missing something?

Thanks!

api doesn't load component on production

Describe the bug

Been trying option 2 (api /doc) following the docs and example and couldn't make it work and noticed on the demo is also broken https://next-swagger-doc-demo.productsway.com/api/doc schemas never get append to the json.

There is a way to make it append the schema as working on local?
Even with yarn build yarn start on local works fine only failing on vercel

Note: I saw this been reported a few times but without to much information or solution.

Reproduction

https://next-swagger-doc-demo.productsway.com/api/doc

System Info

System:
    OS: macOS 13.1
    CPU: (10) arm64 Apple M1 Max
    Memory: 8.35 GB / 64.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.15.0 - ~/.nvm/versions/node/v16.15.0/bin/node
    Yarn: 1.22.18 - ~/.nvm/versions/node/v16.15.0/bin/yarn
    npm: 8.5.5 - ~/.nvm/versions/node/v16.15.0/bin/npm
  Browsers:
    Brave Browser: 104.1.42.88
    Chrome: 109.0.5414.119
    Firefox: 106.0.2
    Safari: 16.2

Used Package Manager

yarn

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Automated doc generation

Describe the bug

Not really a bug, but I don't think it should be a necessity to specify the request url and request method (And perhaps even the possible responses) because all these are things that are available within the code itself

For example we can look at the folder path and exported module name and from there derive the available methods and api paths

Reproduction

/** * @Swagger * /api/hello: * get: * description: Returns the hello world * responses: * 200: * description: Hello World! */

System Info

/**
 * @swagger
 * /api/hello:
 *   get:
 *     description: Returns the hello world
 *     responses:
 *       200:
 *         description: Hello World!
 */

Used Package Manager

yarn

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Next13 example project running issue

Describe the bug

The example project next13-example seems to have some compatibility issues.

Accessing page http://localhost:3000/api-doc led to following issues in the console window:

warn  - ./node_modules/.pnpm/[email protected][email protected]/node_modules/swagger-jsdoc/src/utils.js
Critical dependency: the request of a dependency is an expression

Import trace for requested module:
./node_modules/.pnpm/[email protected][email protected]/node_modules/swagger-jsdoc/src/utils.js
./node_modules/.pnpm/[email protected][email protected]/node_modules/swagger-jsdoc/src/specification.js
./node_modules/.pnpm/[email protected][email protected]/node_modules/swagger-jsdoc/src/lib.js
./node_modules/.pnpm/[email protected][email protected]/node_modules/swagger-jsdoc/index.js
./node_modules/.pnpm/[email protected][email protected][email protected]/node_modules/next-swagger-doc/dist/index.cjs
./src/lib/swagger.ts
./src/app/api-doc/page.tsx

./node_modules/.pnpm/[email protected]/node_modules/node-fetch/lib/index.js
Module not found: Can't resolve 'encoding' in '/Users/hugh/ts/next-swagger-doc/examples/next13-example/node_modules/.pnpm/[email protected]/node_modules/node-fetch/lib'

Import trace for requested module:
./node_modules/.pnpm/[email protected]/node_modules/node-fetch/lib/index.js
./node_modules/.pnpm/[email protected]/node_modules/cross-fetch/dist/node-ponyfill.js
./node_modules/.pnpm/[email protected]/node_modules/cross-fetch/dist/node-polyfill.js
./node_modules/.pnpm/[email protected]/node_modules/swagger-client/es/http/index.js
./node_modules/.pnpm/[email protected]_@[email protected]_@[email protected][email protected][email protected]/node_modules/swagger-ui-react/swagger-ui-es-bundle-core.js
./node_modules/.pnpm/[email protected]_@[email protected]_@[email protected][email protected][email protected]/node_modules/swagger-ui-react/index.js
./src/app/api-doc/ReactSwagger.tsx

Reproduction

https://github.com/jellydn/next-swagger-doc/tree/main/examples/next13-example

System Info

System:
    OS: macOS 13.3.1
    CPU: (8) arm64 Apple M1
    Memory: 95.33 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.14.0 - ~/.nvm/versions/node/v18.14.0/bin/node
    Yarn: 1.22.18 - ~/.yarn/bin/yarn
    npm: 9.6.7 - ~/.nvm/versions/node/v18.14.0/bin/npm
  Browsers:
    Safari: 16.4

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Module not found: Can't resolve '#apg-lite'

Describe the bug

I have problem with module '#apg-lite'

Screenshot 2024-05-13 at 10 14 01

we need delete '#'

Reproduction

we need delete '#'

System Info

-

Used Package Manager

npm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Example must be updated

@jellydn Because of newest swagger-ui-react, this example must be updated.

Otherwise current example produces this error.

This code works with the newest swagger-ui-react:

import { GetStaticProps, InferGetStaticPropsType } from 'next';
import dynamic from "next/dynamic";
import { createSwaggerSpec } from 'next-swagger-doc';
import 'swagger-ui-react/swagger-ui.css';

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

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

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

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

export default ApiDoc;

Swagger annotations $ref as string

Describe the bug

image

When trying to use $ref to point to an external schema json, the definition is only returned as just "string". It's not able to resolve the path to the json it seems. 'Could not resolve reference: Tried to resolve a relative URL, without having a basePath.'

/**
 * @swagger
 * /api/example:
 *   get:
 *     description: Example description
 *     responses:
 *       200:
 *         description: Success
 *         content:
 *            application/json:
 *             schema:
 *               $ref: schemas.json#/definitions/AnExampleDefinition
 */

External schema:

{
    "$ref": "#/definitions/AnExampleDefinition",
    "$schema": "http://json-schema.org/draft-07/schema#",
    "definitions": {
        "AnExampleDefinition": {
            "additionalProperties": false,
            "properties": {
                "isThisPossible": {
                    "type": "boolean"
                }
            },
            "required": ["isThisPossible"],
            "type": "object"
        }
    }
}

Any help appreciated

Reproduction

Complete

System Info

System:
    OS: macOS 12.5.1
    CPU: (8) arm64 Apple M1
    Memory: 1.84 GB / 16.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.19.0 - ~/.nvm/versions/node/v16.19.0/bin/node
    npm: 8.19.3 - ~/.nvm/versions/node/v16.19.0/bin/npm
  Browsers:
    Safari: 15.6.1

Used Package Manager

npm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Error: EISDIR: illegal operation on a directory, read

Describe the bug

Using the code from the ReadME throws the following error. Tried with cli as well, getting the same error.
Operating System: Mac

image

Reproduction

yarn dev

System Info

NON

Used Package Manager

yarn

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Trying to use schemas

Hello, i'm trying to use schemas for documenting API responses, but i don't know how to fill in the example.


/**
 * @swagger
 * components:
 *   schemas:
 *     ArrayOfPolls:
 *       type: array
 *       additionalProperties:
 *         $ref: '#/components/schemas/Poll'
 *     Poll:
 *       type: object
 *       properties:
 *         pollId:
 *           type: integer
 * /api/polling/all-polls:
 *   get:
 *     tags:
 *     - "polls"
 *     description: Returns all polls
 *     produces:
 *     - "application/json"
 *     parameters:
 *     - name: "categories"
 *       in: "query"
 *       description: "Categories to filter polls by. Example 'Collateral', 'Greenlight'"
 *       required: false
 *       type: "array"
 *       items:
 *         type: "string"
 *         enum:
 *         - "Collateral"
 *         - "Greenlight"
 *         - "Governance"
 *         default: ""
 *       collectionFormat: "multi"
 *     responses:
 *       200:
 *         description: "List of polls"
 *           content:
 *             application/json:
 *               schema:
 *                 $ref: '#/components/schemas/ArrayOfPolls'
 */

This is failing for me

Support .tsx extensions in API routes

Some code bases (mine) use .tsx everywhere including API routes because

  1. Next supports .tsx API routes
  2. they use JSX for templating in API responses (e.g. ReactDOMServer.renderToString(...)), or;
  3. .ts and .tsx have slight parsing differences (e.g. <foo>bar; in ts vs bar as foo in tsx) so using .tsx everywhere can help sharing code.

Not working on Next 13

Describe the bug

Hey,
Would've loved this to work, but even with the best of tries, I couldn't get it to work.

After running yarn build, I get the following...

yarn run v1.22.19
$ next build
- info Loaded env from /Users/saadbazaz/Projects/omni-tools/.env
(node:12677) [DEP_WEBPACK_MODULE_UPDATE_HASH] DeprecationWarning: Module.updateHash: Use new ChunkGraph API
(Use `node --trace-deprecation ...` to show where the warning was created)
Failed to compile.

./node_modules/swagger-jsdoc/node_modules/yaml/browser/dist/index.js
Module parse failed: 'import' and 'export' may appear only with 'sourceType: module' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> import { d as defaultTagPrefix, _ as _typeof, a as _createClass, b as _classCallCheck, c as _defineProperty, e as _slicedToArray, Y as YAMLSemanticError, T as Type, f as defaultTags, g as YAMLWarning, h as _createForOfIteratorHelper, i as YAMLSyntaxError, C as Char, j as YAMLReferenceError, k as YAMLError } from 'swagger-jsdoc/node_modules/yaml/browser/dist/errors-2634d01a.js';
| import { P as PlainValue, D as Document$1, p as parse$1 } from 'swagger-jsdoc/node_modules/yaml/browser/dist/parse-d1ba890f.js';
| export { p as parseCST } from 'swagger-jsdoc/node_modules/yaml/browser/dist/parse-d1ba890f.js';

Import trace for requested module:
./node_modules/swagger-jsdoc/node_modules/yaml/browser/dist/index.js
./node_modules/swagger-jsdoc/node_modules/yaml/browser/index.js
./node_modules/swagger-jsdoc/src/specification.js
./node_modules/swagger-jsdoc/src/lib.js
./node_modules/swagger-jsdoc/index.js
./node_modules/next-swagger-doc/dist/index.js
./src/lib/swagger.ts
./src/app/api-doc/page.tsx


> Build failed because of webpack errors
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Reproduction

Install latest version of Next, and latest version of this lib.

System Info

System:
    OS: macOS 13.5.2
    CPU: (10) arm64 Apple M2 Pro
    Memory: 157.84 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 19.8.1 - ~/.nvm/versions/node/v19.8.1/bin/node
    Yarn: 1.22.19 - ~/.nvm/versions/node/v19.8.1/bin/yarn
    npm: 9.7.2 - ~/.nvm/versions/node/v19.8.1/bin/npm
    pnpm: 8.8.0 - ~/.nvm/versions/node/v19.8.1/bin/pnpm
  Browsers:
    Chrome: 118.0.5993.70
    Safari: 16.6


My Package JSON:

    "jsdoc": "^4.0.2",
    "next": "13.4.19",
    "next-swagger-doc": "^0.4.0",
    "swagger-ui-react": "^5.9.0",


### Used Package Manager

yarn

### Validations

- [X] Follow our [Code of Conduct](https://github.com/antfu/.github/blob/main/CODE_OF_CONDUCT.md)
- [X] Read the [Contributing Guide](https://github.com/antfu/contribute).
- [X] Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- [X] Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
- [X] The provided reproduction is a [minimal reproducible](https://stackoverflow.com/help/minimal-reproducible-example) of the bug.

A way to import from a separate file

When using this notation with decorators in comments, some APIs will have hundreds of lines of YAML only for the documentation, leaving the source code way down in the file.
Also, editing these comments (specially because of the * in each line) makes it either hard to edit (prone to human error) or require plugins and extensions in editors.

My suggestion goes like this:

/*
 * @swagger import ./.swagger
 */
export async function () {
  ...
};

In this case, there is a file .swagger right next to the source code.

Another option, perhaps

/*
 * @swagger
 * @import ../my/swagger/file.yaml
 */
export async function () {
  ...
};

`Argument of type 'Promise<typeof import("...@types/swagger-ui-react/index")>' is not assignable to parameter of type 'DynamicOptions<{ spec: any; }> | Loader<{ spec: any; }>'.

Describe the bug

I am trying to show an open API document and followed same example on the github. I am receiving this error. Do you have any idea how to fix this? Thank you.

Argument of type 'Promise<typeof import("c:/workspace/***/***/node_modules/@types/swagger-ui-react/index")>' is not assignable to parameter of type 'DynamicOptions<{ spec: any; }> | Loader<{ spec: any; }>'. Type 'Promise<typeof import("c:/workspace/***/***/node_modules/@types/swagger-ui-react/index")>' is not assignable to type 'LoaderComponent<{ spec: any; }>'. Type 'typeof import("c:/workspace/***/***/node_modules/@types/swagger-ui-react/index")' is not assignable to type 'ComponentType<{ spec: any; }> | ComponentModule<{ spec: any; }>'. Type 'typeof import("c:/workspace/***/***/node_modules/@types/swagger-ui-react/index")' is not assignable to type 'ComponentModule<{ spec: any; }>'. Types of property 'default' are incompatible. Type 'typeof SwaggerUI' is not assignable to type 'ComponentType<{ spec: any; }>'. Type 'typeof SwaggerUI' is not assignable to type 'ComponentClass<{ spec: any; }, any>'. Construct signature return types 'SwaggerUI' and 'Component<{ spec: any; }, any, any>' are incompatible. The types of 'props' are incompatible between these types. Type 'Readonly<SwaggerUIProps>' is not assignable to type 'Readonly<{ spec: any; }>'. Property 'spec' is optional in type 'Readonly<SwaggerUIProps>' but required in type 'Readonly<{ spec: any; }>'.ts(2345)

Reproduction

Followed example on github README.md

System Info

"next": "13.0.7",
"next-swagger-doc": "^0.3.6",
"swagger-ui-react": "^4.18.1",

  System:
    OS: Windows 10 10.0.22621
    CPU: (16) x64 AMD Ryzen 9 5900HX with Radeon Graphics
    Memory: 10.91 GB / 31.35 GB
  Binaries:
    Node: 16.13.0 - C:\Program Files\nodejs\node.EXE
    Yarn: 1.22.11 - ~\AppData\Roaming\npm\yarn.CMD
    npm: 8.1.0 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Edge: Spartan (44.22621.1344.0), Chromium (110.0.1587.69)
    Internet Explorer: 11.0.22621.1

Used Package Manager

yarn

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Theme | no light mode support ?

Describe the bug

so i was trying to render a API json but the generated swagger is in dark mode can I change that into light mode ?

Reproduction

import { GetStaticProps, InferGetStaticPropsType } from "next"; import { createSwaggerSpec } from "next-swagger-doc"; import dynamic from "next/dynamic"; import Sample from "../public/sample.json"; import "swagger-ui-react/swagger-ui.css"; const SwaggerUI = dynamic<{ spec: any; // @ts-ignore }>(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: Sample, }); return { props: { spec, }, }; }; export default ApiDoc;

System Info

windos 10 , 32gb , i7

Used Package Manager

pnpm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Where to keep the schema.json file in next.js project?

swagger is only able to reference the schema.json file when it is kept inside the /public folder and when I move this file to the project's root folder, I get a reference error Could not resolve reference: Could not resolve pointer: /definitions/PackagingConfigDetails does not exist in document. I tried providing the exact path in $ref in js-doc specification but still got the same error.
This is my API route handler code.

* paths:
 *   /v2/api/packaging-config:
 *     post:
 *        description: Insert API to create packaging configuration records
 *        tags:
 *            - Packaging Config
 *        requestBody:
 *          required: true
 *          content:
 *           application/json:
 *             schema:
 *               $ref: 'schemas/schema.json#/definitions/PackagingConfigDetails'
 *        responses:
 *          201:
 *            description: Record inserted successfully
 *          401:
 *            description: Unauthorized
 *          403:
 *            description: Forbidden
 *          500:
 *            description: Internal Server Error
 */

And swagger-specification code:

const SwaggerUI = dynamic(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({
    apiFolder: '/src/pages/api',
    schemaFolders: ['../../../schemas/schema.json'],
    definition: {
      openapi: '3.0.0',
      info: {
        title: 'Next Swagger API Documentation',
        description: 'Next Swagger API Documentation',
        version: '1.0'
      },
      components: {
        securitySchemes: {
          bearerAuth: {
            type: 'http',
            scheme: 'bearer',
            bearerFormat: 'JWT'
          }
        }
      },
      security: [
        { bearerAuth: [] }
      ]
    }
  })

  return {
    props: {
      spec
    }
  }
}

Any help would be greatly appreciated.
Thanks

README Documentation has a missing dependency

The command yarn add next-swagger-doc is missing the swagger-ui-react library addition and an important note for TS users to install @types/swagger-ui-react as a dev dependency, I'll create a merge request for it soon.

Full Example

Hi,

would be awesome if we have a full example making the docs, maybe something simulating the swagger example? https://petstore.swagger.io/v2/swagger.json

One question is, how to create the docs for generic data like:

  • tags
  • schemas

I´ve trying to make it here like this way:

/**
 * @swagger
 * definitions:
 *   Faker:
 *     type: 'object'
 *     properties:
 *       email:
 *         type: string 
 * tags:
 *   -
 *     name: 'faker'
 *     description: Cria valores fictícios para testes
 *     externalDocs:
 *       description: Cria valores fictícios para testes
 * 
 * /api/faker/cpf:
 *   get:
 *     tags: ['faker']
 *     description: Returns the hello world
 *     responses:
 *       200:
 *         description: hello world
 *         schema:
 *           $ref: '#/definitions/Faker'
 */

Error: No API definition provided

Hi there!!

Thanks a lot for this repo!

I´m trying to use it in a simple repo for testing, but it just gives me ' No API definition provided'

I could make the endpoint /api/doc to spit out the json but the api-doc just shows me the No API definition provided

If I use directly like this, it works

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

const ApiDoc = () => <SwaggerUI 
url="/api/doc" />

Thanks

Empty paths in rendered JSON in Production (on Vercel) but not in Dev with NextJS 14

Describe the bug

When generating the machine-readable JSON in a dev environment on a Mac I can see the full JSON including the paths with the descriptions etc:

Output of http://localhost:3000/api/v2/openapi (openapi.ts file contains the code from README.md Usage #3 Step 1)

{
  "openapi": "3.0.0",
  "info": {
    "title": "Techmap's Daily International Job Postings Export API",
    "version": "2.0.1-beta"
  },
  "paths": {
  ...
    "/api/v2/meta/jobs/statistics": {
      "get": {
        "tags": [
          "Metadata Operations"
        ],
        "summary": "Get statistics for searchable fields such as workPlace, industry, timezone etc.",
        "description": "Returns a list of statistics for the given query parameter in the `/api/v2/jobs/search` endpoint.The returned JSON is described below and mainly consist of a list of statistics with counts and percentages for a given field.<br /><h3>Notes</h3><ul><li>This endpoint is only be available for MEGA subscription plans.</li><br /><li>The results are capped at 100 values and are calculated from job postings within the last month (i.e., current date minus 1 month).</li></ul><br /><h2>Search Query Parameters</h2><h3>General Parameters</h3><ul><li>`field`: A field name used in the search endpoint `/api/v2/jobs/search` as a parameter.</li></ul><br /><br /><h2>Usage Examples</h2><p>Statistics on the workPlace field:<br />`/api/v2/meta/jobs/statistics?field=workPlace`</p><p>Statistics on the industry field:<br />`/api/v2/meta/jobs/statistics?field=industry`</p>",
        "parameters": [
          {
            "field": null,
            "in": "query",
            "name": "field",
            "required": true,
            "schema": {
              "type": "string",
              "example": "workPlace"
            },
            "description": "A field name used in the search endpoint `/api/v2/jobs/search` as a parameter."
          }
        ],
        "responses": {
          "200": {
            "description": "OK - indicating success and a correct query execution with results.<h4>Response Schema</h4>The API response provides a list of distinct field values for one field with a count of documents they are used in. Each distinct value object in the `result` array contains the following fields:<ul><li> `totalCount` (integer): The total number of jobs within the time range.<li> `docsWithValue` (integer): The number of documents with any value for that field within the time range.<li> `coverage` (double): The percentage of jobs in the time range that have any value.<li> `valueCount` (integer): The total number of values in the time range.<li> `aggregation` (object): The aggregation query we constructed and used to retrieve the distinct values.<li> `values` (array): A list of up to 100 distinct values with their data. Each distinct value object in the `result` array contains the following fields:<ul><li> `key` (string): The value found in the job documents.<li> `doc_count` (integer): The number of documents the value was found in.<li> `percentage_relative` (integer): The percentage of documents with the value relative to all documents with any value (docs_with_field).<li> `percentage_absolute` (integer): The percentage of documents with the value relative to all documents (total_doc_count).</ul></ul>"
          },
          "401": {
            "description": "Unauthorized request to API! (e.g., not trying to access API via RapidAPI)"
          },
          "403": {
            "description": "Forbidden request to API! (e.g., supscription plan to low)"
          },
          "404": {
            "description": "Not Found - due to an non-existant or invalid query parameter format (e.g., 'dateCreated')"
          },
          "405": {
            "description": "Method Not Allowed - due to unsupported HTTP Method (e.g., PUT, CONNECT, HEAD, etc.)"
          },
          "500": {
            "description": "Internal Server Error - used for general problems (i.e., a catch-all with more info in return value)"
          },
          "503": {
            "description": "Service Unavailable due to problems with our backend (e.g., the connection to our Database is interrupted)"
          }
        }
      }
    }
  },
  "components": {
    
  },
  "tags": [
    
  ]
}

However, in Production after deploying with Vercel they are not shown:

Output of https://example.com/api/v2/openapi

{
  "openapi": "3.0.0",
  "info": {
    "title": "Techmap's Daily International Job Postings Export API",
    "version": "2.0.1-beta"
  },
  "paths": {
    
  },
  "components": {
    
  },
  "tags": [
    
  ]
}

Relevant Dependencies:

"next-swagger-doc": "^0.4.0",
"openapi-types": "^12.1.3",
"swagger-parser": "^10.0.3",
"swagger-ui-react": "^5.10.5"

Btw. the generated OpenAPI docs work both in dev and production - only the generated json does not work.

I assume the problem is a different path to the API in the dev or prod environment of the nextjs application due to the deployment via Vercel. When I change pages/api/v2/ to api/v2/ in dev I get the same incomplete JSON.

I've tried to use /pages/api/v2/ and app/api/v2/ but that did not help in Production.

Any Ideas how to fix this or is this a bug?

Reproduction

Deploy to Vercel and check JSON in production

System Info

on Dev:

  System:
    OS: macOS 14.2
    CPU: (12) arm64 Apple M2 Max
    Memory: 703.17 MB / 32.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.8.1 - /opt/homebrew/bin/node
    Yarn: 1.22.19 - ~/.yarn/bin/yarn
    npm: 10.1.0 - /opt/homebrew/bin/npm
  Browsers:
    Chrome: 120.0.6099.129
    Edge: 120.0.2210.91
    Safari: 17.2

Used Package Manager

yarn

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Authorize using Bearer or OAuth2

Describe the bug

Is there way to configure swagger for different types of security?

I found a discussion here that we could configure security in the format below.

const swaggerOptions = {
  swaggerDefinition: {
    openapi: '3.0.1', // YOU NEED THIS
    info: {
      title: 'Your API title',
      version: '1.0.0',
      description: 'Your API description'
    },
    basePath: '/',
    components: {
      securitySchemes: {
        bearerAuth: {
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT',
        }
      }
    },
    security: [{
      bearerAuth: []
    }]
  },
  apis: ['/some/path.js|yml'],
};

I'm using NextJS 12 and configuring my docs using the code below.

import { withSwagger } from "next-swagger-doc";

const swaggerHandler = withSwagger({
  definition: {
    openapi: "3.0.0",
    info: {
      title: "OTLS-API",
      version: "1.39.0",
    },
  },
  apiFolder: "pages/api",
});
export default swaggerHandler();

I wasn't able to configure a security parameter in the definition. Is there an example of how I can do this?

Reproduction

Reproduction

System Info

NextJS 12
`next-swagger-doc` 0.3.6

Used Package Manager

npm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

Error with yarn build with Next 14

Describe the bug

I have the following error when I run yarn build, I ma using NextJs 14.1.0:

❯ yarn build
yarn run v1.22.19
$ node --require ./swagger-build.js ./node_modules/.bin/next build
node:internal/modules/cjs/loader:1080
  throw err;
  ^

Error: Cannot find module 'next/dist/compiled/undici'
Require stack:
- /Users/xDocuments/Projects/next-swagger-doc/examples/next14-app/swagger-build.js
- internal/preload
    at Module._resolveFilename (node:internal/modules/cjs/loader:1077:15)
    at Module._load (node:internal/modules/cjs/loader:922:27)
    at Module.require (node:internal/modules/cjs/loader:1143:19)
    at require (node:internal/modules/cjs/helpers:119:18)
    at Object.<anonymous> (/Users/x/Documents/Projects/next-swagger-doc/examples/next14-app/swagger-build.js:1:18)
    at Module._compile (node:internal/modules/cjs/loader:1256:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
    at Module.load (node:internal/modules/cjs/loader:1119:32)
    at Module._load (node:internal/modules/cjs/loader:960:12)
    at internalRequire (node:internal/modules/cjs/loader:174:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/Users/x/Documents/Projects/next-swagger-doc/examples/next14-app/swagger-build.js',
    'internal/preload'
  ]
}

Node.js v18.18.0
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Reproduction

cd examples/next14-app && yarn build

System Info

System:
    OS: macOS 14.3
    CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    Memory: 16.47 MB / 32.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 18.18.0 - ~/.n/bin/node
    Yarn: 1.22.19 - /usr/local/bin/yarn
    npm: 9.8.1 - ~/.n/bin/npm
  Browsers:
    Chrome: 121.0.6167.184
    Safari: 17.3

Used Package Manager

yarn

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

How to manage multiple HTTP methods

It is quite common to use multiple HTTP verbs for the same API route, isn't it? Is there a way to handle this and create a swagger doc for routes like below? It would be very annoying to have a separate route for each method.

/api/users

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    switch (req.method) {
        case 'GET':
            break
        case 'PUT':
            break;
        case 'POST':
            break;
        case 'DELETE':
            break;
        default:
            res.setHeader('Allow', ['GET', 'PUT', 'POST', 'DELETE'])
            res.status(405).end(`Method ${req.method} Not Allowed`)
    }
}

No operations defined in spec! error

Describe the bug

While trying to add swagger to my project I faced error:
No operations defined in spec!

image

Docs folder: pages/api.

My code looks like this:

api-doc.tsx

import { GetStaticProps, InferGetStaticPropsType } from 'next';
import { createSwaggerSpec } from 'next-swagger-doc';
import 'swagger-ui-react/swagger-ui.css';
import dynamic from 'next/dynamic';

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

const ApiDoc = ({ _spec }: InferGetStaticPropsType<typeof getStaticProps>) => {
  return <SwaggerUI url="/api/doc" />;
};

export const getStaticProps: GetStaticProps = async () => {
  const spec: Record<string, any> = createSwaggerSpec({
    definition: {
      openapi: '3.0.0',
      info: {
        title: 'Stories Api',
        version: '1.0',
      },
    },
    apiFolder: 'pages/api',
  });
  return {
    props: {
      spec,
    },
  };
};

export default ApiDoc;

And here's my spec definition in /pages/api/doc.ts:
image

Reproduction

npm run dev

System Info

System:
    OS: macOS 12.5.1
    CPU: (16) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
    Memory: 312.75 MB / 32.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.15.0 - ~/.nvm/versions/node/v16.15.0/bin/node
    Yarn: 1.22.5 - ~/.yarn/bin/yarn
    npm: 8.11.0 - ~/.nvm/versions/node/v16.15.0/bin/npm
    Watchman: 2022.03.21.00 - /usr/local/bin/watchman
  Browsers:
    Brave Browser: 91.1.26.74
    Chrome: 105.0.5195.102
    Firefox: 102.0.1
    Safari: 15.6.1
    Safari Technology Preview: 16.0

package.json: 

"next": "^12.2.5",
"next-swagger-doc": "0.3.6",
"swagger-ui-react": "4.14.0",
"typescript": "4.8.2"

Used Package Manager

npm

Validations

  • Follow our Code of Conduct
  • Read the Contributing Guide.
  • Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
  • Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
  • The provided reproduction is a minimal reproducible of the bug.

withSwagger doesn't include schema stored in non /pages/ folder to serve in vercel

following up on #26, where the fix was to include .next/server in file search. However, models defined in /models/ or non /pages/ directories are not picked up.

Demo site shows this behavior. Both have same definition that includes schema but https://next-swagger-doc-demo.productsway.com/ has no schemas while https://next-swagger-doc-demo.productsway.com/api-doc has all schemas

Fs module error while using package.

Module not found: Can't resolve 'fs'.

Capture1

i try to resolve it so i use this in NEXT config file the error resolve and it work perfectly in local

BUT WHEN DEPLOY TO SERVER IT WON'T WORK.
Capture

webpack: (config, { isServer }) => {
// Fixes npm packages that depend on fs module
if (!isServer) {
config.node = {
fs: "empty",
};
}

PLEASE PROVIDE HELP ASAP.

Error when adding a Request Body to a Post Request

Hello,

I'm having trouble with adding a request body to a post request. When I add the request body and load the Swagger docs page on my localhost, I get a console error:

Warning: Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code.

I haven't modified the default docs.ts file in /api or the api-doc.tsx shown in the repo example.

Here's my JSdoc:

/**
 * @swagger
 * /api/admin/users/new-user:
 *
 *   post:
 *     tags:
 *      - Admin
 *     description: Create a new user with a post request
 *     requestBody:
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               name:
 *                 type: string
 *     responses:
 *       201:
 *         description: User created
 *       401:
 *         description: Unauthorized
 *       500:
 *         description: Internal Server Error
 */

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.