Integrate Swagger documentation in Next.js
Next.js inherently doesn't support direct use with Swagger. If you insist on using it, you still have to deal with API Routes yourself? Auto-generation tools? Manually writing specs? This is practically an insult to developers. Manual annotations? This operation is literally pushing the limits of patience.
目录12 个章节
Preface
Recently, I've been using Next.js to develop my new website.
This time, I wrote some APIs.
I wondered if I could debug them using Swagger, just like when developing backends.
So I did some research.
Strictly speaking, Next.js itself does not directly support Swagger, because Swagger (more accurately, the OpenAPI specification) is a tool for backend API documentation, while Next.js is a frontend/full-stack framework.
However, if you use Next.js's API Routes (i.e., interfaces under the app/api/* directory), you can absolutely combine Swagger for API documentation. There are two common approaches:
- Use tools to automatically generate Swagger.
- Manually write an OpenAPI file.
Auto-generation
Tools can be used to automatically generate based on TypeScript types:
- tsoa
- zod-to-openapi (if using Zod validation)
- next-swagger-doc (a tool specifically wrapped for Next.js)
Since there is a tool designed for Next.js, I will definitely use this third one directly.
next-swagger-doc
In my actual use, this tool isn't that great either.
Since the official Next.js hasn't implemented strongly-typed APIs,
you need to define the schema for each endpoint yourself, which is a real hassle.
However, since I've already tried it out, I'll go ahead and introduce it.
Installation
bun i next-swagger-doc
Usage
The README.md documentation for this tool is a bit outdated.
Fortunately, the examples are not outdated, and they include a Next.js 15 project example.
https://github.com/jellydn/next-swagger-doc/tree/main/examples
Just follow the configuration directly.
Create Swagger Spec
Create the lib/swagger.ts file
import { createSwaggerSpec } from 'next-swagger-doc';
import 'server-only';
export const getApiDocs = async () => {
const spec = createSwaggerSpec({
apiFolder: 'app/api',
definition: {
openapi: '3.0.0',
info: {
title: 'Next Swagger API Example',
version: '1.0',
},
components: {
securitySchemes: {
BearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
},
OAuth2: {
type: 'oauth2',
flows: {
authorizationCode: {
authorizationUrl: 'https://example.com/oauth/authorize',
tokenUrl: 'https://example.com/oauth/token',
scopes: {
read: 'Grants read access',
write: 'Grants write access',
},
},
},
},
},
},
security: [],
},
});
return spec;
};
Creating Swagger UI Component
This can generate a Swagger interface.
There are various tools to achieve this functionality.
next-swagger-doc uses swagger-ui-react.
bun i swagger-ui-react
I'll follow the configuration here first, and then later try other tools from the Node.js ecosystem, such as stoplightio/elements.
Create the app/api-doc/react-swagger.tsx file.
'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) {
// @ts-ignore - SwaggerUI is not typed
return <SwaggerUI spec={spec} />;
}
export default ReactSwagger;
Creating an API Documentation Page
This involves wrapping the previously mentioned Swagger UI component into a page.
Create the app/api-doc/page.tsx file:
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>
);
}
Adding API Documentation Annotations
It's troublesome as this library cannot automatically identify APIs based on paths; they must be manually defined.
After adding these, the readability of the Swagger documentation improves significantly.
/**
* @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,
});
}
View the Effect
Visit http://localhost:3000/api-doc to view the API documentation.
Manual Generation
Generate an OpenAPI spec from API routes using tools like swagger-jsdoc
Place the swagger.json file in the public directory
Then use tools like swagger-ui-react mentioned earlier to implement Swagger documentation display
import dynamic from 'next/dynamic';
const SwaggerUI = dynamic(() => import('swagger-ui-react'), { ssr: false });
import 'swagger-ui-react/swagger-ui.css';
export default function ApiDocs() {
return <SwaggerUI url="/swagger.json" />;
}
Reference: Swagger integration in next JS
Summary
Both methods don't seem very perfect.
As expected, Next.js is still more frontend-focused, and writing too many APIs isn't quite suitable either.
Recently, I discovered something new: hono. This framework has excellent support for edge, so it might be worth considering using it alongside Next.js for some small projects.
I have to say that the frontend tech stack evolves way too fast, haha.
_EOF_
Integrate Swagger documentation in Next.js
- 本文作者:
- 程序设计实验室
- 版权声明:
- 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
相关文章
使用国内NPM镜像源提高速度
NPM介绍 npm(全称 Node Package Manager,即“node包管理器”)是Node.js默认的、以JavaScript编写的软件包管理系统。 npm可以管理本地项目的所需模块并自动维护依赖情况,也可以管理全局安装的JavaScript工具。 但是由于npm的源在国外,所以国内使用起来动辄10kb/s,甚至根本下载不了,所以使用国内镜像源替代官方源就很有必要了。 国内源 淘宝np
2022-02-25 · Web前端 · 约 1 分钟
NPM-Warn--ENOENT--no-such-file-or-directory
Now type the command to auto generate the package.json npm init --yes
2022-07-18 · Web前端 · 约 1 分钟
代码使我头疼之React初学习
前言 开始了,去年(2020)说要学的React,到现在2021年的12月底了,才来实施……(年底警告!~~年末总结还没开始写!~~) 不过前端为啥要学React呢?Vue不是很好用吗?Vue确实很好用,并且MVVM模式也更容易让人接受和理解,但大概是各种社区上都说react yyds啦,react一统江山啦什么的,加上我之前学Flutter做了很多项目,对声明式UI的思想已经基本掌握了,所以就想
2021-12-26 · Web前端 · 约 1 分钟
配置Chrome支持网页内的frame跨域
前言 跨域限制可以保证安全,但是调试的时候关掉会更方便,然而现在网络上能找到的关闭跨域限制方法,在新版的Chrome浏览器上根本没用…… 经过一番摸索,发现用旧版的Chrome就可以绕过跨域限制,刚好我做的这个需要跨域内嵌frame的网页只是单纯展示的,所以这个正好符合我的需求,奥利给! 然后我找到了旧版的Chrome软件,解压出来是绿色版的可以直接运行,不过运行后发现直接把系统的Chrome给调
2021-12-18 · Web前端 · 约 1 分钟
讨论
共 0 条加载评论中…