Skip to content

FastifyAdapter

reference
2 min readUpdated

Kind: Class

Source: packages/platform-fastify/adapters/fastify-adapter.ts

Part of: Platform Fastify

FastifyAdapter bridges the framework’s HTTP abstractions to a Fastify server instance. It initializes the Fastify application, registers request/response lifecycle hooks, exposes common HTTP route methods, and starts the server through overloaded listen() methods.

Extends: AbstractHttpAdapter

Methods

MethodSignatureReturns
setOnRequestHook`setOnRequestHook(hook: ( request: TRequest, reply: TReply, done: (err?: Error) => void, ) => voidPromise)`
setOnResponseHook`setOnResponseHook(hook: ( request: TRequest, reply: TReply, done: (err?: Error) => void, ) => voidPromise)`
initinit()void
listen`listen(port: stringnumber, callback: () => void)`
listen`listen(port: stringnumber, hostname: string, callback: () => void)`
listen`listen(listenOptions: stringnumber
getget(args: any[])void
postpost(args: any[])void
headhead(args: any[])void
deletedelete(args: any[])void
putput(args: any[])void
patchpatch(args: any[])void
optionsoptions(args: any[])void
searchsearch(args: any[])void
propfindpropfind(args: any[])void
proppatchproppatch(args: any[])void
mkcolmkcol(args: any[])void
copycopy(args: any[])void
movemove(args: any[])void
locklock(args: any[])void
unlockunlock(args: any[])void
applyVersionFilterapplyVersionFilter(handler: Function, version: VersionValue, versioningOptions: VersioningOptions)VersionedRoute<TRequest, TReply>
reply`reply(response: TRawResponseTReply, body: any, statusCode: number)`
status`status(response: TRawResponseTReply, statusCode: number)`
endend(response: TReply, message: string)void
renderrender(response: TReply & { view: Function }, view: string, options: any)void
redirectredirect(response: TReply, statusCode: number, url: string)void
setErrorHandlersetErrorHandler(handler: Parameters<TInstance['setErrorHandler']>[0])void
setNotFoundHandlersetNotFoundHandler(handler: Function)void
getHttpServergetHttpServer()T
getInstancegetInstance()T
registerregister(plugin: TRegister['0'], opts: TRegister['1'])void
injectinject()LightMyRequestChain
inject`inject(opts: InjectOptionsstring)`
inject`inject(opts: InjectOptionsstring)`
closeclose()void
initHttpServerinitHttpServer()void
useStaticAssetsuseStaticAssets(options: FastifyStaticOptions)void
setViewEngine`setViewEngine(options: FastifyViewOptionsstring)`
isHeadersSentisHeadersSent(response: TReply)boolean
getHeadergetHeader(response: any, name: string)void
setHeadersetHeader(response: TReply, name: string, value: string)void
appendHeaderappendHeader(response: any, name: string, value: string)void
getRequestHostnamegetRequestHostname(request: TRequest)string
getRequestMethodgetRequestMethod(request: TRequest)string
getRequestUrlgetRequestUrl(request: TRequest)string
getRequestUrlgetRequestUrl(request: TRawRequest)string
getRequestUrlgetRequestUrl(request: TRequest & TRawRequest)string
enableCorsenableCors(options: FastifyCorsOptions)void
registerParserMiddlewareregisterParserMiddleware(prefix: string, rawBody: boolean)void

Properties

PropertyType
loggerany
instanceTInstance
_pathPrefixstring

Where it refuses work

  • FastifyAdapter stops the work with Error when !isString(value) && !Array.isArray(value) — “Version constraint should be a string or an array of strings.”.
  • FastifyAdapter stops the work with an early return when Array.isArray(version).
  • FastifyAdapter stops the work with an early return when this.versioningOptions?.type === VersioningType.CUSTOM.
  • FastifyAdapter stops the work with an early return when this.isMiddieRegistered.
  • FastifyAdapter stops the work with an early return when err.code !== 'ERR_SERVER_NOT_RUNNING'.
  • FastifyAdapter stops the work with an early return when this._isParserRegistered.

When something fails

  • FastifyAdapter handles failure in 2 places: it lets it reach the caller in all 2.

Diagram

mermaid
graph LR
  App[Application] --> Adapter[FastifyAdapter]
  Adapter --> Hooks[Request / Response Hooks]
  Adapter --> Routes[GET / POST / HEAD / DELETE Routes]
  Adapter --> Fastify[Fastify Server]
  Fastify --> Client[HTTP Clients]

Usage

ts
import { FastifyAdapter } from '@platform-fastify/adapters/fastify-adapter';

const adapter = new FastifyAdapter();

adapter.setOnRequestHook(async (request, reply) => {
  request.log.info({ url: request.url }, 'Incoming request');

  // Example authentication guard
  if (request.headers['x-api-key'] !== process.env.API_KEY) {
    return reply.code(401).send({ message: 'Unauthorized' });
  }
});

adapter.setOnResponseHook(async (request, reply) => {
  request.log.info(
    { url: request.url, statusCode: reply.statusCode },
    'Response sent',
  );
});

adapter.get('/health', async () => {
  return { status: 'ok' };
});

adapter.post('/users', async (request, reply) => {
  const user = request.body;

  reply.code(201);
  return { user };
});

await adapter.init();
adapter.listen(3000);

AI Coding Instructions

  • Register lifecycle hooks with setOnRequestHook() and setOnResponseHook() before calling init() or listen().
  • Use the adapter’s route helpers (get, post, head, and delete) instead of registering routes directly on the underlying Fastify instance when working within the abstraction.
  • Ensure handlers return serializable response values or explicitly send a response through Fastify’s reply object.
  • Call init() before starting the server when initialization is not handled automatically by the surrounding application bootstrap.
  • Preserve Fastify request/reply semantics in hooks and route handlers, including returning early after sending an error response.

Relationships

  • IMPORTS → HttpStatus
  • IMPORTS → Logger
  • IMPORTS → RawBodyRequest
  • IMPORTS → RequestMethod
  • IMPORTS → StreamableFile
  • IMPORTS → VERSION_NEUTRAL
  • IMPORTS → VersioningOptions
  • IMPORTS → VersioningType
  • IMPORTS → VersionValue
  • IMPORTS → loadPackage
  • IMPORTS → isString
  • IMPORTS → isUndefined
  • IMPORTS → AbstractHttpAdapter
  • IMPORTS → LegacyRouteConverter

Was this page helpful?

Download as PDF
FastifyAdapter — NestJS head-to-head