CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-fastify--compress

Fastify plugin providing compression and decompression utilities for HTTP responses and requests.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

plugin-configuration.mddocs/

Plugin Configuration

Core plugin setup and configuration options for @fastify/compress, including global settings, encoding preferences, and content-type matching.

Capabilities

Main Plugin Function

Registers the compression plugin with Fastify, configuring global compression and decompression behavior.

/**
 * Registers @fastify/compress plugin with Fastify instance
 * @param fastify - Fastify instance to register with
 * @param options - Plugin configuration options
 * @param next - Callback function for plugin registration completion
 */
function fastifyCompress(
  fastify: FastifyInstance,
  options: FastifyCompressOptions,
  next: (err?: Error) => void
): void;

Usage Examples:

const fastify = require('fastify')({ logger: true });

// Basic setup with global compression
await fastify.register(require('@fastify/compress'), {
  global: true
});

// Advanced configuration
await fastify.register(require('@fastify/compress'), {
  global: true,
  encodings: ['br', 'gzip', 'deflate'],
  threshold: 2048,
  customTypes: /^(text\/|application\/(json|xml))/,
  brotliOptions: {
    params: {
      [require('zlib').constants.BROTLI_PARAM_QUALITY]: 6
    }
  }
});

Configuration Validation Rules

The plugin validates configuration options at registration time with these rules:

// Validation constraints
const VALIDATION_RULES = {
  // Arrays must have at least 1 item
  encodings: 'Array must contain at least 1 encoding',
  requestEncodings: 'Array must contain at least 1 encoding',
  // forceRequestEncoding must be included in requestEncodings
  forceRequestEncoding: 'Must be included in requestEncodings array',
  // threshold must be a positive number
  threshold: 'Must be a positive number',
  // Node.js version requirements
  zstd: 'Requires Node.js 22.15+ or 23.8+ for zstd support'
};

Plugin Options Interface

Complete configuration interface for the compression plugin.

/**
 * Configuration options for @fastify/compress plugin
 */
interface FastifyCompressOptions {
  /** Enable global compression for all routes (default: true) */
  global?: boolean;
  
  /** Supported compression encodings in preference order */
  encodings?: EncodingToken[];
  
  /** Minimum payload size in bytes to trigger compression (default: 1024) */
  threshold?: number;
  
  /** Custom content-type matcher - RegExp or function to determine compressible types */
  customTypes?: RegExp | CompressibleContentTypeFunction;
  
  /** Brotli compression options */
  brotliOptions?: BrotliOptions;
  
  /** Zlib compression options for gzip/deflate */
  zlibOptions?: ZlibOptions;
  
  /** Remove Content-Length header when compressing (default: true) */
  removeContentLengthHeader?: boolean;
  
  /** Inflate pre-compressed content for clients that don't support compression */
  inflateIfDeflated?: boolean;
  
  /** Handler for unsupported Accept-Encoding values */
  onUnsupportedEncoding?: (
    encoding: string, 
    request: FastifyRequest, 
    reply: FastifyReply
  ) => string | Buffer | Stream;
  
  /** Supported request decompression encodings */
  requestEncodings?: EncodingToken[];
  
  /** Force specific encoding for request decompression */
  forceRequestEncoding?: EncodingToken;
  
  /** Handler for unsupported request Content-Encoding values */
  onUnsupportedRequestEncoding?: (
    encoding: string, 
    request: FastifyRequest,
    reply: FastifyReply
  ) => Error | undefined | null;
  
  /** Handler for invalid compressed request payloads */
  onInvalidRequestPayload?: (
    encoding: string, 
    request: FastifyRequest, 
    error: Error
  ) => Error | undefined | null;
  
  /** Custom zlib implementation */
  zlib?: unknown;
}

Route-Level Configuration

Routes can override global compression settings using route-specific options.

/**
 * Route-level compression options (subset of plugin options)
 */
type RouteCompressOptions = Pick<FastifyCompressOptions,
  | 'brotliOptions'
  | 'customTypes'
  | 'encodings' 
  | 'inflateIfDeflated'
  | 'onUnsupportedEncoding'
  | 'removeContentLengthHeader'
  | 'threshold'
  | 'zlib'
  | 'zlibOptions'
>;

/**
 * Route-level decompression options (subset of plugin options)
 */
type RouteDecompressOptions = Pick<FastifyCompressOptions,
  | 'forceRequestEncoding'
  | 'onInvalidRequestPayload'
  | 'onUnsupportedRequestEncoding'
  | 'requestEncodings'
  | 'zlib'
>;

Usage Examples:

// Route with custom compression settings
fastify.get('/api/data', {
  compress: {
    threshold: 512,
    encodings: ['br', 'gzip']
  }
}, async (request, reply) => {
  return await getData();
});

// Route with compression disabled
fastify.get('/api/small', {
  compress: false
}, async (request, reply) => {
  return { small: 'payload' };
});

// Route with custom decompression
fastify.post('/api/upload', {
  decompress: {
    requestEncodings: ['gzip', 'deflate'],
    onInvalidRequestPayload: (encoding, request, error) => {
      return new Error(`Failed to decompress ${encoding}: ${error.message}`);
    }
  }
}, async (request, reply) => {
  // Handle decompressed payload
  return { received: request.body };
});

