# Fumadocs (Framework Mode, React Router): createOpenAPI()
URL: /docs/react-router/integrations/openapi/server
Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/(framework)/[framework]/integrations/openapi/server.mdx

The OpenAPI server instance.

## OpenAPI Server [#openapi-server]

The main config for Fumadocs OpenAPI.

> It should not be referenced in browser environments.

### `input` [#input]

The OpenAPI schemas to read from.

- File Paths
- External URLs
- Functions (see below)

Only schemas listed here can be loaded, other IDs passed to `getSchema()` or preloaded by pages throw an error.

<Callout type="warn">
Do not pass untrusted schemas to `input`, their `$ref`s can read local files and fetch URLs, private hosts included.
</Callout>

```ts tab="Basic"
import { createOpenAPI } from 'fumadocs-openapi/server';

export const openapi = createOpenAPI({
  input: ['./unkey.json'],
});
```

```ts tab="Functions"
import { createOpenAPI } from 'fumadocs-openapi/server';

export const openapi = createOpenAPI({
  input: {
    // [id]: downloaded OpenAPI Schema
    my_schema: async () => {
      const res = await fetch('https://registry.scalar.com/@scalar/apis/galaxy/latest?format=json');
      return res.json();
    },
  },
});
```

## Loading Documents Once [#loading-documents-once]

Pages receive the whole document in their props, so every page load, navigation and prefetch sends it again. For large documents, leave it out:

```ts title="lib/openapi.ts"
import { createOpenAPI } from 'fumadocs-openapi/server';

export const openapi = createOpenAPI({
  // IDs end up in URLs, keep them URL-safe
  input: { museum: './museum.yaml' },
  includeDocument: false, // [!code ++]
});
```

Pass `loadDocument` to load each document once per browser session. It also runs during server rendering:

```tsx title="components/api-page.tsx"
'use client';
import { preload } from 'react-dom';
import { createOpenAPIPage } from 'fumadocs-openapi/ui';

export const OpenAPIPage = createOpenAPIPage({
  async loadDocument(id) {
    if (import.meta.env.SSR) {
      // the browser starts downloading it with the page
      preload(`/api/openapi/${id}`, { as: 'fetch', crossOrigin: 'anonymous' });
      const { openapi } = await import('@/lib/openapi');
      return (await openapi.getSchema(id)).bundled;
    }
    return (await fetch(`/api/openapi/${id}`)).json();
  },
});
```

Serve the documents to the browser from a route:

```ts tab="app/routes/openapi.ts"
import type { Route } from './+types/openapi';
import { openapi } from '@/lib/openapi';

export async function loader({ params }: Route.LoaderArgs) {
  return Response.json((await openapi.getSchema(params.id)).bundled);
}
```

```ts tab="app/routes.ts"
import { route, type RouteConfig } from '@react-router/dev/routes';

export default [
  // [!code ++]
  route('api/openapi/:id', 'routes/openapi.ts'),
  // ...
] satisfies RouteConfig;
```

