### Install and Run Example App Source: https://github.com/tazo90/next-openapi-gen/blob/main/README.md Steps to install dependencies, navigate to an example app, generate OpenAPI specs, and start the development server. ```bash pnpm install cd apps/next-app-zod pnpm exec openapi-gen generate pnpm dev ``` -------------------------------- ### Install Dependencies and Generate OpenAPI Docs Source: https://github.com/tazo90/next-openapi-gen/blob/main/apps/next-app-mixed-schemas/README.md Install project dependencies using pnpm and then generate the OpenAPI documentation. This is a common setup for projects within a pnpm workspace. ```bash # Install dependencies pnpm install # Generate OpenAPI documentation pnpm openapi:generate # Start development server pnpm dev ``` -------------------------------- ### Start Development Server Source: https://github.com/tazo90/next-openapi-gen/blob/main/apps/next-app-drizzle-zod/README.md Use this command to start the Next.js development server. After starting, you can view the API documentation at http://localhost:3000/api-docs. ```bash pnpm dev ``` -------------------------------- ### Install Dependencies and Generate OpenAPI Docs Source: https://github.com/tazo90/next-openapi-gen/blob/main/apps/next-pages-router/README.md Run `pnpm install` to install dependencies from the repository root. Then, use `pnpm exec openapi-gen generate` to generate the OpenAPI documentation. ```bash # Install dependencies pnpm install # Generate OpenAPI documentation pnpm exec openapi-gen generate # Start the development server pnpm dev ``` -------------------------------- ### Documenting GET and POST requests for /users Source: https://github.com/tazo90/next-openapi-gen/blob/main/apps/next-pages-router/README.md This example shows how to document both GET and POST requests for the `/users` endpoint using separate JSDoc blocks with the `@method` tag. It includes descriptions, parameter schemas, and response schemas. ```APIDOC ## GET /users ### Description Get all users ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **UserListParamsSchema** (object) - Required - Schema for user list parameters ### Response #### Success Response (200) - **UserSchema[]** (array) - Array of user objects ## POST /users ### Description Create a new user ### Method POST ### Endpoint /users ### Parameters #### Request Body - **CreateUserSchema** (object) - Required - Schema for creating a user ### Response #### Success Response (201) - **UserSchema** (object) - The created user object ``` -------------------------------- ### Install next-openapi-gen with npm Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/getting-started.md Install the package as a development dependency using npm. ```bash npm install --save-dev next-openapi-gen ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/tazo90/next-openapi-gen/blob/main/apps/next-app-drizzle-zod/README.md Run this command from the repository root to install all necessary dependencies for the project within the pnpm workspace. ```bash pnpm install ``` -------------------------------- ### Install next-openapi-gen with yarn Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/getting-started.md Install the package as a development dependency using yarn. ```bash yarn add --dev next-openapi-gen ``` -------------------------------- ### Install next-openapi-gen with pnpm Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/getting-started.md Install the package as a development dependency using pnpm. ```bash pnpm add -D next-openapi-gen ``` -------------------------------- ### Local CLI Testing within Workspace Source: https://github.com/tazo90/next-openapi-gen/blob/main/CONTRIBUTING.md Steps to test the CLI locally within the project's workspace. This involves installing dependencies, building the workspace, and running an example app. ```bash pnpm install pnpm build cd apps/next-app-zod pnpm exec openapi-gen generate pnpm dev ``` -------------------------------- ### Initialize Project with next-openapi-gen Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Scaffolds the config file and an optional docs page for the selected framework and UI provider. Installs required dependencies automatically. ```bash pnpm exec openapi-gen init pnpm exec openapi-gen init --framework tanstack --ui swagger --schema typescript pnpm exec openapi-gen init --framework react-router --ui none # All init flags # --framework next | tanstack | react-router (default: next) # --ui scalar | swagger | redoc | stoplight | rapidoc | none (default: scalar) # --schema zod | typescript (default: zod) # --docs-url (default: api-docs) # --output (default: next.openapi.json) ``` -------------------------------- ### Using @examples for Request Payloads Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/jsdoc-reference.md Illustrates how to use the @examples annotation to provide inline JSON, serialized payloads, or external references for request parameters. ```APIDOC ## Examples `@examples` supports several styles: - inline JSON values - serialized wire-format payloads - external URLs - exported typed references Example: ```ts export const streamQueryExamples = [ { name: "filters", value: { status: "active" }, }, ]; /** * @examples querystring:streamQueryExamples * @openapi */ export async function GET() { return Response.json({ ok: true }); } ``` ``` -------------------------------- ### Authentication Configuration and Usage Source: https://context7.com/tazo90/next-openapi-gen/llms.txt This example shows how to configure security schemes and override authentication presets in `next.openapi.json`. It also demonstrates different ways to apply authentication to API routes using `@auth` and `@security` annotations. ```typescript // openapi-gen.config.ts — define security schemes and override presets import { defineConfig } from "next-openapi-gen"; export default defineConfig({ openapi: "3.1.0", info: { title: "Secure API", version: "1.0.0" }, apiDir: "src/app/api", schemaType: "zod", schemaDir: "src/schemas", outputFile: "openapi.json", outputDir: "./public", authPresets: { bearer: "JwtAuth", // override default "BearerAuth" apikey: "ApiKeyAuth", oauth2: "OAuth2", // add a new preset }, components: { securitySchemes: { JwtAuth: { type: "http", scheme: "bearer", bearerFormat: "JWT" }, ApiKeyAuth: { type: "apiKey", in: "header", name: "X-API-Key" }, OAuth2: { type: "oauth2", flows: { authorizationCode: { authorizationUrl: "https://auth.example.com/oauth/authorize", tokenUrl: "https://auth.example.com/oauth/token", scopes: { "read:users": "Read user data", "write:users": "Write user data" }, }, }, }, }, }, }); // src/app/api/admin/route.ts /** * Admin endpoint — bearer only * @auth bearer * @response AdminResponse * @openapi */ export async function GET() { return Response.json({ ok: true }); } /** * Admin endpoint — bearer OR api-key accepted * @auth bearer,apikey * @response AdminResponse * @openapi */ export async function POST() { return Response.json({ ok: true }); } /** * Scoped endpoint — explicit security with scopes * @security JwtAuth, OAuth2:read:users|write:users * @response AdminResponse * @openapi */ export async function PUT() { return Response.json({ ok: true }); } ``` -------------------------------- ### Examples for Query String Parameters Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/jsdoc-reference.md The @examples annotation supports inline JSON, serialized payloads, external URLs, and exported typed references for query string parameters. ```typescript export const streamQueryExamples = [ { name: "filters", value: { status: "active" }, }, ]; /** * @examples querystring:streamQueryExamples * @openapi */ export async function GET() { return Response.json({ ok: true }); } ``` -------------------------------- ### Default configuration file structure Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/getting-started.md Example of a default configuration file generated by `init`. This structure defines OpenAPI version, API directory, schema settings, output paths, and route options. ```json { "openapi": "3.0.0", "info": { "title": "Next.js API", "version": "1.0.0", "description": "API generated by next-openapi-gen" }, "apiDir": "./src/app/api", "routerType": "app", "schemaDir": "./src", "schemaType": "zod", "schemaFiles": [], "outputFile": "openapi.json", "outputDir": "./public", "docsUrl": "api-docs", "includeOpenApiRoutes": false, "ignoreRoutes": [], "debug": false } ``` -------------------------------- ### Conventional Commits with Scope Example Source: https://github.com/tazo90/next-openapi-gen/blob/main/CONTRIBUTING.md Examples demonstrating the use of a scope in Conventional Commits to provide more context about the change, such as 'feat(drizzle)' or 'fix(types)'. ```text feat(drizzle): add support for Drizzle schemas fix(types): resolve TypeScript errors in route processor docs(readme): add installation instructions ``` -------------------------------- ### Start File Watcher with `watchProject` Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Starts a file watcher that regenerates the OpenAPI spec on changes to route files, schema files, or the config file. Returns a function to stop the watcher. ```typescript import { watchProject } from "next-openapi-gen"; const stopWatching = await watchProject({ cwd: process.cwd(), configPath: "openapi-gen.config.ts", }); // Later, to stop watching: stopWatching(); ``` -------------------------------- ### Bad Commit Message Examples Source: https://github.com/tazo90/next-openapi-gen/blob/main/CONTRIBUTING.md Examples of commit messages that do not adhere to the Conventional Commits format, which should be avoided. ```text added feature fix update WIP Fixed stuff ``` -------------------------------- ### Good Commit Message Examples Source: https://github.com/tazo90/next-openapi-gen/blob/main/CONTRIBUTING.md Examples of well-formatted commit messages following the Conventional Commits specification for various types like feat, fix, perf, and docs. ```text feat: add support for Drizzle ORM schemas fix: resolve crash on dynamic routes perf: improve OpenAPI generation speed by 40% docs: add examples for Zod integration refactor: simplify schema processor logic test: add integration tests for route processor ``` -------------------------------- ### Wildcard status codes example Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Demonstrates the use of wildcard status codes for success, client errors, and default responses. ```APIDOC ## GET /api/orders ### Description Wildcard status codes ### Method GET ### Endpoint /api/orders ### Response #### Success Response (2XX) - **OrderResponse** - Any success #### Error Response (4XX) - **ErrorResponse** - Any client error #### Default Response - **ErrorResponse** - Fallback ``` -------------------------------- ### Type-Safe Configuration with defineConfig Source: https://context7.com/tazo90/next-openapi-gen/llms.txt This example demonstrates using `defineConfig` for type-safe configuration in `openapi-gen.config.ts`. It shows mixed schema sources and component definitions. ```typescript import { defineConfig } from "next-openapi-gen"; // openapi-gen.config.ts export default defineConfig({ openapi: "3.2.0", info: { title: "Events API", version: "2.0.0" }, apiDir: "src/app/api", schemaType: ["zod", "typescript"], // mixed schema sources schemaDir: ["src/schemas", "src/types"], schemaFiles: ["schemas/external-partner.yaml"], outputFile: "openapi.json", outputDir: "./public", includeOpenApiRoutes: true, // only emit @openapi-tagged routes ignoreRoutes: ["**/internal/**", "**/health"], defaultResponseSet: "common", responseSets: { common: ["400", "401", "500"] }, components: { securitySchemes: { JwtAuth: { type: "http", scheme: "bearer", bearerFormat: "JWT" }, }, }, }); ``` -------------------------------- ### GET Request Handler with OpenAPI Metadata Source: https://github.com/tazo90/next-openapi-gen/blob/main/README.md Implement a GET request handler for fetching product information, including OpenAPI metadata in JSDoc for automatic spec generation. This handler uses Zod schemas for path parameters and response structure. ```typescript import { NextRequest } from "next/server"; import { z } from "zod"; export const ProductParams = z.object({ id: z.string().describe("Product ID"), }); export const ProductResponse = z.object({ id: z.string(), name: z.string(), price: z.number().positive(), }); /** * Get product information * @description Fetch a product by ID * @pathParams ProductParams * @response ProductResponse * @openapi */ export async function GET(request: NextRequest, { params }: { params: { id: string } }) { return Response.json({ id: params.id, name: "Keyboard", price: 99 }); } ``` -------------------------------- ### Get product Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Retrieves a specific product's information using its unique ID. ```APIDOC ## GET /api/products/{id} ### Description Get product. ### Method GET ### Endpoint /api/products/{id} #### Path Parameters - **id** (string) - Required - Product UUID ### Response #### Success Response (200) - **ProductResponse** ### Response Example { "example": "{\n "id": "abc",\n "name": "Keyboard",\n "price": 99.99,\n "category": "electronics",\n "createdAt": "2023-10-27T10:00:00.000Z"\n}" } ``` -------------------------------- ### Zod Annotations with .describe() and .meta() Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Use Zod's `.describe()` method for simple descriptions and `.meta()` for richer OpenAPI metadata, including descriptions, examples, and custom extensions. `.meta({ id })` is specifically used to decouple component names. ```typescript import { z } from "zod"; // .describe() → description field only z.string().describe("ISO 639-1 language code"); // → { type: "string", description: "ISO 639-1 language code" } // .meta() → description, examples, and any OpenAPI extension z.number().int().positive().meta({ description: "PIM ID of the slider", examples: [42, 1337], }); // → { type: "integer", exclusiveMinimum: 0, description: "PIM ID of the slider", examples: [42, 1337] } // .meta({ id }) → decouple component name from export name export const internalSchema = z.object({ value: z.string() }).meta({ id: "PublicComponent" }); // → components.schemas.PublicComponent ``` -------------------------------- ### Next.js Adapter with `createNextOpenApiAdapter` Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Integrates OpenAPI generation into the Next.js build lifecycle. Call `onBuildComplete` after every build, and Next will regenerate the spec automatically. This example shows manual wiring. ```typescript // next.config.ts import { createNextOpenApiAdapter } from "next-openapi-gen/next"; const adapter = createNextOpenApiAdapter({ configPath: "openapi-gen.config.ts" }); // next.config.ts — manual wiring const nextConfig = { // pass adapter to the Next.js experimental.adaptors list if your Next version // supports it, or call onBuildComplete() in a custom webpack plugin }; export default nextConfig; ``` -------------------------------- ### Typed configuration with defineConfig Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/getting-started.md Use `defineConfig` for typed configuration in `openapi-gen.config.ts`. This example shows setting OpenAPI version, API directory, schema directory, and schema type. ```typescript import { defineConfig } from "next-openapi-gen"; export default defineConfig({ openapi: "3.0.0", apiDir: "./src/app/api", schemaDir: "./src", schemaType: "typescript", }); ``` -------------------------------- ### UI Page Templates for OpenAPI Docs Source: https://context7.com/tazo90/next-openapi-gen/llms.txt The `init` command can generate a UI documentation page using various frameworks. The default is Scalar, but Swagger UI, Redoc, Stoplight Elements, and RapiDoc are also supported. ```tsx // Scalar (default) — templates/init/ui/nextjs/scalar.tsx "use client"; import { ApiReferenceReact } from "@scalar/api-reference-react"; import "@scalar/api-reference-react/style.css"; export default function ApiDocsPage() { return ( ); } // Swagger UI — templates/init/ui/nextjs/swagger.tsx // "use client"; + SwaggerUI component pointing at /openapi.json // Redoc — templates/init/ui/nextjs/redoc.tsx // RedocStandalone component // Stoplight Elements — templates/init/ui/nextjs/stoplight.tsx // // RapiDoc — templates/init/ui/nextjs/rapidoc.tsx // ``` -------------------------------- ### Initialize next-openapi-gen for Next.js Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/getting-started.md Initialize the project with default settings for Next.js. This command scaffolds framework-aware defaults, creates a config file, and sets up an API docs page. ```bash # Next.js (default) pnpm exec openapi-gen init ``` -------------------------------- ### Bad Pull Request Title Examples Source: https://github.com/tazo90/next-openapi-gen/blob/main/CONTRIBUTING.md Examples of PR titles that do not follow the Conventional Commits format and should be avoided. ```text Added drizzle support Fixed bugs Update ``` -------------------------------- ### Annotate GET and PUT for Product API Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Annotates GET and PUT handlers for the product API using JSDoc tags referencing TypeScript types for path parameters and request bodies. The GET handler retrieves a product, and the PUT handler updates it. ```typescript /** * Get product * @pathParams ProductParams * @response ProductResponse * @openapi */ export async function GET(_req: Request, { params }: { params: { id: string } }) { return Response.json({ id: params.id, name: "Keyboard", price: 99.99, category: "electronics", createdAt: new Date().toISOString() }); } /** * Update product * @pathParams ProductParams * @body CreateProductBody * @response ProductResponse * @openapi */ export async function PUT(request: Request, { params }: { params: { id: string } }) { const body = (await request.json()) as CreateProductBody; return Response.json({ id: params.id, ...body, createdAt: new Date().toISOString() }); } ``` -------------------------------- ### Create a New Release with np Source: https://github.com/tazo90/next-openapi-gen/blob/main/CONTRIBUTING.md Initiates the release process using the 'np' tool, which automates testing, building, versioning, changelog generation, tagging, and publishing. ```bash pnpm run release ``` -------------------------------- ### Initialize next-openapi-gen for React Router Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/getting-started.md Initialize the project with framework-specific defaults for React Router. This command scaffolds defaults, creates a config file, and sets up an API docs page. ```bash # React Router pnpm exec openapi-gen init --framework react-router ``` -------------------------------- ### Annotate GET and DELETE for Specific User API Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Annotates GET and DELETE handlers for a specific user API endpoint. The GET handler uses `UserParams` for path parameters and returns `UserResponse`. The DELETE handler also uses `UserParams` and is marked as deprecated. ```typescript import { UserParams, UserResponse } from "@/schemas/user"; /** * Get user by ID * @pathParams UserParams * @response UserResponse * @responseDescription The requested user object * @response 404:ErrorResponse:User not found * @tag Users * @auth bearer * @openapi */ export async function GET(_req: Request, { params }: { params: { id: string } }) { return Response.json({ id: params.id, name: "Alice", email: "alice@example.com", role: "admin", createdAt: new Date().toISOString() }); } /** * Delete a user * @pathParams UserParams * @response 204 * @deprecated Prefer PATCH /users/:id/deactivate * @tag Users * @auth bearer * @openapi */ export async function DELETE(_req: Request, { params }: { params: { id: string } }) { return new Response(null, { status: 204 }); } ``` -------------------------------- ### Annotate GET and POST for User List API Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Annotates GET and POST handlers for the user list API using JSDoc tags to define parameters, responses, and tags. The GET handler supports pagination, and the POST handler validates the request body against `CreateUserBody`. ```typescript import { NextRequest, NextResponse } from "next/server"; import { CreateUserBody, UserResponse, UsersQueryParams } from "@/schemas/user"; /** * List users * @description Returns a paginated list of users * @params UsersQueryParams * @response UserResponse[] * @responseDescription Paginated user list * @tag Users * @auth bearer * @openapi */ export async function GET(request: NextRequest) { const { searchParams } = request.nextUrl; const page = Number(searchParams.get("page") ?? 1); const limit = Number(searchParams.get("limit") ?? 10); return NextResponse.json([{ id: "abc", name: "Alice", email: "alice@example.com", role: "admin", createdAt: new Date().toISOString() }]); } /** * Create a user * @description Register a new user account * @body CreateUserBody * @bodyDescription User registration payload * @response 201:UserResponse:User created successfully * @responseSet common * @tag Users * @auth bearer * @openapi */ export async function POST(request: NextRequest) { const body = CreateUserBody.parse(await request.json()); return NextResponse.json({ id: "new-uuid", ...body, createdAt: new Date().toISOString() }, { status: 201 }); } ``` -------------------------------- ### Initialize next-openapi-gen for TanStack Router Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/getting-started.md Initialize the project with framework-specific defaults for TanStack Router. This command scaffolds defaults, creates a config file, and sets up an API docs page. ```bash # TanStack Router pnpm exec openapi-gen init --framework tanstack ``` -------------------------------- ### TypeScript Property Comments with Tags Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/jsdoc-reference.md Use JSDoc tags like @example and @format within TypeScript property comments to define schema examples and formats. ```typescript type Health = { /** @example "alive" */ status: string; /** Process uptime in seconds @example 123.45 */ uptime: number; /** @format date-time @example "2025-11-26T22:00:00.000Z" */ startedAt: string; // Trailing comments parse the same tags region: string; // @example "eu-central-1" }; ``` -------------------------------- ### Conventional Commits Breaking Change Example Source: https://github.com/tazo90/next-openapi-gen/blob/main/CONTRIBUTING.md Example of how to denote a breaking change in a commit message, either by using '!' after the type or by including 'BREAKING CHANGE:' in the footer. ```text feat!: migrate to ESM modules BREAKING CHANGE: CommonJS is no longer supported. Node.js 16 is no longer supported, minimum version is now 18.0.0. ``` -------------------------------- ### Initialize next-openapi-gen for TanStack Router Source: https://github.com/tazo90/next-openapi-gen/blob/main/README.md Initialize the generator for a TanStack Router project. ```bash pnpm exec openapi-gen init --framework tanstack ``` -------------------------------- ### Fork and Clone Repository Source: https://github.com/tazo90/next-openapi-gen/blob/main/CONTRIBUTING.md Instructions for forking the project repository on GitHub and cloning it locally. Remember to replace YOUR_USERNAME with your GitHub username. ```bash # Fork the repository on GitHub, then: git clone https://github.com/YOUR_USERNAME/next-openapi-gen.git cd next-openapi-gen ``` -------------------------------- ### Build Workspace with Turborepo Source: https://github.com/tazo90/next-openapi-gen/blob/main/CONTRIBUTING.md Use this command to build the entire project workspace using Turborepo. ```bash pnpm build ``` -------------------------------- ### Add Metadata to Zod Schema Source: https://github.com/tazo90/next-openapi-gen/blob/main/README.md Use the `.meta()` method on a Zod schema to attach OpenAPI metadata such as 'description', 'examples', 'example', 'deprecated', 'title', and custom 'x-*' extensions. ```typescript z.number() .int() .positive() .meta({ description: "PIM ID of the slider", examples: [42, 1337], }); // → { type: "integer", exclusiveMinimum: 0, description: "PIM ID of the slider", examples: [42, 1337] } ``` -------------------------------- ### Good Pull Request Title Examples Source: https://github.com/tazo90/next-openapi-gen/blob/main/CONTRIBUTING.md Examples of well-formatted PR titles that follow the Conventional Commits format, which is required as PR titles are used as commit messages upon merging. ```text feat: add support for Drizzle ORM schemas fix: resolve TypeScript type errors in route processor docs: update README with new examples ``` -------------------------------- ### Initialize and Generate OpenAPI Specs Source: https://github.com/tazo90/next-openapi-gen/blob/main/README.md CLI commands for initializing the OpenAPI generator and generating specifications, with an option for watch mode. ```bash pnpm exec openapi-gen init ``` ```bash pnpm exec openapi-gen generate ``` ```bash pnpm exec openapi-gen generate --watch ``` -------------------------------- ### Initialize next-openapi-gen for Next.js Source: https://github.com/tazo90/next-openapi-gen/blob/main/README.md Initialize the generator for a Next.js project. This is the default framework. ```bash pnpm exec openapi-gen init ``` -------------------------------- ### TypeScript Property Annotations Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Annotate TypeScript properties with JSDoc tags like `@example` and `@format` to provide additional metadata for OpenAPI generation. These tags help define example values and data formats for schema properties. ```typescript type Health = { /** @example "alive" */ status: string; /** Process uptime in seconds @example 123.45 */ uptime: number; /** @format date-time @example "2025-11-26T22:00:00.000Z" */ startedAt: string; region: string; // @example "eu-central-1" }; ``` -------------------------------- ### Create a user Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Registers a new user account with the provided details. ```APIDOC ## POST /api/users ### Description Register a new user account. ### Method POST ### Endpoint /api/users #### Request Body - **name** (string) - Required - Full name - **email** (string) - Required - Email address - **role** (string) - Optional - Role (admin, member, viewer), defaults to member ### Request Example { "example": "{\n "name": "Alice",\n "email": "alice@example.com",\n "role": "admin"\n}" } ### Response #### Success Response (201) - **UserResponse** - User created successfully ### Response Example { "example": "{\n "id": "new-uuid",\n "name": "Alice",\n "email": "alice@example.com",\n "role": "admin",\n "createdAt": "2023-10-27T10:00:00.000Z"\n}" } ``` -------------------------------- ### GET /api/admin Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Admin endpoint that requires bearer authentication. ```APIDOC ## GET /api/admin ### Description Admin endpoint that requires bearer authentication. ### Method GET ### Endpoint /api/admin ### Authentication - bearer ### Response #### Success Response (200) - **ok** (boolean) ### Request Example (No request body specified in source) ### Response Example ```json { "ok": true } ``` ``` -------------------------------- ### Path Parameters Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/jsdoc-reference.md Demonstrates how to define and use path parameters in API requests. ```APIDOC ## GET /users/{id} ### Description Get a user by their ID. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - User ID ### Response #### Success Response (200) - **UserResponse** - Description of the user response object ``` -------------------------------- ### Add next-openapi-gen Scripts to package.json Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Add these scripts to your package.json to manage the OpenAPI generation process. Use 'openapi:init' once to set up, 'openapi:generate' for manual generation, 'openapi:watch' for development, and include 'openapi:gen generate' in your 'build' script. ```json { "scripts": { "openapi:init": "openapi-gen init --framework next --ui scalar --schema zod", "openapi:generate": "openapi-gen generate", "openapi:watch": "openapi-gen generate --watch", "build": "openapi-gen generate && next build" } } ``` -------------------------------- ### Get user by ID Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Retrieves a specific user's information using their unique ID. ```APIDOC ## GET /api/users/{id} ### Description Get user by ID. ### Method GET ### Endpoint /api/users/{id} #### Path Parameters - **id** (string) - Required - User UUID ### Response #### Success Response (200) - **UserResponse** - The requested user object #### Error Response (404) - **ErrorResponse** - User not found ### Response Example { "example": "{\n "id": "abc",\n "name": "Alice",\n "email": "alice@example.com",\n "role": "admin",\n "createdAt": "2023-10-27T10:00:00.000Z"\n}" } ``` -------------------------------- ### Preview Pre-commit Hook Actions Source: https://github.com/tazo90/next-openapi-gen/blob/main/CONTRIBUTING.md Command to preview the actions that the pre-commit hook will perform, such as formatting staged files with Oxfmt and linting with Oxlint. ```bash pnpm lint:staged ``` -------------------------------- ### Initialize next-openapi-gen for React Router Source: https://github.com/tazo90/next-openapi-gen/blob/main/README.md Initialize the generator for a React Router project. ```bash pnpm exec openapi-gen init --framework react-router ``` -------------------------------- ### GET /api/users/[id] Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Retrieves a user by their ID. This endpoint is part of the Pages Router handlers and requires specific route annotations. ```APIDOC ## GET /api/users/[id] ### Description Retrieves a user by their ID. ### Method GET ### Endpoint /api/users/[id] ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) - **id** (string) - The user's ID. - **name** (string) - The user's name. - **email** (string) - The user's email address. ### Request Example (No request body specified in source) ### Response Example ```json { "id": "123", "name": "Alice", "email": "alice@example.com" } ``` ``` -------------------------------- ### Manual Release Versioning with np Source: https://github.com/tazo90/next-openapi-gen/blob/main/CONTRIBUTING.md Allows for manual specification of release versions, including specific versions, beta releases, or skipping the npm publish step. ```bash pnpm exec np 1.0.0 ``` ```bash pnpm exec np 1.0.0-beta.1 ``` ```bash pnpm exec np --no-publish ``` -------------------------------- ### Configure Schema Type and Directory Source: https://github.com/tazo90/next-openapi-gen/blob/main/README.md Specify the schema type (e.g., 'zod') and the directory where schemas are located. ```json { "schemaType": "zod", "schemaDir": "src/schemas" } ``` -------------------------------- ### Response Sets and Extra Responses Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/jsdoc-reference.md Demonstrates how to use `@responseSet` and `@add` to opt into predefined response sets and extend them with additional responses, such as rate limit errors. ```APIDOC ## PUT / ### Description Update a user. ### Method PUT ### Endpoint / ### Parameters ### Request Body ### Request Example ### Response #### Success Response (200) - **UserResponse** (UserResponse) - #### Additional Responses - **429** (RateLimitResponse) - ### Response Example { "ok": true } ``` -------------------------------- ### Servers, External Docs, and Security Requirements Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/jsdoc-reference.md Shows how to declare operation-level servers, external documentation links, and security requirements directly on the route handler. ```APIDOC ## Servers, external docs, and security Operation-level `servers`, `externalDocs`, and `security` requirements can be declared directly on the route. ```ts /** * Subscribe to events * @servers https://api.example.com, https://staging.example.com * @externalDocs https://docs.example.com/events Event docs * @security BearerAuth, ApiKeyAuth:read:events|write:events * @openapi */ export async function POST() { return Response.json({ ok: true }); } ``` `@security` accepts comma-separated security requirements; use `Scheme:scope1|scope2` to attach scopes to a scheme. `@auth` remains available for preset-based shortcuts such as `bearer`, `basic`, and `apikey`. ``` -------------------------------- ### API Route for Listing Posts Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Defines a GET API route to list posts. It uses JSDoc annotations to specify query parameters and the response schema, integrating with OpenAPI. ```typescript // src/app/api/posts/route.ts import { CreatePostSchema, PostResponseSchema, PostsQueryParams } from "@/schemas/post"; /** * List posts * @params PostsQueryParams * @response PostResponseSchema[] * @tag Posts * @openapi */ export async function GET() { return Response.json([]); } ``` -------------------------------- ### Run Specific Test Suites Source: https://github.com/tazo90/next-openapi-gen/blob/main/CONTRIBUTING.md Commands to run specific test suites like unit, integration, or e2e. Also includes options for watch mode and UI. ```bash pnpm test:unit ``` ```bash pnpm test:integration ``` ```bash pnpm test:watch ``` ```bash pnpm test:ui ``` ```bash pnpm test:e2e ``` -------------------------------- ### Multipart Encoding for File Uploads Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/jsdoc-reference.md When `@contentType multipart/form-data` is used, `next-openapi-gen` derives per-part `encoding` entries from the body schema. This example shows how `contentMediaType` and specific property types influence the encoding. ```typescript export const UploadBody = { type: "object", properties: { avatarFile: { type: "object", description: "Avatar file", }, upload: { type: "object", description: "Avatar upload", contentMediaType: "image/png", }, }, }; ``` -------------------------------- ### Vite Plugin for TanStack Router with `createViteOpenApiPlugin` Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Drop this plugin into `vite.config.ts` to generate the OpenAPI spec on `buildStart` and watch during `dev` for TanStack Router projects. Configuration options include `configPath` and `watch`. ```typescript // vite.config.ts import { defineConfig } from "vite"; import { TanStackRouterVite } from "@tanstack/router-plugin/vite"; import { createViteOpenApiPlugin } from "next-openapi-gen/vite"; export default defineConfig({ plugins: [ TanStackRouterVite(), createViteOpenApiPlugin({ configPath: "openapi-gen.config.ts", // optional watch: true, // enable in dev server (default: true) }), ], }); ``` -------------------------------- ### OpenAPI Query Parameter Serialization Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/jsdoc-reference.md When a schema referenced by `@params` includes OpenAPI parameter serialization fields, `next-openapi-gen` lifts them onto the generated parameter object. This example shows how `style`, `explode`, and `allowReserved` are handled. ```typescript export const SearchParams = { type: "object", properties: { filter: { type: "object", properties: { status: { type: "string", }, }, }, search: { type: "string", style: "form", explode: false, allowReserved: true, }, }, }; ``` -------------------------------- ### JSON Configuration for next-openapi-gen Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Use this JSON file for basic configuration. It auto-discovers routes and defines schema resolution, output paths, and error response structures. ```json // next.openapi.json (JSON, auto-discovered) { "openapi": "3.1.0", "info": { "title": "My API", "version": "1.0.0", "description": "Generated by next-openapi-gen" }, "servers": [{ "url": "https://api.example.com" }], // Route scanning "apiDir": "src/app/api", // directory containing route files "routerType": "app", // "app" | "pages" "includeOpenApiRoutes": false, // true → only routes tagged @openapi "ignoreRoutes": ["src/app/api/internal/*", "src/app/api/health"], // Schema resolution "schemaDir": "src/schemas", "schemaType": "zod", // "zod" | "typescript" | ["zod","typescript"] "schemaFiles": ["schemas/shared.yaml"], // Output "outputFile": "openapi.json", "outputDir": "./public", "docsUrl": "api-docs", "ui": "scalar", // Reusable error response groups "defaultResponseSet": "common", "responseSets": { "common": ["400", "401", "500"], "auth": ["400", "401", "403", "500"] }, "errorConfig": { "template": { "type": "object", "properties": { "error": { "type": "string", "example": "{{ERROR_MESSAGE}}" }, "code": { "type": "string", "example": "{{ERROR_CODE}}" } } }, "codes": { "400": { "description": "Bad Request", "variables": { "ERROR_MESSAGE": "Invalid parameters", "ERROR_CODE": "BAD_REQUEST" } }, "401": { "description": "Unauthorized", "variables": { "ERROR_MESSAGE": "Auth required", "ERROR_CODE": "UNAUTHORIZED" } }, "500": { "description": "Server Error", "variables": { "ERROR_MESSAGE": "Unexpected error", "ERROR_CODE": "INTERNAL_ERROR" } } } }, // Auth preset overrides "authPresets": { "bearer": "JwtAuth", "oauth2": "OAuth2Auth" }, "debug": false } ``` -------------------------------- ### Configure Server-Sent Events Stream Source: https://context7.com/tazo90/next-openapi-gen/llms.txt Sets up a GET API route to stream events using Server-Sent Events (SSE). It uses JSDoc annotations to describe the stream, set content type, and define response items. ```typescript // src/app/api/stream/route.ts /** * Stream events * @description Server-sent event stream of real-time events * @tag Events * @tagSummary Event navigation * @tagKind nav * @querystring SearchFilter as advancedQuery * @responseContentType text/event-stream * @responseItem EventChunk * @responseItemEncoding {"headers":{"content-type":"application/json"}} * @openapi */ export async function GET() { return new Response(null, { status: 200, headers: { "Content-Type": "text/event-stream" } }); } ``` -------------------------------- ### Run All Workspace Tests Source: https://github.com/tazo90/next-openapi-gen/blob/main/CONTRIBUTING.md Execute all tests across the entire workspace. ```bash pnpm test ``` -------------------------------- ### API Route Handler with JSDoc for OpenAPI Source: https://github.com/tazo90/next-openapi-gen/blob/main/apps/next-app-drizzle-zod/README.md An example of a Next.js API route handler for creating a new post. It uses JSDoc tags (`@body`, `@response`, `@openapi`) to describe the request body, response schema, and OpenAPI metadata, which `next-openapi-gen` processes. ```typescript // src/app/api/posts/route.ts /** * Create a new post * @description Create a new blog post with validation * @body CreatePostSchema * @response 201:PostResponseSchema * @openapi */ export async function POST(request: NextRequest) { const body = await request.json(); const validated = CreatePostSchema.parse(body); // ... create post } ``` -------------------------------- ### OpenAPI Configuration Source: https://github.com/tazo90/next-openapi-gen/blob/main/apps/next-app-drizzle-zod/README.md The `next.openapi.json` configuration file specifies details for OpenAPI generation, including the OpenAPI version, API information, schema directory, schema type (zod), and the output file path. ```json { "openapi": "3.0.0", "info": { "title": "Drizzle-Zod Blog API", "version": "1.0.0" }, "schemaDir": "src/schemas", "schemaType": "zod", "outputFile": "openapi.json" } ``` -------------------------------- ### Opt into Response Sets with @responseSet and @add Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/jsdoc-reference.md Routes can opt into predefined response sets using @responseSet and extend them with additional responses using the @add tag, referencing response names defined in next.openapi.json. ```typescript /** * Update a user * @response UserResponse * @responseSet auth * @add 429:RateLimitResponse * @openapi */ export async function PUT() { return Response.json({ ok: true }); } ``` -------------------------------- ### Query Parameters Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/jsdoc-reference.md Illustrates how to define and use query parameters for filtering and pagination. ```APIDOC ## GET /users ### Description List users with optional filtering and pagination. ### Method GET ### Endpoint /users ### Parameters #### Query Parameters - **page** (number) - Optional - Page number - **limit** (number) - Optional - Results per page ``` -------------------------------- ### Header and Cookie Parameters Source: https://github.com/tazo90/next-openapi-gen/blob/main/docs/jsdoc-reference.md Explains how to document request headers and cookies using @header and @cookie annotations, referencing Zod schemas. ```APIDOC ## Header and cookie parameters Use `@header` and `@cookie` to document request headers and cookies. The referenced schema is emitted as one OpenAPI parameter per property, with `in` set to `header` or `cookie`. ```ts const RequestHeaders = z.object({ "X-Api-Key": z.string().describe("API key"), "X-Request-Id": z.string().uuid().optional(), }); const SessionCookies = z.object({ session: z.string().describe("Opaque session cookie"), }); /** * @header RequestHeaders * @cookie SessionCookies * @response UserResponse * @openapi */ export async function GET() { return Response.json({ ok: true }); } ``` ```