Skip to content

OpenAPI Handler

The OpenAPIHandler enables communication with clients over RESTful APIs, adhering to the OpenAPI specification. It is fully compatible with OpenAPILink and the OpenAPI Specification.

Supported Data Types

OpenAPIHandler serializes and deserializes the following JavaScript types:

  • string
  • number (NaNnull)
  • boolean
  • null
  • undefined (undefined in arrays → null)
  • Date (Invalid Datenull)
  • BigInt (BigIntstring)
  • RegExp (RegExpstring)
  • URL (URLstring)
  • Record (object)
  • Array
  • Set (Setarray)
  • Map (Maparray)
  • Blob (unsupported in AsyncIteratorObject)
  • File (unsupported in AsyncIteratorObject)
  • AsyncIteratorObject (only at the root level; powers the Event Iterator)

WARNING

If a payload contains Blob or File outside the root level, it must use multipart/form-data. In such cases, oRPC applies Bracket Notation and converts other types to strings (exclude null and undefined will not be represented).

TIP

You can extend the list of supported types by creating a custom serializer.

Installation

sh
npm install @orpc/openapi@latest
sh
yarn add @orpc/openapi@latest
sh
pnpm add @orpc/openapi@latest
sh
bun add @orpc/openapi@latest
sh
deno install npm:@orpc/openapi@latest

Setup and Integration

ts
import { OpenAPIHandler } from '@orpc/openapi/fetch' // or '@orpc/server/node'
import { CORSPlugin } from '@orpc/server/plugins'
import { onError } from '@orpc/server'

const handler = new OpenAPIHandler(router, {
  plugins: [new CORSPlugin()],
  interceptors: [
    onError(error => console.error(error))
  ],
})

export default async function fetch(request: Request) {
  const url = new URL(request.url)

  if (url.pathname.startsWith('/api')) {
    const result = await handler.handle(request, {
      prefix: '/api',
      context: {} // Add initial context if needed
    })

    if (result.matched)
      return result.response
  }

  return new Response('Not Found', { status: 404 })
}

Event Iterator Keep Alive

To keep Event Iterator connections alive, OpenAPIHandler periodically sends a ping comment to the client. You can configure this behavior using the following options:

  • eventIteratorKeepAliveEnabled (default: true) – Enables or disables pings.
  • eventIteratorKeepAliveInterval (default: 5000) – Time between pings (in milliseconds).
  • eventIteratorKeepAliveComment (default: '') – Custom content for ping messages.
ts
const result = await handler.handle(request, {
  eventIteratorKeepAliveEnabled: true,
  eventIteratorKeepAliveInterval: 5000, // 5 seconds
  eventIteratorKeepAliveComment: '',
})

Released under the MIT License.