Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
ab8820d
feat: add brotli to supported compression 🗜️
bricss May 19, 2024
51d3f2c
chore: address comments 📝
bricss May 19, 2024
db9799b
chore: address comments 📝
bricss May 26, 2024
dc84dce
feat: add br & zstd to supported compression 🗜️ algos
bricss Jul 26, 2025
b83c6b2
fix: cure ⚕️ ci
bricss Jul 26, 2025
f91efbb
feat: adjust default priority 🎛️
bricss Jul 27, 2025
b7d4a97
feat: make built-in `br` & `zstd` algos opt-in and disabled by default
bricss Jul 29, 2025
0081822
chore: brush up 💄
bricss Jul 29, 2025
b4e456d
feat: add support for compression 🗜 options 🎛️
bricss Aug 2, 2025
2f4b7e0
fix: fixate 🪛 types
bricss Aug 2, 2025
9ac5e5b
fix: fixate 🪛 types, take 2 🎬
bricss Aug 2, 2025
45e3ec7
chore: clean up 🧽
bricss Aug 2, 2025
6e1e5d3
feat: address comments 📝
bricss Aug 3, 2025
7a4e7ca
feat: reverse ↩️ ci min node version 🔢
bricss Aug 3, 2025
60b093d
feat: betterment 💈
bricss Aug 3, 2025
82a36cf
feat: address comments 📝
bricss Aug 3, 2025
13f532b
fix: cure 🩹 code coverage
bricss Aug 4, 2025
57f87c5
refactor: refinement ⚗️
bricss Sep 14, 2025
70642d1
fix: adjust 🪛 default params
bricss Sep 14, 2025
b346d5e
feat: betterment 💈
bricss Sep 14, 2025
07c3e00
feat: betterment 💈 take 2 🎬
bricss Sep 14, 2025
eb647c5
refactor: refinement ⚗️ take 2 🎬
bricss Sep 15, 2025
13c587e
feat: add opt to disable decompression ⛔
bricss Sep 15, 2025
c262277
feat: improve tests 🧪
bricss Sep 15, 2025
9a21c01
fixup!: fixate 🪛 missing types 📙
bricss Aug 30, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 36 additions & 6 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,35 @@ assigned one or more (array):

#### <a name="server.options.compression" /> `server.options.compression`

Default value: `{ minBytes: 1024 }`.
Default value: `{ decompress: true, encodings: { gzip: true, deflate: true, br: false, zstd: false }, minBytes: 1024 }`.

Defines server handling of content encoding requests. If `false`, response content encoding is
disabled and no compression is performed by the server.
disabled, and no compression is performed by the server.

#### <a name="server.options.compression.decompress" /> `server.options.compression.decompress`

Default value: `true`.

Controls whether the server automatically decompresses incoming content encoding requests.
If `false`, no decompression automatically performed by the server.

#### <a name="server.options.compression.encodings" /> `server.options.compression.encodings`

Default value: `{ gzip: true, deflate: true, br: false, zstd: false }`.

Configures the built-in support of compression algorithms aka encodings, represented by the object of kv pairs.

Available values for each kv pair:

- `true` - enables the encoding with default options.
- `false` - disables the encoding.

