Performance Middleware
Response Compression
Compress HTTP responses with brotli, gzip, or deflate, negotiated per request from Accept-Encoding, to reduce bandwidth usage and improve application performance.
Overview
Without compression, you're wasting bandwidth, slowing down page loads, and increasing server costs. With MoroJS, you get 60-80% bandwidth reduction automatically.
Traditional compression setup requires manual configuration. We handle that automatically.
1import { middleware } from '@morojs/moro';
2
3// Basic compression with defaults
4app.use(middleware.compression());
5
6// Compression is now enabled for all responses
7app.get('/api/data', (req, res) => {
8 return { data: largeDataset };
9});Without Compression
- Wasted bandwidth (uncompressed responses)
- Slower page loads
- Higher server costs
- Poor mobile experience
With MoroJS
- 60-80% bandwidth reduction
- Faster page loads
- Lower server costs
- Better mobile experience
Automatic
Detects client support and compresses automatically
Efficient
60-80% bandwidth reduction with minimal CPU overhead
Flexible
gzip, deflate, or brotli. Configurable per route.
How It Works
MoroJS provides built-in response compression middleware that automatically compresses responses using gzip, deflate, or brotli based on client support. The middleware detects the client's Accept-Encoding header and compresses responses larger than a configurable threshold.
Basic Compression
MoroJS provides built-in response compression middleware that automatically compresses responses using gzip, deflate, or brotli based on client support.
1import { middleware } from '@morojs/moro';
2
3// Basic compression with defaults
4app.use(middleware.compression());
5
6// Compression is now enabled for all responses
7app.get('/api/data', (req, res) => {
8 return { data: largeDataset };
9});Default Behavior
When compression is enabled, MoroJS automatically:
- • Detects client compression support via Accept-Encoding header
- • Compresses responses larger than 1KB by default
- • Prefers brotli, then gzip, then deflate, among the encodings the client accepts
- • Compresses bodies up to 16 KB on the calling thread and sends them with a Content-Length; larger ones go to the threadpool and stream
- • Skips compression for already-compressed content
Advanced Configuration
1import zlib from 'node:zlib';
2import { middleware } from '@morojs/moro';
3
4app.use(middleware.compression({
5 level: 6, // 1-9: the gzip/deflate level, mapped onto brotli quality 1-11
6 threshold: 1024, // bodies smaller than this are never compressed
7 encodings: ['br', 'gzip', 'deflate'], // server preference order (this is the default)
8 maxInlineBytes: 16384, // compressed on the calling thread up to here, on the pool above
9 gzip: { level: 3 }, // zlib options for gzip/deflate; a level here wins over `level`
10 brotli: { // brotli options; a quality here wins over `level`
11 params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 3 }
12 },
13 reuseEncoders: true, // default; keep one encoder per setting and reset it between bodies
14 filter: (req, res) => {
15 // Custom filter - don't compress if client requests no compression
16 if (req.headers['x-no-compression']) {
17 return false;
18 }
19 // Only compress JSON, text, JavaScript, and CSS
20 const contentType = res.getHeader('Content-Type') || '';
21 return /json|text|javascript|css/.test(contentType);
22 }
23}));1// The same options go under performance.compression, where they apply
2// to every response without a middleware.
3const app = await createApp({
4 performance: {
5 compression: {
6 enabled: true, // opt-in
7 level: 6,
8 threshold: 1024,
9 encodings: ['gzip', 'br'],
10 maxInlineBytes: 16384
11 }
12 }
13});How the options interact
- level is one knob for both encoders: the gzip level as given, and a brotli quality it is mapped onto (level 6 is quality 7). Pin either encoder exactly with gzip or brotli, and what you pin wins
- encodings is the server's preference order among what the client accepts. For API-sized JSON, gzip compresses in about half the CPU for a body roughly a tenth larger, so a service measured on throughput may prefer ['gzip', 'br']
- maxInlineBytes (default 16384): a body at or below it is compressed on the calling thread and sent as a single write with a Content-Length; a larger one is compressed on the threadpool and streamed chunked, so a big export never holds the event loop. 0 sends every body through the pool
- reuseEncoders (default true): one encoder per setting is kept and reset between bodies instead of being built and torn down per response. Brotli reuse needs Node 26.11 or later; on older Node brotli falls back to the one-call API by itself
- The brotli window is fitted to the body unless you set BROTLI_PARAM_LGWIN yourself
- A compressed res.json() reply carries Content-Type: application/json, the same type it carries without the middleware
On the native engine the middleware does not wrap res.json and res.send: it hands its settings to the response, and the reply takes the server's own compression path, the one a performance.compression setting takes. A route-level compression() therefore costs one property write per request. A filter is consulted per response, so a middleware with one keeps the wrapping path, as it does on the Node.js server.
Compression Levels
- •
1-3- Fast compression, larger files - •
4-6- Balanced (default: 6) - •
7-9- Maximum compression, slower
Compression Formats
- •
br- Brotli: best compression, preferred by default - •
gzip- Widest client support, about half the CPU - •
deflate- Fallback option
Per-Route Compression
1// The compression factory attaches to a single route through .before()
2import { middleware } from '@morojs/moro';
3
4// Maximum compression for large data endpoints
5app.get('/api/large-data')
6 .before(middleware.compression({ level: 9 }))
7 .handler((req, res) => {
8 return largeDataset; // Automatically compressed
9 });
10
11// Disable compression for specific routes
12app.get('/api/small-data')
13 .before(middleware.compression({ threshold: Infinity })) // Never compress
14 .handler((req, res) => {
15 return { message: 'Small response' };
16 });
17
18// Custom compression for streaming endpoints
19app.get('/api/stream')
20 .before(middleware.compression({
21 level: 4, // Faster compression for streaming
22 filter: (req, res) => {
23 // Only compress if client explicitly requests it
24 return req.headers['accept-encoding']?.includes('gzip');
25 }
26 }))
27 .handler((req, res) => {
28 return streamData();
29 });Performance Impact
Compression Benefits
- • Bandwidth reduction: 60-80% for text-based content
- • Faster page loads: Reduced transfer time
- • Lower server costs: Less bandwidth usage
- • Better mobile experience: Faster on slow connections
- • CPU overhead: Minimal (~5-10ms per response)
Best Practices
Do
- Enable compression for text-based content (JSON, HTML, CSS, JS)
- Use level 6 for balanced performance
- Set appropriate thresholds (1KB+) to avoid overhead
- Put gzip first in encodings when throughput matters more than size
- Compress API responses with large payloads
Don't
- Compress already-compressed formats (images, videos)
- Use maximum compression for real-time endpoints
- Compress very small responses (< 1KB)
- Compress streaming responses without careful configuration
- Ignore client compression preferences
1import zlib from 'node:zlib';
2import { middleware } from '@morojs/moro';
3
4// Production-optimized compression
5app.use(middleware.compression({
6 level: 6, // Balanced compression
7 threshold: 1024, // Only compress responses > 1KB
8 filter: (req, res) => {
9 const contentType = res.getHeader('Content-Type') || '';
10
11 // Don't compress binary formats
12 if (/image|video|audio|application\/(zip|pdf|octet-stream)/.test(contentType)) {
13 return false;
14 }
15
16 // Compress text-based content
17 return /json|text|javascript|css|html|xml/.test(contentType);
18 },
19 brotli: { // Pin the brotli quality instead of deriving it from level
20 params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 4 }
21 }
22}));