Next.js with Swagger

Viewed 8244

Is there a way to have a swagger documentation for NEXT.js API routes? I'm using Next.js for both front-end and back-end development and I want to have a swagger documentation for the APIs I develop with Next.js.

3 Answers

You can use the following project to bootstrap the integration between Next.js and Swagger

yarn add next-swagger-doc swagger-ui-react
import { GetStaticProps, InferGetStaticPropsType } from 'next';

import { createSwaggerSpec } from 'next-swagger-doc';
import SwaggerUI from 'swagger-ui-react';
import 'swagger-ui-react/swagger-ui.css';

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

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

export default ApiDoc;

The actual definition of a Next.js API route endpoint looks like this:

/**
 * @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',
  });
};

You got to have the swagger json files or specification for the APIS and can use libs such as Swagger UI or Redoc

Using Redoc you can do a /doc/[slug].js and do dynamic fetching on the .json or yaml files for your documentation (or swagger ui)

This website: https://openapi.tools/ , has a lot of tools for React and OpenAPI in general that you can use it.

Related