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 许可协议。转载请注明出处!
相关文章
主流 nodejs 包管理器 pnpm vs bun vs npm vs yarn 简单横评
pnpm还真是会玩空间魔术?单项目里它领先优势就这么点?Node.js 20把npm喂肥了,现在谁还敢说npm是废物?这测试结果真是让人摸不着头脑。
2025-08-27 · Web前端 · 约 1 分钟
视频中台解决方案:组织树组件+多路视频直播界面开发
这种国产粗犷风格的项目居然能用?16路视频播放界面倒是简单直接,但现场配置和设备管理流程真是够折腾的。WVP和mpegts.js?B站开源的尿性,细节全靠蒙。
2025-07-04 · Web前端 · 约 1 分钟
魔改了一下bootstrap-treeview组件,发布个NPM包体验一下
前言 之前在这篇文章 基于.NetCore开发博客项目 StarBlog - (8) 分类层级结构展示 中说到,我为了让文章分类列表支持层级结构,用了一个树形组件,不过这个组件太老了,使用的Bootstrap版本居然是3.x的,但又找不到更好的,只能硬着头皮用。 但实际效果有很多我不满意的,人家作者直接放弃了,在GitHub上标记项目为Archive状态,没辙。 感谢开源,我直接fork一份代码来
2022-05-27 · Web前端 · 约 1 分钟
2025年底的 TailwindCSS 组件库简单横评
TailwindCSS组件库多到让人选择困难。shadcn/ui虽优雅但不够全,Origin UI倒是堆了500+组件——这年头连UI都要内卷?大而全还是小而精,选型前先想清楚自己要不要加班调样式。
2025-11-23 · Web前端 · 约 1 分钟
讨论
共 0 条加载评论中…