Add compression to Elysia Server. Supports gzip
, deflate
, and brotli
.
Note Brotli Compression is only available and supported by Bun v1.1.8 or higher
bun add elysia-compress
This plugin provides a function to automatically compress every Response sent by Elysia Response. Especially on responses in the form of JSON Objects, Text and Stream (Server Sent Events).
Currently, the following encoding tokens are supported, using the first acceptable token in this order:
br
gzip
deflate
If an unsupported encoding is received or if the 'accept-encoding'
header is missing, it will not compress the payload.
The plugin automatically decides if a payload should be compressed based on its content-type
; if no content type is present, it will assume text/plain
. But if you send a response in the form of an Object then it will be detected automatically as application/json
The global compression hook is enabled by default. To disable it, pass the option { as: 'scoped' }
or { as: 'scoped' }
You can read in-depth about Elysia Scope on this page
import { Elysia } from 'elysia'
import { compression } from 'elysia-compress'
const app = new Elysia()
.use(
compression({
as: 'scoped',
}),
)
.get('/', () => ({ hello: 'world' }))
The minimum byte size for a response to be compressed. Defaults to 1024
.
const app = new Elysia().use(
compression({
threshold: 2048,
}),
)
You can selectively disable response compression by using the x-no-compression
header in the request.
You can still disable this option by adding disableByHeader: true
to options. Default to false
const app = new Elysia().use(
compression({
disableByHeader: true,
}),
)
You can tune compression by setting the brotliOptions
and zlibOptions
properties. These properties are passed directly to native node zlib
methods, so they should match the corresponding class definitions.
const app = new Elysia().use(
compression({
brotliOptions: {
params: {
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT, // useful for APIs that primarily return text
[zlib.constants.BROTLI_PARAM_QUALITY]: 4, // default is 4, max is 11, min is 0
},
},
zlibOptions: {
level: 6, // default is typically 6, max is 9, min is 0
},
}),
)
By default, elysia-compress
prioritizes compression as described Usage. You can change that by passing an array of compression tokens to the encodings
option:
const app = new Elysia().use(
compression({
// Only support gzip and deflate, and prefer deflate to gzip
encodings: ['deflate', 'gzip'],
}),
)