### Install @fastify/accepts-serializer Source: https://github.com/fastify/fastify-accepts-serializer/blob/main/README.md Install the plugin using npm. ```sh npm i @fastify/accepts-serializer ``` -------------------------------- ### Register Per-Route Serializers with @fastify/accepts-serializer Source: https://github.com/fastify/fastify-accepts-serializer/blob/main/README.md Configure per-route serializers for Protobuf. This example shows how to define specific serializers for a particular route. ```js // Per-router serializers const config = { serializers: [ { regex: /^application\/x-protobuf$/, serializer: body => AwesomeMessage.encode(AwesomeMessage.create(body)).finish() } ] } fastify.get('/request', { config }, function (req, reply) { reply.send({pippo: 'pluto'}) }) ``` -------------------------------- ### Register Plugin with Global Serializers Source: https://context7.com/fastify/fastify-accepts-serializer/llms.txt Register the plugin globally with an array of serializers, a default MIME type, and an optional cache size. The example demonstrates YAML and MessagePack serialization. ```javascript const fastify = require('fastify')() const YAML = require('yamljs') const msgpack = require('msgpack5')() fastify.register(require('@fastify/accepts-serializer'), { serializers: [ { regex: /^application\/yaml$/, serializer: body => YAML.stringify(body) }, { regex: /^application\/x-msgpack$/, serializer: body => msgpack.encode(body) } ], default: 'application/yaml', // used when Accept header matches nothing cacheSize: 100 // LRU cache limit (default: 100) }) fastify.get('/data', (req, reply) => { reply.send({ hello: 'world' }) }) fastify.listen({ port: 3000 }) // curl -H "Accept: application/yaml" http://localhost:3000/data // → Content-Type: application/yaml // → hello: world // curl -H "Accept: application/x-msgpack" http://localhost:3000/data // → Content-Type: application/x-msgpack // → // curl -H "Accept: text/html" http://localhost:3000/data // → Content-Type: application/yaml (fallback to default) // → hello: world ``` -------------------------------- ### 406 Not Acceptable Behavior Example Source: https://context7.com/fastify/fastify-accepts-serializer/llms.txt Demonstrates the plugin's behavior when no serializer matches the Accept header and no default is configured. It sends a 406 Not Acceptable response listing supported MIME types. ```javascript const fastify = require('fastify')() fastify.register(require('@fastify/accepts-serializer'), { serializers: [ { regex: /^application\/yaml$/, serializer: body => require('yamljs').stringify(body) } ] // no 'default' key }) fastify.get('/strict', (req, reply) => reply.send({ value: 42 })) // curl -H "Accept: text/html" http://localhost:3000/strict // → HTTP 406 // → Content-Type: application/json; charset=utf-8 // → { // "statusCode": 406, // "error": "Not Acceptable", // "message": "Allowed: /^application\/yaml$/,application/json" // } // curl -H "Accept: application/json" http://localhost:3000/strict // → HTTP 200 (application/json is always supported by Fastify) // → Content-Type: application/json; charset=utf-8 // → {"value":42} ``` -------------------------------- ### Bounded LRU Serializer Cache Example Source: https://context7.com/fastify/fastify-accepts-serializer/llms.txt Illustrates configuring the LRU cache size for serializer lookups. The cache prevents unbounded memory growth by capping entries based on the full Accept header string. ```javascript const fastify = require('fastify')() fastify.register(require('@fastify/accepts-serializer'), { cacheSize: 50, // keep at most 50 distinct Accept header entries serializers: [ { regex: /^application\/msgpack$/, serializer: body => require('msgpack5')().encode(body) } ] }) // Inspect the live cache size from inside a handler: fastify.get('/debug', function (req, reply) { console.log('Cache size:', reply.serializer.cache.size) console.log('Cache max:', reply.serializer.cache.max) // → 50 console.log('Cached keys:', reply.serializer.cache.keys()) reply.send({ ok: true }) }) // Repeated requests with the same Accept header reuse the cached entry: // Request 1: Accept: application/msgpack → cache miss, entry stored // Request 2: Accept: application/msgpack → cache hit, no re-evaluation ``` -------------------------------- ### Per-Route Serializers via Route Config Source: https://context7.com/fastify/fastify-accepts-serializer/llms.txt Add route-specific serializers by including a `serializers` array in the route's `config` object. These are checked before global serializers. This example adds Protocol Buffers support to a route. ```javascript const protobuf = require('protobufjs') const YAML = require('yamljs') const root = protobuf.loadSync('test/awesome.proto') const AwesomeMessage = root.lookupType('awesomepackage.AwesomeMessage') const fastify = require('fastify')() fastify.register(require('@fastify/accepts-serializer'), { serializers: [ { regex: /^application\/yaml$/, serializer: body => YAML.stringify(body) } ], default: 'application/yaml' }) // This route additionally supports protobuf const config = { serializers: [ { regex: /^application\/x-protobuf$/, serializer: body => AwesomeMessage.encode(AwesomeMessage.create(body)).finish() } ] } fastify.get('/proto', { config }, (req, reply) => { reply.send({ id: 1, name: 'example' }) }) // curl -H "Accept: application/x-protobuf" http://localhost:3000/proto // → Content-Type: application/x-protobuf // → // curl -H "Accept: application/yaml" http://localhost:3000/proto // → Content-Type: application/yaml (falls through to global serializer) // → id: 1 // → name: example ``` -------------------------------- ### TypeScript Usage with Global and Per-Route Serializers Source: https://context7.com/fastify/fastify-accepts-serializer/llms.txt Shows how to use the plugin with TypeScript, including defining serializer options globally and overriding them per-route. It demonstrates type safety for serializer configurations. ```typescript import fastify from 'fastify' import fastifyAcceptsSerializer, { FastifyAcceptsSerializerPluginOptions, SerializerConfig } from '@fastify/accepts-serializer' import YAML from 'yamljs' const app = fastify() const opts: FastifyAcceptsSerializerPluginOptions = { serializers: [ { regex: /^application\/yaml$/, serializer: (body: unknown): string => YAML.stringify(body) } satisfies SerializerConfig ], default: 'application/yaml', cacheSize: 200 } app.register(fastifyAcceptsSerializer, opts) app.get('/typed', (req, reply) => { reply.send({ message: 'typed response' }) }) // Per-route config is also typed via FastifyContextConfig augmentation: app.get( '/per-route', { config: { serializers: [ { regex: /^application\/xml$/, serializer: body => `${JSON.stringify(body)}` } ] } }, (req, reply) => reply.send({ xml: true }) ) app.listen({ port: 3000 }) ``` -------------------------------- ### Register Global Serializers with @fastify/accepts-serializer Source: https://github.com/fastify/fastify-accepts-serializer/blob/main/README.md Register the plugin globally with custom serializers for YAML and MessagePack. Sets 'application/yaml' as the default and configures a cache size. ```js const protobuf = require('protobufjs') const YAML = require('yamljs') const msgpack = require('msgpack5')() const root = protobuf.loadSync('test/awesome.proto') const AwesomeMessage = root.lookupType('awesomepackage.AwesomeMessage') const fastify = require('fastify')() // Global serializers fastify.register(require('@fastify/accepts-serializer'), { serializers: [ { regex: /^application\/yaml$/, serializer: body => YAML.stringify(body) }, { regex: /^application\/x-msgpack$/, serializer: body => msgpack.encode(body) } ], default: 'application/yaml', // MIME type used if Accept header does not match anything cacheSize: 100 // max number of Accept header combinations to cache (default: 100) }) ``` -------------------------------- ### Default MIME Type Fallback Configuration Source: https://context7.com/fastify/fastify-accepts-serializer/llms.txt Configure a `default` MIME type to handle requests with unmatched Accept headers, preventing a 406 error. Setting `default: 'application/json'` uses Fastify's built-in JSON serializer as the fallback. ```javascript const fastify = require('fastify')() // Fallback to YAML for unrecognised Accept headers fastify.register(require('@fastify/accepts-serializer'), { serializers: [ { regex: /^application\/yaml$/, serializer: body => require('yamljs').stringify(body) } ], default: 'application/yaml' }) fastify.get('/item', (req, reply) => reply.send({ status: 'ok' })) // curl -H "Accept: text/html" http://localhost:3000/item // → HTTP 200 // → Content-Type: application/yaml // → status: ok // Without default (or default: undefined), the same request yields: // → HTTP 406 // → { "statusCode": 406, "error": "Not Acceptable", "message": "Allowed: /^application\/yaml$/,application/json" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.