- `loadDocument` works with generated MDX files too.
- For the [UI installed by Fumadocs CLI](/docs/react-router/integrations/openapi/api-page#full-ui), pass `loadDocument` to `createOpenAPIRenderer()`.
- Browsers keep each document until a reload. With `disableCache`, leave `includeDocument` on.

## Creating Proxy [#creating-proxy]

A proxy server sends HTTP requests without the CORS restrictions of browsers. The API playground uses it for:

- Requests to API endpoints that don't allow your origin with CORS.
- OAuth requests of confidential clients (with a client secret) and device flows.

<Callout type="warn">
The proxy is public without authentication. It forwards the headers and body of requests, including `Authorization`. Restrict it with [`allowedOrigins`](#allowed-origins) and `filterRequest`.
</Callout>

### Setup [#setup]

The playground sends its requests to the proxy as `POST`, with the method of the operation in the URL. Create a route handler for it:

```ts tab="app/routes/proxy.ts"
import type { Route } from './+types/proxy';
import { openapi } from '@/lib/openapi';

const proxy = openapi.createProxy();

export const action = ({ request }: Route.ActionArgs) => proxy.handle(request);
```

```ts tab="app/routes.ts"
import { route, type RouteConfig } from '@react-router/dev/routes';

export default [
  // [!code ++]
  route('api/proxy', 'routes/proxy.ts'),
  // ...
] satisfies RouteConfig;
```

Then set its URL in `createOpenAPI()`:

```ts title="lib/openapi.ts"
import { createOpenAPI } from 'fumadocs-openapi/server';

export const openapi = createOpenAPI({
  proxyUrl: '/api/proxy', // [!code ++]
});
```

### Allowed Origins [#allowed-origins]

By default, the proxy accepts any public origin, refuses hosts on private networks (e.g. `localhost`), and doesn't forward your site's cookies.
List the origins in your proxy route to restrict it, or to proxy private APIs:

```ts
openapi.createProxy({
  // strings or regular expressions
  allowedOrigins: ['https://api.example.com', 'http://localhost:8080'],
});
```

Redirects are checked by the same rules.

<Callout type="warn">
Refusing private networks requires Node.js or Deno. On other runtimes, like Bun, specify
`allowedOrigins`.
</Callout>

Use `filterRequest` to refuse requests, for example to only allow reads:

```ts
openapi.createProxy({
  // proxied requests that return false are refused
  filterRequest: (request) => request.method === 'GET',
});
```

## OAuth Redirect [#oauth-redirect]

OAuth providers only accept registered redirect URIs, but the API playground redirects to the current page by default.
Create a route handler as the redirect URI of every page. It sends users back to the page that started the flow.

```ts tab="app/routes/oauth.ts"
import type { Route } from './+types/oauth';
import { openapi } from '@/lib/openapi';

const handler = openapi.createOAuthHandler();

export const loader = ({ request }: Route.LoaderArgs) => handler(request);
```

```ts tab="app/routes.ts"
import { route, type RouteConfig } from '@react-router/dev/routes';

export default [
  // [!code ++]
  route('api/oauth', 'routes/oauth.ts'),
  // ...
] satisfies RouteConfig;
```

Pass its URL to `createOpenAPIPage()`, and register the full URL (e.g. `https://docs.example.com/api/oauth`) on your OAuth provider:

```tsx title="components/api-page.tsx"
export const OpenAPIPage = createOpenAPIPage({
  oauthRedirectUrl: '/api/oauth', // [!code ++]
});
```

<Callout title="Content Security Policy">
The handler sends users back with a script served from its own route. If a Content Security Policy covers the route, it must allow `'self'` scripts. Policies with `'strict-dynamic'` ignore `'self'`, leave the route out of them instead.
</Callout>

### Static Sites [#static-sites]

On a static site, the route is prerendered to a file. Pass `inline: true` to put the script in the page, and end the path in `.html` so static hosts serve the file as HTML.

```ts tab="app/routes/oauth.ts"
import type { Route } from './+types/oauth';
import { openapi } from '@/lib/openapi';

const handler = openapi.createOAuthHandler({ inline: true });

export const loader = ({ request }: Route.LoaderArgs) => handler(request);
```

```ts tab="app/routes.ts"
import { route, type RouteConfig } from '@react-router/dev/routes';

export default [
  // [!code ++]
  route('api/oauth.html', 'routes/oauth.ts'),
  // ...
] satisfies RouteConfig;
```

```ts tab="react-router.config.ts"
import type { Config } from '@react-router/dev/config';

export default {
  prerender: [
    '/api/oauth.html', // [!code ++]
    // ...
  ],
} satisfies Config;
```

Use the `.html` URL as the redirect URI, like `oauthRedirectUrl: '/api/oauth.html'`. The script is in the page, so a Content Security Policy covering the route must allow inline scripts.