Install @elysia/openapi
mainTo add OpenAPI documentation support to your Elysia application, install the @elysia/openapi plugin using bun:
bun add @elysia/openapirepository·main·Indexed 41 days ago
https://github.com/elysiajs/elysia-openapiA plugin for the ElysiaJS framework that automatically generates and serves OpenAPI (Swagger) documentation based on route definitions and TypeBox schemas. Version 1.4.16 supports OpenAPI versions 3.0.x and 3.1.x, and provides built-in integration for Scalar and Swagger UI documentation frontends.
To add OpenAPI documentation support to your Elysia application, install the @elysia/openapi plugin using bun:
bun add @elysia/openapiThe openapi() function accepts a configuration object to customize the generated documentation.
enabled: (default: true) Enable or disable the plugin.openapiVersion: (default: '3.1.2') The OpenAPI document version to emit. Supports 3.0.x and 3.1.x.path: (default: '/openapi') The endpoint to expose the OpenAPI documentation frontend.specPath: (default: '/${path}/json') The endpoint to expose the OpenAPI specification in JSON format.provider: (default: 'scalar') The documentation frontend provider. Options are scalar, swagger, or null to disable the frontend.Use the exclude object to hide specific parts of your API from the documentation:
exclude.methods: A list of HTTP methods to exclude.exclude.paths: A list of paths to exclude.exclude.staticFile: (default: true) Exclude static file routes.exclude.tags: A list of tags to exclude.documentation: Object containing OpenAPI documentation information.references: Additional OpenAPI references for each endpoint.scalar: Configuration for the Scalar provider (follows Scalar config).swagger: Configuration for the SwaggerUI provider (follows Swagger config).By default, the documentation UI fetches the OpenAPI specification from the specPath via a network request. If you set embedSpec: true, the plugin will inject the entire JSON specification directly into the HTML response. This is useful for reducing network requests or when working in environments like Cloudflare Workers where you might want to minimize external fetches.
app.use(openapi({
embedSpec: true
}))To use the plugin, import openapi from @elysia/openapi and register it using .use(openapi()) on your Elysia instance. The plugin automatically generates documentation based on your route definitions, including schemas provided via Elysia's t (TypeBox) validation. By default, the documentation frontend is available at /openapi.
import { Elysia, t } from 'elysia'
import { openapi } from '@elysia/openapi'
const app = new Elysia()
.use(openapi())
.get('/', () => 'hi', {
response: t.String({ description: 'sample description' })
})
.post(
'/json/:id',
({ body, params: { id }, query: { name } }) => ({
...body,
id,
name
}),
{
params: t.Object({
id: t.String()
}),
query: t.Object({
name: t.String()
}),
body: t.Object({
username: t.String(),
password: t.String()
}),
response: t.Object(
{
username: t.String(),
password: t.String(),
id: t.String(),
name: t.String()
},
{ description: 'sample description' }
)
}
)
.listen(3000)The openapi() function accepts a configuration object of type ElysiaOpenAPIConfig.
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | true | Whether the plugin is active. |
path | string | '/openapi' | The URL path where the documentation UI is served. |
provider | 'scalar' | 'swagger-ui' | null | The UI provider. Use null to disable the UI and only serve the JSON spec. | |
specPath | string | '{path}/json' | The URL path where the raw OpenAPI JSON specification is served. |
openapiVersion | OpenAPIVersion | '3.1.2' | The OpenAPI version to use in the generated spec. |
documentation | object | {} | Custom metadata for the OpenAPI document (e.g., info, tags, components). |
exclude | object | undefined | Options to filter out parts of the documentation (see Exclude documentation). |
swagger | object | {} | Configuration specific to the swagger-ui provider. |
scalar | object | {} | Configuration specific to the scalar provider. |
embedSpec | boolean | false | If true, the OpenAPI specification is embedded directly into the HTML of the documentation page. |
mapJsonSchema | function | undefined | A function to map JSON schemas during generation. |
references | object | undefined | Custom references for the OpenAPI schema. |
Use the exclude object to hide specific parts of your API from the documentation:
exclude.methods: Array of HTTP methods to exclude.exclude.paths: Array of path strings to exclude.exclude.staticFile: Exclude static file routes.exclude.tags: Array of tag names to exclude.app.use(openapi({
path: '/docs',
provider: 'swagger-ui',
documentation: {
info: {
title: 'My API',
version: '1.0.0'
}
},
exclude: {
tags: ['internal']
}
}))The ElysiaOpenAPIConfig interface defines the configuration options for the @elysiajs/openapi plugin. It allows you to control the OpenAPI version, documentation content, endpoint paths, provider selection (Scalar or Swagger UI), and exclusion rules for specific methods, paths, or tags.
// Example configuration structure
openapi({
enabled: true,
openapiVersion: '3.1.0',
path: '/docs',
provider: 'scalar',
documentation: {
info: { title: 'My API', version: '1.0.0' }
},
exclude: {
methods: ['DELETE'],
paths: ['/internal/.*'],
tags: ['admin']
}
})/${path}/json, where path is your configured documentation endpoint (defaulting to /openapi). You can override this using the specPath option.Use the exclude object in your configuration to prevent certain parts of your API from appearing in the generated OpenAPI documentation.
methods: An array of strings representing HTTP methods to exclude (e.g., ['DELETE']).paths: A string, RegExp, or array of strings/RegExps to exclude specific paths.tags: An array of strings to exclude specific tags.staticFile: A boolean to determine if static files should be excluded (defaults to true).openapi({
exclude: {
methods: ['POST'],
paths: [/^\/private/, '/health'],
tags: ['internal']
}
})You can explicitly set the OpenAPI specification version and provide custom documentation metadata.
openapiVersion: Set the version using the format `3.0.${number}` or `3.1.${number}` (e.g., '3.1.2').documentation: An object containing partial OpenAPIV3 or OpenAPIV3_1 document properties (like info, servers, etc.). Note that x-express-openapi-additional-middleware and x-express-openapi-validation-strict are omitted from this type.You can choose between scalar (default) and swagger-ui using the provider option. Each provider has its own specific configuration block:
scalar key to pass ApiReferenceConfiguration. You can also specify a version for the CDN bundle or a custom cdn path (e.g., a local file or a specific unpkg URL).swagger key to pass options to SwaggerUIBundle. Supported options include theme (string or light/dark object), version (default 4.18.2), autoDarkMode, and cdn for custom bundle paths. Note that functional options like requestInterceptor are not supported.// Scalar configuration example
openapi({
provider: 'scalar',
scalar: {
version: 'latest',
cdn: 'https://unpkg.com/@scalar/api-reference@1.13.10/dist/browser/standalone.js'
}
})
// Swagger UI configuration example
openapi({
provider: 'swagger-ui',
swagger: {
theme: { light: 'css-string', dark: 'css-string' },
autoDarkMode: true
}
})The SwaggerUIRender function generates a complete HTML string to serve a Swagger UI documentation page. It takes OpenAPI information and configuration options to customize the look and feel of the documentation.
When calling SwaggerUIRender, you can provide the following configuration via the config object:
version (string, default: 'latest'): The version of swagger-ui-dist to use from the Unpkg CDN.theme (string | { light: string, dark: string }):light and dark keys, it provides specific stylesheets for different color schemes.cdn (string, default: uses version to build a URL): The URL for the swagger-ui-bundle.js script.autoDarkMode (boolean, default: true): If true, injects CSS to automatically apply a dark mode filter to the Swagger UI based on the user's system preference....rest: Any other valid SwaggerUIOptions (passed directly to the SwaggerUIBundle constructor).Note: Functions passed in the configuration object are automatically stripped out before being stringified for the browser-side script.
import { SwaggerUIRender } from './src/swagger/index'
import { OpenAPIV3 } from 'openapi-types'
const info: OpenAPIV3.InfoObject = {
title: 'My API',
version: '1.0.0',
description: 'An example API'
}
const config = {
version: '5.17.11',
autoDarkMode: true,
// other SwaggerUIOptions
}
const html = SwaggerUIRender(info, config)The ScalarRender function generates a complete HTML string used to serve the Scalar API documentation UI. It takes the OpenAPI information object, a configuration object, and an optional embedded specification string.
This function is typically used internally by @elysia/openapi to provide a visual interface for your API documentation. It injects the provided configuration and any custom CSS into a standalone HTML document that loads the Scalar library via the specified CDN.
import { ScalarRender } from './src/scalar/index'
import type { OpenAPIV3 } from 'openapi-types'
// Example usage (internal/manual implementation)
const html = ScalarRender(
{ title: 'My API', description: 'An example API' } as OpenAPIV3.InfoObject,
{
cdn: 'https://cdn.jsdelivr.net/npm/@scalar/api-reference',
customCss: '.my-class { color: red; }'
},
'{"openapi": "3.0.0", ...}' // embedSpec
);