Content-Type Matching

Configure which content types should be compressed using built-in patterns or custom functions.

/**
 * Function to determine if a content-type should be compressed
 * @param contentType - The Content-Type header value
 * @returns true if the content should be compressed
 */
type CompressibleContentTypeFunction = (contentType: string) => boolean;

Usage Examples:

// Using RegExp for custom types
await fastify.register(require('@fastify/compress'), {
  customTypes: /^(text\/|application\/(json|xml|javascript))/
});

// Using function for complex logic
await fastify.register(require('@fastify/compress'), {
  customTypes: (contentType) => {
    // Compress all text types and specific application types
    return contentType.startsWith('text/') || 
           ['application/json', 'application/xml', 'application/javascript']
             .includes(contentType.split(';')[0]);
  }
});

Compression Algorithm Options

Fine-tune compression behavior with algorithm-specific options.

/**
 * Brotli compression options
 */
interface BrotliOptions {
  /** Brotli compression parameters */
  params?: {
    [key: number]: number;
  };
}

/**
 * Zlib compression options (for gzip and deflate)
 */
interface ZlibOptions {
  /** Flush mode */
  flush?: number;
  /** Final flush mode */
  finishFlush?: number;
  /** Chunk size in bytes */
  chunkSize?: number;
  /** Window size (8-15 for deflate, 8-16 for gzip) */
  windowBits?: number;
  /** Compression level (0-9) */
  level?: number;
  /** Memory usage level (1-9) */
  memLevel?: number;
  /** Compression strategy */
  strategy?: number;
  /** Compression dictionary */
  dictionary?: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer;
}

Usage Examples:

const zlib = require('zlib');

await fastify.register(require('@fastify/compress'), {
  brotliOptions: {
    params: {
      // Higher quality but slower compression
      [zlib.constants.BROTLI_PARAM_QUALITY]: 8,
      // Larger window for better compression on large files
      [zlib.constants.BROTLI_PARAM_LGWIN]: 22
    }
  },
  zlibOptions: {
    level: 6,        // Balanced compression vs speed
    windowBits: 15,  // Maximum window size
    memLevel: 8,     // Default memory usage
    strategy: zlib.constants.Z_DEFAULT_STRATEGY
  }
});

Encoding Preferences

Configure which compression algorithms are supported and their preference order.

/**
 * Supported compression encoding identifiers
 */
type EncodingToken = 'zstd' | 'br' | 'gzip' | 'deflate' | 'identity';

Usage Examples:

// Prefer modern algorithms first
await fastify.register(require('@fastify/compress'), {
  encodings: ['br', 'zstd', 'gzip', 'deflate', 'identity']
});

// Only support specific algorithms
await fastify.register(require('@fastify/compress'), {
  encodings: ['gzip', 'deflate'],
  requestEncodings: ['gzip', 'deflate']
});

Error Handling Configuration

Configure custom handlers for unsupported encodings and compression errors.

/**
 * Handler for unsupported Accept-Encoding values
 * @param encoding - The unsupported encoding from Accept-Encoding header
 * @param request - Fastify request object
 * @param reply - Fastify reply object  
 * @returns Response payload to send instead of compressed content
 */
type UnsupportedEncodingHandler = (
  encoding: string,
  request: FastifyRequest,
  reply: FastifyReply
) => string | Buffer | Stream;

/**
 * Handler for unsupported request Content-Encoding values
 * @param encoding - The unsupported encoding from Content-Encoding header
 * @param request - Fastify request object
 * @param reply - Fastify reply object
 * @returns Error to throw, or null/undefined to use default error
 */
type UnsupportedRequestEncodingHandler = (
  encoding: string,
  request: FastifyRequest,
  reply: FastifyReply
) => Error | undefined | null;

/**
 * Handler for invalid compressed request payloads  
 * @param encoding - The encoding that failed to decompress
 * @param request - Fastify request object
 * @param error - The decompression error
 * @returns Error to throw, or null/undefined to use default error
 */
type InvalidRequestPayloadHandler = (
  encoding: string,
  request: FastifyRequest,
  error: Error
) => Error | undefined | null;

Usage Examples:

await fastify.register(require('@fastify/compress'), {
  onUnsupportedEncoding: (encoding, request, reply) => {
    // Log unsupported encoding attempts
    request.log.warn(`Unsupported encoding requested: ${encoding}`);
    // Return uncompressed content
    return JSON.stringify({ error: 'Compression not supported' });
  },
  
  onUnsupportedRequestEncoding: (encoding, request) => {
    // Return custom error for unsupported request encodings
    return new Error(`Cannot decompress Content-Encoding: ${encoding}`);
  },
  
  onInvalidRequestPayload: (encoding, request, error) => {
    // Log decompression failures
    request.log.error(`Failed to decompress ${encoding} payload: ${error.message}`);
    // Return custom error
    return new Error(`Invalid ${encoding} compressed payload`);
  }
});

docs

index.md

plugin-configuration.md

request-decompression.md

response-compression.md

tile.json