# Fumadocs (Framework Mode, Next.js): Generating Pages
URL: /docs/next/integrations/openapi/generate-files
Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/(framework)/[framework]/integrations/openapi/generate-files.mdx

Generate pages from OpenAPI schema.

`staticSource()` and `dynamicSource()` generate pages for your [`loader()`](/docs/next/integrations/openapi#generate-pages), while `generateFiles()` writes them into your content directory as MDX files. They accept the same options.

`<OpenAPIPage />` still renders the content of pages. The generator only arranges the endpoints and webhooks of each page.

## Options [#options]

### `per` [#per]

Customize the content of pages, default to `operation`.

<Callout>
Operation refers to an API endpoint with specific method like `/api/weather:GET`.
</Callout>

| mode      | content                        | file path                            |
| --------- | ------------------------------ | ------------------------------------ |
| tag       | operations with same tag       | `{tag_name}.mdx`                     |
| file      | operations in same schema file | `{file_name}.mdx`                    |
| operation | each operation                 | `{operationId ?? endpoint_path}.mdx` |
| custom    | see below                      | N/A                                  |

```ts
import { openapi } from '@/lib/openapi';

await openapi.staticSource({
  per: 'tag',
});
```

When set to `custom`, you can pass a function to fully customize the generation process:

```ts title="Example"
import type { OperationOutput } from 'fumadocs-openapi';
import { openapi } from '@/lib/openapi';

await openapi.staticSource({
  per: 'custom',
  toPages(builder) {
    const items = builder.extract();

    for (const op of items.operations) {
      const { pathItem, operation, displayName } = builder.fromExtractedOperation(op)!;

      const entry: OperationOutput = {
        type: 'operation',
        schemaId: builder.id,
        item: op,
        path: '...',
        info: {
          title: displayName,
          description: operation.description ?? pathItem.description,
        },
      };

      builder.create(entry);
    }
  },
});
```

When set to `tag`, adding `x-displayName` to the tag definition can control the title of each page.

```yaml title="openapi.yaml"
tags:
  - name: test
    description: this is a tag.
    x-displayName: My Test Name
```

Pages follow the tag hierarchy of OpenAPI 3.2 like [`groupBy`](#groupby), tags without operations get no page.

```yaml title="openapi.yaml"
tags:
  - name: store
    kind: nav
  # output: store/products.mdx
  - name: products
    parent: store
```

### `groupBy` [#groupby]

In `operation` mode, you can group output files with folders.

| value          | output                                                 |
| -------------- | ------------------------------------------------------ |
| tag            | `{tag}/{operationId ?? endpoint_path}.mdx`             |
| route          | `{endpoint_path}/{method}.mdx` (ignores `name` option) |
| none (default) | `{operationId ?? endpoint_path}.mdx`                   |

```ts
import { openapi } from '@/lib/openapi';

await openapi.staticSource({
  per: 'operation',
  groupBy: 'tag',
});
```

When grouping by `tag`, it follows the tag hierarchy of OpenAPI 3.2: a tag is nested into the folder of its `parent` tag, while tags with a `kind` other than `nav` are ignored.

```yaml title="openapi.yaml"
tags:
  - name: store
    summary: Store
    kind: nav
  - name: products
    parent: store

paths:
  /products:
    get:
      # output: store/products/listProducts.mdx
      operationId: listProducts
      tags: [products]
```

Operations without tags are grouped under an `unknown` folder.

### `name` [#name]

A function that controls the file name of generated pages.

```ts
import { openapi } from '@/lib/openapi';

await openapi.staticSource({
  name(output) {
    const doc = this.document;
    if (output.type === 'operation') {
      const operation = doc.paths![output.item.path]![output.item.method]!;
      // operation object
      console.log(operation);

      return 'my-dir/filename';
    }

    const hook = this.dereferenceShallow(doc.webhooks![output.item.name])[output.item.method]!;
    // webhook object
    console.log(hook);
    return 'my-dir/filename';
  },
});
```

### `meta` [#meta]

Generate [`meta.json`](/docs/next/page-conventions#meta) files automatically.

You can always define the `meta.json` files manually for maximal flexibility.

```ts
import { openapi } from '@/lib/openapi';

await openapi.staticSource({
  meta: true,
});
```

Or customize how folders are represented:

```ts
import { openapi } from '@/lib/openapi';

await openapi.staticSource({
  meta: {
    folderStyle: 'separator',
  },
});
```

## MDX Files [#mdx-files]

To write pages as MDX files, create a script:

```ts title="scripts/generate-docs.ts"
import { generateFiles } from 'fumadocs-openapi';
import { openapi } from '@/lib/openapi';

void generateFiles({
  input: openapi,
  output: './content/docs',
  // we recommend to enable it
  // make sure your endpoint description doesn't break MDX syntax.
  includeDescription: true,
});
```

Generate docs with the script:

```bash
bun ./scripts/generate-docs.ts
```

Add the `OpenAPIPage` component to your MDX components.

```tsx title="app/docs/[[...slug]]/page.tsx"
// [!code ++:2]
import { openapi } from '@/lib/openapi';
import { OpenAPIPage } from '@/components/api-page';

export default async function Page(props: PageProps<'/docs/[[...slug]]'>) {
  // ...
  <MDX
    components={getMDXComponents({
      // [!code ++:3]
      OpenAPIPage: async (props) => (
        <OpenAPIPage {...await openapi.preloadOpenAPIPage(page)} {...props} />
      ),
    })}
  />;
}
```

Add the plugin to your `loader()`:

```ts title="lib/source.ts"
import { openapi } from '@/lib/openapi';
import { loader } from 'fumadocs-core/source';

export const source = loader({
  // [!code ++:2] optional: adds a badge to each page item in page tree
  plugins: [openapi.loaderPlugin()],
});
```

`generateFiles()` also accepts the options below.

### `index` [#index]

Generate index files with cards linking to generated pages.

```ts
import { generateFiles } from 'fumadocs-openapi';

void generateFiles({
  index: {
    // for generating `href`
    url: {
      baseUrl: '/docs',
      contentDir: './content/docs',
    },
    items: [
      {
        // output path
        path: 'index.mdx',
        // optional: restrict the input files (identical to the `input` field in server)
        only: ['petstore.yaml'],
        // optional: set frontmatter
        description: 'All available pages',
      },
    ],
  },
});
```

### `imports` [#imports]

Add custom imports to generated MDX files. This is useful for including components, utilities, or other dependencies in your generated documentation.

```ts
import { generateFiles } from 'fumadocs-openapi';

void generateFiles({
  imports: [
    {
      names: ['API_BASE_URL'],
      from: '@/constants',
    },
  ],
});
```

This will add the following imports to all generated MDX files:

```ts
import { API_BASE_URL } from '@/constants';
```

### `frontmatter` [#frontmatter]

Customize the frontmatter of MDX files.

By default, it includes:

| property      | description                        |
| ------------- | ---------------------------------- |
| `title`       | Page title                         |
| `description` | Page description                   |
| `full`        | Always true, added for Fumadocs UI |
| `_openapi`    | Internal Properties                |

```ts
import { generateFiles } from 'fumadocs-openapi';

void generateFiles({
  frontmatter: (title, description) => ({
    myProperty: 'hello',
  }),
});
```

### `addGeneratedComment` [#addgeneratedcomment]

Add a comment to the top of generated files indicating they are auto-generated.

```ts
import { generateFiles } from 'fumadocs-openapi';

void generateFiles({
  // Add default comment
  addGeneratedComment: true,

  // Or provide a custom comment
  addGeneratedComment: 'Custom auto-generated comment',

  // Or disable comments
  addGeneratedComment: false,
});
```