Note that default encoder and decoder options can be configured at the server default [route configuration](#server.options.routes)

Zstd compression is experimental (see [node Zstd documentation](https://nodejs.org/api/zlib.html#zlibcreatezstdcompressoptions)).

Disabling an encoding allows custom compression algorithm to be applied by
[`server.encoder()`](#server.encoder()) and [`server.decoder()`](#server.decoder()).

##### <a name="server.options.compression.minBytes" /> `server.options.compression.minBytes`

Expand All @@ -110,6 +135,13 @@ Default value: '1024'.
Sets the minimum response payload size in bytes that is required for content encoding compression.
If the payload size is under the limit, no compression is performed.

##### <a name="server.options.compression.priority" /> `server.options.compression.priority`

Default value: `null`.

Sets the priority for content encoding compression algorithms in descending order,
e.g.: `['zstd', 'br', 'gzip', 'deflate']`.

#### <a name="server.options.debug" /> `server.options.debug`

Default value: `{ request: ['implementation'] }`.
Expand Down Expand Up @@ -1290,8 +1322,7 @@ are called, where:

### <a name="server.decoder()" /> `server.decoder(encoding, decoder)`

Registers a custom content decoding compressor to extend the built-in support for `'gzip'` and
'`deflate`' where:
Registers a custom content decoding compressor to extend the built-in support where:

- `encoding` - the decoder name string.

Expand Down Expand Up @@ -1487,8 +1518,7 @@ The `dependencies` configuration accepts one of:

### <a name="server.encoder()" /> `server.encoder(encoding, encoder)`

Registers a custom content encoding compressor to extend the built-in support for `'gzip'` and
'`deflate`' where:
Registers a custom content encoding compressor to extend the built-in support where:

- `encoding` - the encoder name string.

Expand Down
88 changes: 74 additions & 14 deletions lib/compression.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,87 @@ const Zlib = require('zlib');
const Accept = require('@hapi/accept');
const Bounce = require('@hapi/bounce');
const Hoek = require('@hapi/hoek');
const Boom = require('@hapi/boom');

const defaultBrotliOptions = {
params: {
[Zlib.constants.BROTLI_PARAM_QUALITY]: 4
}
};

const defaultZstdOptions = {
params: {
[Zlib.constants.ZSTD_c_compressionLevel]: 6
}
};

const internals = {
common: ['gzip, deflate', 'deflate, gzip', 'gzip', 'deflate', 'gzip, deflate, br']
common: [
'gzip, deflate, br, zstd',
Comment thread
bricss marked this conversation as resolved.
'gzip, deflate, br',
'zstd',
'br',
'gzip, deflate',
'deflate, gzip',
'gzip',
'deflate'
],
provision: new Map([
['zstd', [
(options = {}) => Zlib.createZstdCompress(Hoek.applyToDefaults(defaultZstdOptions, options)),
(options) => Zlib.createZstdDecompress(options)
]],
['br', [
(options = {}) => Zlib.createBrotliCompress(Hoek.applyToDefaults(defaultBrotliOptions, options)),
(options) => Zlib.createBrotliDecompress(options)
]],
['deflate', [
(options) => Zlib.createDeflate(options),
(options) => Zlib.createInflate(options)
]],
['gzip', [
(options) => Zlib.createGzip(options),
(options) => Zlib.createGunzip(options)
]]
])
};


exports = module.exports = internals.Compression = class {

decoders = {
gzip: (options) => Zlib.createGunzip(options),
deflate: (options) => Zlib.createInflate(options)
};
decoders = {};

encodings = ['identity', 'gzip', 'deflate'];
encodings = ['identity'];
Comment thread
bricss marked this conversation as resolved.

encoders = {
identity: null,
gzip: (options) => Zlib.createGzip(options),
deflate: (options) => Zlib.createDeflate(options)
identity: null
};

#common = null;
#options = null;

constructor() {
constructor(options) {

this._updateCommons();
this.#options = options;
if (!this.#options) {
return this._updateCommons();
}

for (const [encoding, [encoder, decoder]] of internals.provision.entries()) {
const conditions = this.#options?.encodings?.[encoding];
if (conditions) {
this.addEncoder(encoding, encoder);
if (this.#options.decompress !== false) {
this.addDecoder(encoding, decoder);
}
else {
this.addDecoder(encoding, () => {

throw Boom.unsupportedMediaType();
});
}
}
}
}

_updateCommons() {
Expand Down Expand Up @@ -89,13 +143,13 @@ exports = module.exports = internals.Compression = class {
return null;
}

const request = response.request;
if (!request._core.settings.compression ||
length !== null && length < request._core.settings.compression.minBytes) {
if (!this.#options ||
length !== null && length < this.#options.minBytes) {

return null;
}

const request = response.request;
const mime = request._core.mime.type(response.headers['content-type'] || 'application/octet-stream');
if (!mime.compressible) {
return null;
Expand All @@ -116,4 +170,10 @@ exports = module.exports = internals.Compression = class {
Hoek.assert(encoder !== undefined, `Unknown encoding ${encoding}`);
return encoder(request.route.settings.compression[encoding]);
}

setPriority(priority) {

this.encodings = [...new Set([...priority, ...this.encodings])];
this._updateCommons();
}
};
10 changes: 9 additions & 1 deletion lib/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,15 @@ internals.server = Validate.object({
autoListen: Validate.boolean(),
cache: Validate.allow(null), // Validated elsewhere
compression: Validate.object({
minBytes: Validate.number().min(1).integer().default(1024)
decompress: Validate.boolean().default(true),
encodings: Validate.object({
gzip: Validate.boolean().default(true),
deflate: Validate.boolean().default(true),
br: Validate.boolean().default(false),
zstd: Validate.boolean().default(false)
}).default(),
minBytes: Validate.number().min(1).integer().default(1024),
priority: Validate.array().items(Validate.string().valid('gzip', 'deflate', 'br', 'zstd')).default(null)
})
.allow(false)
.default(),
Expand Down
7 changes: 6 additions & 1 deletion lib/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ exports = module.exports = internals.Core = class {
app = {};
auth = new Auth(this);
caches = new Map(); // Cache clients
compression = new Compression();
compression = null;
controlled = null; // Other servers linked to the phases of this server
dependencies = []; // Plugin dependencies
events = new Podium.Podium(internals.events);
Expand Down Expand Up @@ -119,6 +119,7 @@ exports = module.exports = internals.Core = class {
this.settings = settings;
this.type = type;

this.compression = new Compression(this.settings.compression);
this.heavy = new Heavy(this.settings.load);
this.mime = new Mimos(this.settings.mime);
this.router = new Call.Router(this.settings.router);
Expand All @@ -127,6 +128,10 @@ exports = module.exports = internals.Core = class {
this._debug();
this._initializeCache();

if (this.settings.compression.priority) {
this.compression.setPriority(this.settings.compression.priority);
}

if (this.settings.routes.validate.validator) {
this.validator = Validation.validator(this.settings.routes.validate.validator);
}
Expand Down
6 changes: 5 additions & 1 deletion lib/types/server/encoders.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createDeflate, createGunzip, createGzip, createInflate } from 'zlib';
import { createBrotliCompress, createBrotliDecompress, createDeflate, createGunzip, createGzip, createInflate, createZstdCompress, createZstdDecompress } from 'zlib';

/**
* Available [content encoders](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder).
Expand All @@ -7,6 +7,8 @@ export interface ContentEncoders {

deflate: typeof createDeflate;
gzip: typeof createGzip;
br: typeof createBrotliCompress;
zstd: typeof createZstdCompress;
}

/**
Expand All @@ -16,4 +18,6 @@ export interface ContentDecoders {

deflate: typeof createInflate;
gzip: typeof createGunzip;
br: typeof createBrotliDecompress;
zstd: typeof createZstdDecompress;
}
8 changes: 8 additions & 0 deletions lib/types/server/options.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,15 @@ import { CacheProvider, ServerOptionsCache } from './cache';
import { SameSitePolicy, ServerStateCookieOptions } from './state';

export interface ServerOptionsCompression {
decompress?: boolean;
encodings?: {
gzip?: boolean;
deflate?: boolean;
br?: boolean;
zstd?: boolean;
};
minBytes: number;
priority?: string[];
}

/**
Expand Down
4 changes: 2 additions & 2 deletions lib/types/server/server.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ export class Server<A = ServerApplicationState> {
cache: ServerCache;

/**
* Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' where:
* Registers a custom content decoding compressor to extend the built-in support where:
* @param encoding - the decoder name string.
* @param decoder - a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the
* return value is an object compatible with the output of node's zlib.createGunzip().
Expand Down Expand Up @@ -392,7 +392,7 @@ export class Server<A = ServerApplicationState> {
dependency(dependencies: Dependencies, after?: ((server: Server) => Promise<void>) | undefined): void;

/**
* Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where:
* Registers a custom content encoding compressor to extend the built-in support where:
* @param encoding - the encoder name string.
* @param encoder - a function using the signature function(options) where options are the encoding specific options configured in the route compression option, and the return value is an object
* compatible with the output of node's zlib.createGzip().
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
"@hapi/lab": "^25.3.2",
"@hapi/vision": "^7.0.3",
"@hapi/wreck": "^18.1.0",
"@types/node": "^18.19.130",
"@types/node": "^22.20.1",
"handlebars": "^4.7.9",
"joi": "^17.13.3",
"legacy-readable-stream": "npm:readable-stream@^1.0.34",
Expand Down
3 changes: 3 additions & 0 deletions test/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
const ChildProcess = require('child_process');
const Http = require('http');
const Net = require('net');
const Zlib = require('zlib');

const internals = {};

Expand Down Expand Up @@ -30,3 +31,5 @@ internals.hasIPv6 = () => {
exports.hasLsof = internals.hasLsof();

exports.hasIPv6 = internals.hasIPv6();

exports.hasZstd = !!Zlib.constants.ZSTD_CLEVEL_DEFAULT;
Loading