swagger next js
Install necessary dependencies:
bash npm install --save swagger-ui-react npm install --save swagger-jsdoc
Create a
swaggerOptions.js
file for Swagger configuration:javascript module.exports = { definition: { openapi: '3.0.0', info: { title: 'Your API Documentation', version: '1.0.0', description: 'Description of your API', }, servers: [ { url: 'http://localhost:3000', description: 'Local development server', }, ], }, apis: ['./routes/*.js'], // Path to your API routes };
Set up Swagger JSDoc in your project: In your project's
package.json
:json "scripts": { "swagger-jsdoc": "swagger-jsdoc -d swaggerOptions.js -o swagger.json" }
Generate Swagger documentation:
bash npm run swagger-jsdoc
Create a
swagger.js
file to serve the Swagger UI: ```javascript import SwaggerUI from 'swagger-ui-react'; import 'swagger-ui-react/swagger-ui.css';
export default function Swagger() {
return
- Set up a route for serving Swagger UI in your
pages/api
directory, e.g.,pages/api/swagger.js
: ```javascript import nextConnect from 'next-connect'; import swaggerUi from 'swagger-ui-express'; import swaggerDocument from '../../swagger.json';
const handler = nextConnect();
handler.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
export default handler; ```
Start your Next.js app:
bash npm run dev
Access Swagger UI at
http://localhost:3000/api/swagger
in your browser.
Note: Adjust paths and configurations based on your project structure and requirements.