Telaio
API Reference

Server API Reference

Complete reference for registerPlugins, registerHooks, registerSwagger, registerScalar, and all request decorators.

Server API Reference

The server module provides low-level registration functions used internally by the Telaio builder. You may call these directly when composing a Fastify application manually without the builder.


registerPlugins(server, pluginOptions, options)

Registers the set of optional Fastify plugins. Each plugin is guarded by a dynamic import(): if the peer dependency is not installed, the plugin is silently skipped.

import { registerPlugins } from 'telaio/server';

await registerPlugins(server, pluginOptions, {
  logger,
  baseDir: '/app',
  skipAutoload: false,
});

Signature

async function registerPlugins(
  server: FastifyInstance,
  pluginOptions: PluginOptions,
  options: {
    logger: Logger;
    baseDir: string;
    skipAutoload?: boolean;
  }
): Promise<void>

PluginOptions

Pass true to enable a plugin with all defaults, or an object to override specific fields. All keys are optional.

OptionTypePeer DependencyDescription
corsCorsOptions | boolean@fastify/corsCORS headers
helmetHelmetOptions | boolean@fastify/helmetSecurity headers
cookieCookieOptions | boolean@fastify/cookieCookie parsing and signing
compressCompressOptions | boolean@fastify/compressResponse compression (gzip/brotli)
multipartMultipartOptions | boolean@fastify/multipartMultipart form data handling
websocketWebsocketOptions | boolean@fastify/websocketWebSocket upgrade support
ssebooleanfastify-sse-v2Server-Sent Events support
autoloadAutoloadOptions | false@fastify/autoloadRoute auto-discovery from directory

Plugins are registered in fixed order regardless of how they appear in the options object:

SSE -> Cookie -> WebSocket -> Compress -> CORS -> Helmet -> Multipart -> Autoload

CorsOptions

FieldTypeDefaultDescription
credentialsbooleantrueAllow cookies and Authorization headers in cross-origin requests
allowedHeadersstring[]--Restrict which request headers are permitted
maxAgenumber86400Preflight cache TTL in seconds
originsstring[]--Allowed origins; omit to reflect the request origin
methodsstring[]GET POST PUT PATCH DELETE OPTIONSAllowed HTTP methods

HelmetOptions

FieldTypeDescription
enableCSPNoncesbooleanAttach a CSP nonce to every request
contentSecurityPolicyboolean | { directives?: Record<string, string[]> }Raw CSP directives to merge with Telaio's defaults; set to false to disable CSP entirely

CookieOptions

FieldTypeDescription
secretstringSecret used to sign cookies; omit for unsigned cookies

CompressOptions

FieldTypeDescription
globalbooleanCompress all responses globally; defaults to per-route opt-in

MultipartOptions

FieldTypeDescription
limits.fieldNameSizenumberMax field name length in bytes
limits.fieldSizenumberMax field value size in bytes
limits.fieldsnumberMax number of non-file fields
limits.fileSizenumberMax file size in bytes (default 10 MB)
limits.filesnumberMax number of files per request (default 1)

WebsocketOptions

FieldTypeDescription
optionsRecord<string, unknown>Passthrough options for @fastify/websocket

AutoloadOptions

FieldTypeDescription
dirstringDirectory to scan for route files; defaults to src/routes
routeParamsbooleanEnable directory-based route parameters (e.g. [id])
autoHooksbooleanAutomatically load hook files alongside routes
cascadeHooksbooleanApply parent directory hooks to nested routes

registerAutoload(server, pluginOptions, options)

Registers only the autoload plugin. Used internally when autoload needs to run after other setup has completed.

async function registerAutoload(
  server: FastifyInstance,
  pluginOptions: PluginOptions,
  options: {
    logger: Logger;
    baseDir: string;
  }
): Promise<void>

registerHooks(server, options)

Registers Fastify lifecycle hooks: request timing, auth session decoration, temp file management, and onReady/onClose callbacks.

import { registerHooks } from 'telaio/server';

await registerHooks(server, {
  logger,
  tempFiles: true,
  onReady: async () => {
    logger.info('Server ready');
  },
  onClose: async () => {
    await pool.end();
  },
});

Signature

async function registerHooks(
  server: FastifyInstance,
  options: {
    logger: Logger;
    tempFiles?: boolean;
    onReady?: () => Promise<void>;
    onClose?: () => Promise<void>;
  }
): Promise<void>

Options

FieldTypeDescription
loggerLoggerPino logger instance
tempFilesbooleanEnable temp file management decorators on every request
onReady() => Promise<void>Callback invoked when the server finishes startup
onClose() => Promise<void>Callback invoked when the server begins shutdown

Request decorators

registerHooks adds these decorators to every Fastify request. Auth decorators are added by buildAuthPlugin when an auth adapter is registered.

DecoratorTypeRequiresDescription
req.startTimenumber | undefinedAlwaysRequest start timestamp (Unix ms)
req.maybeAuthSessionTSession | nullAuth adapterSession if authenticated, null otherwise
req.getAuthSession()TSessionAuth adapterReturns session or throws UnauthorizedError (401)
req.hasAuthSession()booleanAuth adaptertrue if a session is present
req.tempFilesstring[]tempFiles: truePaths of temp files registered for this request
req.addTempFile(path)voidtempFiles: trueRegister a file path for automatic cleanup after response
req.getTempFile(opts?)stringtempFiles: trueGenerate and register a unique temp file path; accepts { extension?: string }

All temp files registered via req.addTempFile or req.getTempFile are deleted automatically after the response is sent, including on error paths.


registerSwagger(server, options)

Registers OpenAPI 3.1 spec generation via @fastify/swagger.

import { registerSwagger } from 'telaio/server';

await registerSwagger(server, {
  info: {
    title: 'My API',
    version: '1.0.0',
    description: 'REST API for the My App platform',
  },
});

Signature

async function registerSwagger(
  server: FastifyInstance,
  options: SwaggerOptions
): Promise<void>

SwaggerOptions

FieldTypeRequiredDescription
info.titlestringYesAPI title shown in the spec and UI
info.versionstringNoAPI version string (e.g. 1.0.0)
info.descriptionstringNoAPI description; supports Markdown

Additional standard OpenAPI fields can be passed alongside info and are forwarded to @fastify/swagger.

Schema $id values become $ref component names in the generated spec. A schema registered with $id: 'User' appears as #/components/schemas/User in every route that references it via AutoRef.


registerScalar(server, options?)

Mounts the Scalar interactive API reference UI. Requires registerSwagger to be called first.

import { registerScalar } from 'telaio/server';

registerScalar(server, {
  // Passthrough options for @scalar/fastify-api-reference
});

Signature

function registerScalar(
  server: FastifyInstance,
  options?: ScalarOptions
): void

URLs

URLContents
/docsScalar interactive API explorer UI
/docs/jsonRaw OpenAPI JSON spec

ScalarOptions are passed through to @scalar/fastify-api-reference. Any valid Scalar configuration option can be provided.


registerSchemas and registerBuiltinSchemas

These functions are exported from telaio/schema, not telaio/server, but are part of the server setup pipeline.

See the Schema API Reference for full documentation on registerSchemas(fastify, schemasDir) and registerBuiltinSchemas(fastify).

On this page