https://github.com/fastify/fastify-accepts-serializer
Serializer according to the accept header
https://github.com/fastify/fastify-accepts-serializer
fastify fastify-plugin
Last synced: 3 days ago
JSON representation
Serializer according to the accept header
- Host: GitHub
- URL: https://github.com/fastify/fastify-accepts-serializer
- Owner: fastify
- License: mit
- Created: 2017-08-02T17:53:56.000Z (almost 8 years ago)
- Default Branch: main
- Last Pushed: 2025-05-01T10:38:23.000Z (11 days ago)
- Last Synced: 2025-05-09T00:08:49.236Z (3 days ago)
- Topics: fastify, fastify-plugin
- Language: JavaScript
- Homepage: https://npmjs.com/package/@fastify/accepts-serializer
- Size: 134 KB
- Stars: 28
- Watchers: 15
- Forks: 12
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-fastify - `fastify-accepts-serializer`
README
# @fastify/accepts-serializer
[](https://github.com/fastify/fastify-accepts-serializer/actions/workflows/ci.yml)
[](https://www.npmjs.com/package/@fastify/accepts-serializer)
[](https://github.com/neostandard/neostandard)Serialize according to the `Accept` header.
## Install
```sh
npm i @fastify/accepts-serializer
```### Compatibility
| Plugin version | Fastify version |
| ---------------|-----------------|
| `>=6.x` | `^5.x` |
| `^5.x` | `^4.x` |
| `>=3.x <5.x` | `^3.x` |
| `^2.x` | `^2.x` |
| `^1.x` | `^1.x` |Please note that if a Fastify version is out of support, then so are the corresponding versions of this plugin
in the table above.
See [Fastify's LTS policy](https://github.com/fastify/fastify/blob/main/docs/Reference/LTS.md) for more details.## Usage
```jsconst 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
})// 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'})
})
```## Behavior
For each route, a SerializerManager is defined, which has both per-route and global serializer definitions.
The MIME type `application/json` is always handled by `fastify` if no serializer is registered for that MIME type.
If no `default` key is specified in configuration, all requests with an unknown `Accept` header will be replied to with a 406 response (a boom error is used).
## License
Licensed under [MIT](./LICENSE).