Files
shorturl-analytics/docs/swagger-setup.md
2025-03-26 17:39:58 +08:00

3.9 KiB

Setting up Swagger UI in Next.js

This guide explains how to set up Swagger UI in a Next.js application using route groups.

Directory Structure

The recommended directory structure for Swagger documentation:

app/
  (swagger)/           # Route group for swagger-related pages
    swagger/          # Actual swagger route
      page.tsx       # Swagger UI component

Installation

  1. Add Swagger UI dependencies to your project:
{
  "dependencies": {
    "swagger-ui-react": "^5.12.0",
    "swagger-ui-dist": "^5.12.0"
  },
  "devDependencies": {
    "@types/swagger-ui-react": "^4.18.3"
  }
}
  1. Install webpack style loaders for handling Swagger UI CSS:
pnpm add -D style-loader css-loader

Next.js Configuration

Create or update next.config.js to handle Swagger UI CSS:

/** @type {import('next').NextConfig} */
const nextConfig = {
  transpilePackages: ['swagger-ui-react'],
  webpack: (config) => {
    config.module.rules.push({
      test: /\.css$/,
      use: ['style-loader', 'css-loader'],
    });
    return config;
  },
};

module.exports = nextConfig;

Swagger UI Component

Create app/(swagger)/swagger/page.tsx:

"use client";

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

export default function SwaggerPage() {
  useEffect(() => {
    document.title = 'API Documentation - ShortURL Analytics';
  }, []);

  const swaggerConfig = {
    openapi: '3.0.0',
    info: {
      title: 'Your API Title',
      version: '1.0.0',
      description: 'API documentation',
      contact: {
        name: 'API Support',
        email: 'support@example.com',
      },
      license: {
        name: 'MIT',
        url: 'https://opensource.org/licenses/MIT',
      },
    },
    // ... your API configuration
  };

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="mb-8">
        <h1 className="text-3xl font-bold mb-2">API Documentation</h1>
        <p className="text-gray-600">
          Explore and test the API endpoints using the interactive documentation below.
        </p>
      </div>
      <SwaggerUI spec={swaggerConfig} />
    </div>
  );
}

Best Practices

  1. Route Groups: Use route groups (groupname) to organize related pages without affecting the URL structure.

  2. API Documentation:

    • Add detailed descriptions for all endpoints
    • Include parameter descriptions and constraints
    • Define response schemas
    • Document error responses
    • Use appropriate data formats (UUID, URI, etc.)
    • Group related endpoints using tags
  3. Swagger Configuration:

    • Add contact information
    • Include license details
    • Set appropriate servers configuration
    • Define required fields
    • Add parameter validations (min/max values)

Common Issues

  1. Route Conflicts: Avoid parallel routes that resolve to the same path. For example, don't have both app/swagger/page.tsx and app/(group)/swagger/page.tsx as they would conflict.

  2. CSS Loading: Make sure to:

    • Import Swagger UI CSS
    • Configure webpack in next.config.js
    • Use the "use client" directive as Swagger UI is a client-side component
  3. React Version Compatibility: Be aware of potential peer dependency warnings between Swagger UI React and your React version. You might need to use --legacy-peer-deps or adjust your React version accordingly.

Accessing the Documentation

After setup, your Swagger documentation will be available at /swagger in your application. The UI provides:

  • Interactive API documentation
  • Request/response examples
  • Try-it-out functionality
  • Schema definitions
  • Error responses

Maintenance

Keep your Swagger documentation up-to-date by:

  • Updating the OpenAPI specification when adding or modifying endpoints
  • Maintaining accurate parameter descriptions
  • Keeping example values relevant
  • Updating response schemas when data structures change