@standardserver/fastify
v0.8.0
Published
Readme
@standardserver/fastify
@standardserver/fastify adapts Fastify request and reply objects to the transport-agnostic request and response model defined by Standard Server.
Standard Server provides a unified interface for client-server communication across HTTP and message-based transports. It lets you write handlers against the same request, response, body, and streaming primitives whether the underlying transport is the Fetch API, Node.js HTTP, HTTP/2, or a peer-style message channel.
Standard Server ships as a small ecosystem of packages:
| Package | Description |
| ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| @standardserver/core | The shared contract: types, body parsing rules, validators, and SSE helpers |
| @standardserver/fetch | Fetch API adapter for browsers, workers, and other Fetch-based runtimes |
| @standardserver/node | Node.js HTTP and HTTP/2 adapter |
| @standardserver/fastify | Fastify adapter built on the Node.js adapter |
| @standardserver/aws-lambda | AWS Lambda adapter with response streaming |
| @standardserver/peer | Message-based adapter for WebSocket, MessagePort, and custom transports |
| @standardserver/shared | Internal utilities shared across the ecosystem |
This package is the Fastify adapter for that model. It builds on @standardserver/node, reusing the same body, URL, and abort-signal primitives, while routing the response back through Fastify's reply lifecycle so hooks, plugins, and serializers keep working. Both Fastify() and Fastify({ http2: true }) instances are supported.
fastify is a peer dependency, so the adapter always uses the Fastify version installed in your project.
Package overview
The package exposes two helpers and their option shapes:
| Group | Exports | Purpose |
| ----------------------- | ------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| Request and response | toStandardLazyRequest(), sendStandardResponse() | Adapt Fastify request and reply objects to Standard Server |
| Types and option shapes | AnyFastifyRequest, AnyFastifyReply, FastifyRequest, FastifyReply, SendStandardResponseOptions | Type handler inputs and serializer options |
Both helpers accept AnyFastifyRequest and AnyFastifyReply, which are FastifyRequest and FastifyReply widened over every raw server. That is what lets the same call site work for Fastify(), Fastify({ http2: true }), typed route generics, hooks, and encapsulated plugins alike.
Lower-level helpers such as toStandardBody(), toNodeHttpBody(), and toEventStream() are not re-exported here — import them from @standardserver/node when you need them.
Server-side request handling
Use toStandardLazyRequest() to convert an incoming Fastify request into a StandardLazyRequest, then sendStandardResponse() to write the resulting StandardResponse back through the reply.
import type { StandardLazyRequest, StandardResponse } from '@standardserver/core'
import { sendStandardResponse, toStandardLazyRequest } from '@standardserver/fastify'
import Fastify from 'fastify'
async function handle(request: StandardLazyRequest): Promise<StandardResponse> {
const body = await request.resolveBody()
return {
status: 200,
headers: { 'content-type': 'application/json' },
body: {
ok: true,
method: request.method,
url: request.url,
received: body,
},
}
}
const fastify = Fastify()
fastify.all('/*', async (req, reply) => {
const standardRequest = toStandardLazyRequest(req, reply)
const standardResponse = await handle(standardRequest)
await sendStandardResponse(reply, standardResponse, {/** options */})
})
await fastify.listen({ port: 3000 })sendStandardResponse() resolves once the response is fully flushed, and rejects if the underlying connection errors. Do not return a value from the route handler afterwards — Fastify would try to send a second response.
[!TIP] When sending responses, you can pass additional options such as event-stream keep-alive.
Resolving Body
resolveBody(hint?) returns the body Fastify already parsed with its own content type parsers, if there is one. Otherwise it falls back to toStandardBody() from @standardserver/node, which follows the shared Standard Server resolution rules: an explicit hint wins, then the standard-server header, then inference from the content headers. See how body parsing works in the core README for the full algorithm.
Because Fastify's own parsers win, a hint only applies to bodies Fastify left unparsed. Fastify ships parsers for application/json and text/plain, and rejects every other content type with 415 Unsupported Media Type unless you register one. To let the adapter own body parsing end to end, register a catch-all parser that leaves the body untouched:
// optional: also drop fastify's built-in json and text/plain parsers
fastify.removeAllContentTypeParsers()
fastify.addContentTypeParser('*', (req, payload, done) => {
done(null, undefined)
})Register it inside an encapsulated plugin if you only want it to apply to the routes that serve Standard Server handlers.
[!TIP] For efficient communication, set the
standard-serverheader to explicitly hint the body type, especially for file or binary streaming. For example, if you upload a file with a commoncontent-typesuch asapplication/jsonbut omit thestandard-serverheader, the server may interpret it as JSON and parse it unexpectedly.
Fastify behavior to be aware of
Fastify owns the reply lifecycle, so a few of its rules apply to the response the adapter writes:
Empty
content-typeis rejected. ABloborFilewithout a type is sent with an emptycontent-typeheader, which Fastify answers with415 Unsupported Media Typebefore your handler runs. Normalize it first if clients may send one:fastify.addHook('onRequest', async (req) => { if (req.headers['content-type'] === '') { delete req.headers['content-type'] } })JSON responses gain a charset. Fastify rewrites any
content-typewhose media type containsjsonto include; charset=utf-8. The payload itself is never serialized twice, because the adapter always hands Fastify an already-encoded string or stream.set-cookieis merged, not replaced. Cookies set by plugins such as@fastify/cookieare kept, and the ones on yourStandardResponseare appended to them. Every other header is overwritten.Streams are managed by Fastify. Streaming bodies are piped and destroyed by Fastify itself, including when the client aborts mid-response.
Learn more
For the project overview and the shared contract, see the core documentation. For the Node.js primitives this adapter is built on, see the Node.js adapter documentation.
Sponsors
Like what we build over at middleapi? You can help keep it going here: GitHub Sponsors. Every bit helps! 🚀
🏆 Platinum Sponsor
🥈 Silver Sponsor
Generous Sponsors
Sponsors
Backers
With thanks to 37 past sponsors who helped get us here.
License
Distributed under the MIT License. See LICENCE for more information.
