Skip to content
Aback Tools Logo

Lambda@Edge Compression Script Generator

Generate a production-ready Lambda@Edge function that adds Brotli and GZIP compression to CloudFront responses — for origins that don't support compression natively. Configure the event type (Origin Response or Viewer Response), compression algorithm, and optional headers. The lambda@edge compression script generator produces the function code, IAM trust policy, IAM execution policy, and step-by-step AWS CLI deployment commands. All generation happens in your browser with no signup required.

Lambda@Edge Compression Script Generator

Configure the options below to generate a Lambda@Edge function that adds Brotli and GZIP compression to CloudFront responses. The lambda@edge compression script generator produces the function code, IAM trust policy, IAM execution policy, and deployment steps. All generation happens in your browser — no signup required.

Node.js 20.x is recommended. Lambda@Edge supports Node.js 18.x and 20.x.

Response Headers

Skip Conditions

/**
 * Lambda@Edge Compression Script
 * Event type: origin-response
 * Runtime: nodejs20.x
 * Generated by AbackTools — https://abacktools.com
 */

'use strict';

// Content types that benefit from compression
const COMPRESSIBLE_TYPES = [
  'text/html', 'text/css', 'text/plain', 'text/xml', 'text/javascript',
  'application/javascript', 'application/x-javascript', 'application/json',
  'application/ld+json', 'application/xml', 'application/rss+xml',
  'application/atom+xml', 'image/svg+xml', 'font/ttf', 'font/otf',
];

// Already-compressed formats — skip to avoid overhead
const SKIP_TYPES = [
  'image/jpeg', 'image/png', 'image/webp', 'image/avif', 'image/gif',
  'image/bmp', 'video/mp4', 'video/webm', 'audio/mpeg', 'audio/ogg',
  'application/zip', 'application/gzip', 'application/x-brotli',
  'font/woff2',
];

exports.handler = async (event) => {
  const { request, response } = event.Records[0].cf;

  // Get the Accept-Encoding header from the viewer request
  const acceptEncoding =
    (request.headers['accept-encoding'] || [{ value: '' }])[0].value.toLowerCase();

  // Get the Content-Type of the response
  const contentType =
    (response.headers['content-type'] || [{ value: '' }])[0].value.split(';')[0].trim().toLowerCase();

  // Skip if already compressed
  const alreadyEncoded = response.headers['content-encoding'];
  if (alreadyEncoded && alreadyEncoded[0]?.value) {
    return response;
  }

  // Skip already-compressed content types
  if (SKIP_TYPES.some(t => contentType.startsWith(t))) {
    return response;
  }

  // Only compress compressible content types
  const isCompressible = COMPRESSIBLE_TYPES.some(t => contentType.startsWith(t));
  if (!isCompressible) {
    return response;
  }

  // Skip small responses (compression overhead not worth it)
  const bodyLength = response.body ? Buffer.byteLength(response.body, 'utf8') : 0;
  if (bodyLength < 1024) {
    return response;
  }

  // Determine the best encoding to use
  let encoding = null;
  if (acceptEncoding.includes('br')) {
    encoding = 'br';
  } else if (acceptEncoding.includes('gzip')) {
    encoding = 'gzip';
  }

  if (!encoding) {
    return response;
  }

  // Compress the response body
  try {
    const zlib = require('zlib');
    const body = Buffer.from(
      response.body,
      response.bodyEncoding === 'base64' ? 'base64' : 'utf8'
    );

    let compressed;
    if (encoding === 'br') {
      compressed = zlib.brotliCompressSync(body, {
        params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 6 },
      });
    } else {
      compressed = zlib.gzipSync(body, { level: 6 });
    }

    // Only use compressed version if it's actually smaller
    if (compressed.length < body.length) {
      response.body = compressed.toString('base64');
      response.bodyEncoding = 'base64';
      response.headers['content-encoding'] = [{ key: 'Content-Encoding', value: encoding }];
      response.headers['content-length'] = [{ key: 'Content-Length', value: String(compressed.length) }];
    }
  } catch (err) {
    console.error('Compression failed:', err);
    // Return uncompressed response on error
  }

  // Add Vary: Accept-Encoding so CloudFront caches separate variants
  const existingVary = (response.headers['vary'] || [{ value: '' }])[0].value;
  if (!existingVary.toLowerCase().includes('accept-encoding')) {
    response.headers['vary'] = [{
      key: 'Vary',
      value: existingVary ? `${existingVary}, Accept-Encoding` : 'Accept-Encoding',
    }];
  }

  // Set Cache-Control for compressed assets
  if (!response.headers['cache-control']) {
    response.headers['cache-control'] = [{
      key: 'Cache-Control',
      value: 'public, max-age=31536000, stale-while-revalidate=86400',
    }];
  }

  return response;
};

Lambda@Edge requirement: Functions must be deployed in us-east-1(N. Virginia) regardless of your CloudFront distribution's origin region. Lambda@Edge does not support environment variables or VPC access.

Why Use Our Lambda@Edge Compression Script Generator?

Instant Lambda@Edge Compression Script

Generate a production-ready Lambda@Edge compression function instantly — no AWS documentation diving, no Node.js zlib API research. Our lambda@edge compression script generator produces correctly formatted function code, IAM policies, and deployment steps in seconds.

Secure Lambda@Edge Compression Script Generator Online

Your configuration choices never leave your device when you use this lambda@edge compression script generator. All script generation runs entirely in your browser — no server requests, no data retention, 100% private. Safe for configuring production CloudFront distributions.

Lambda@Edge Compression Script Generator — No Installation

Generate Lambda@Edge compression scripts directly in any modern browser with no AWS CLI installation, no Node.js setup, and no account required. The lambda@edge compression script generator works on Windows, macOS, Linux, and mobile.

Complete Package: Script, IAM Policies, and Deploy Steps

The lambda@edge compression script generator produces everything you need — the function code, IAM trust policy, IAM execution policy, and step-by-step AWS CLI deployment commands. Includes real-time warnings for common misconfigurations like missing Vary headers.

Common Use Cases for Lambda@Edge Compression Script Generator

CloudFront Distribution Compression

Add Brotli and GZIP compression to a CloudFront distribution that serves content from an S3 bucket or custom origin that doesn't support compression. The lambda@edge compression script generator produces an Origin Response function that compresses responses before CloudFront caches them — so compression runs once per cache miss, not on every request.

API Gateway + CloudFront Compression

Compress API Gateway responses served through CloudFront. API Gateway supports GZIP but not Brotli — the lambda@edge compression script generator adds Brotli support for modern browsers while falling back to GZIP for legacy clients, improving API response transfer sizes by 15–25% over GZIP alone.

S3 Static Site Compression

Add dynamic compression to a static site hosted on S3 and served through CloudFront. S3 does not compress responses — the lambda@edge compression script generator adds an Origin Response function that compresses HTML, CSS, JavaScript, and JSON before CloudFront caches the compressed version.

Multi-Region CDN Optimization

Reduce bandwidth costs across all CloudFront edge locations by compressing responses at the origin. The lambda@edge compression script generator produces a function that runs in us-east-1 but executes at CloudFront edge locations worldwide — reducing transfer sizes by 60–80% for text-based content.

Legacy Origin Compression Upgrade

Add Brotli compression to a legacy origin server that only supports GZIP or no compression. The lambda@edge compression script generator intercepts Origin Response events and applies Brotli compression for modern browsers — no changes required to the origin server.

Security Headers + Compression Bundle

Combine compression with security headers in a single Lambda@Edge function. The lambda@edge compression script generator optionally adds X-Content-Type-Options, X-Frame-Options, and X-XSS-Protection headers alongside compression — reducing the number of Lambda@Edge functions needed per CloudFront behavior.

Understanding Lambda@Edge Compression

What is Lambda@Edge Compression?

Lambda@Edge is an AWS service that runs Node.js functions at CloudFront edge locations worldwide. A Lambda@Edge compression function intercepts CloudFront responses and applies GZIP or Brotli compression before the response is cached or delivered to the viewer. This is useful when your origin server (S3, API Gateway, EC2, or a custom server) does not support compression — the Lambda@Edge function adds compression transparently at the CDN layer. Our lambda@edge compression script generator produces a complete Node.js function using the built-in zlib module (no external dependencies) that handles Accept-Encoding negotiation, content type filtering, Vary header management, and Cache-Control headers.

How Our Lambda@Edge Compression Script Generator Works

  1. 1Configure your options: Select the CloudFront event type (Origin Response or Viewer Response), Node.js runtime, compression algorithm (Brotli preferred, GZIP only, or Brotli only), and optional features like Vary headers, Cache-Control, and security headers. The lambda@edge compression script generator updates the output in real time.
  2. 2Copy the script, IAM policies, and deploy steps: The generator produces four outputs — the function code (index.js), IAM trust policy, IAM execution policy, and AWS CLI deployment commands. All generation runs in your browser — no data is sent anywhere.
  3. 3Deploy to AWS and associate with CloudFront: Create the Lambda function in us-east-1, publish a version, and associate it with your CloudFront distribution behavior. The deploy steps tab provides the exact AWS CLI commands with placeholders for your account ID and distribution ID.

Origin Response vs Viewer Response

  • Origin Response (recommended): Runs after CloudFront receives the response from your origin, before it is cached. The compressed response is stored in the CloudFront cache — subsequent requests for the same object are served from cache without invoking the Lambda function. This is the most cost-effective approach: compression runs once per cache miss.
  • Viewer Response: Runs before CloudFront sends the response to the viewer, after the cache lookup. This means the Lambda function runs on every request — including cache hits. Use Viewer Response only when you need to modify responses that are already cached, or when you need to add per-viewer headers that cannot be cached.
  • Lambda@Edge limits: Functions must be deployed in us-east-1. Maximum execution time: 5 seconds (Viewer) or 30 seconds (Origin). Maximum response body size: 1 MB (Viewer) or 1 MB (Origin). No environment variables or VPC access. No external npm packages — use only Node.js built-ins.
  • CloudFront compression vs Lambda@Edge:CloudFront has a built-in compression feature (enabled in distribution settings) that supports GZIP and Brotli. Use CloudFront's built-in compression when possible — it is free and has no Lambda invocation cost. Use Lambda@Edge compression only when you need custom logic (content type filtering, security headers, or compression for origins that send incorrect Content-Type headers).

Important Lambda@Edge Limitations

Lambda@Edge functions have strict constraints: they must be deployed in us-east-1(N. Virginia) regardless of your origin region. They cannot use environment variables, VPC connections, or external npm packages — the generated script uses only Node.js's built-in zlib module. The maximum response body size is 1 MB — responses larger than 1 MB cannot be modified by Lambda@Edge. For large responses, consider using CloudFront Functions(for header manipulation only) or enabling CloudFront's built-in compression instead. Lambda@Edge also has a cold start latency of 100–500ms on the first invocation at each edge location.

Frequently Asked Questions About Lambda@Edge Compression Script Generator

A lambda@edge compression script generator produces a ready-to-deploy Node.js function for AWS Lambda@Edge that adds Brotli and GZIP compression to CloudFront responses. Our free lambda@edge compression script generator online produces the function code, IAM trust policy, IAM execution policy, and AWS CLI deployment steps — all in your browser with no signup required.

CloudFront has built-in compression (free, no Lambda cost) that supports GZIP and Brotli — use it when possible. Use Lambda@Edge compression when your origin sends incorrect Content-Type headers, when you need custom content type filtering, when you want to combine compression with security headers in one function, or when you need compression for origins that CloudFront's built-in compression doesn't support.

Use Origin Response — it runs once per cache miss and stores the compressed response in CloudFront's cache. Subsequent requests are served from cache without invoking Lambda. Viewer Response runs on every request including cache hits, which is significantly more expensive and adds latency to every response.

Yes. All script generation runs entirely in your browser using JavaScript. No configuration data is sent to any server, stored remotely, or transmitted over the network. The lambda@edge compression script generator is completely safe for configuring production CloudFront distributions.

Yes — 100% free, forever. No signup, no account, no premium tier, and no ads. Generate unlimited Lambda@Edge compression scripts completely free.

AWS requires all Lambda@Edge functions to be created in the us-east-1 (N. Virginia) region. When you associate the function with a CloudFront distribution, AWS automatically replicates it to all CloudFront edge locations worldwide. This is an AWS architectural requirement — it applies regardless of where your origin or CloudFront distribution is located.

Lambda@Edge functions can include npm packages if you deploy a ZIP file containing node_modules. However, the generated script uses only Node.js's built-in zlib module — no external packages needed. This keeps the deployment package small (under 1 KB) and eliminates dependency management. Lambda@Edge has a 1 MB deployment package limit for Viewer Request/Response and 50 MB for Origin Request/Response.

Lambda@Edge can only modify response bodies up to 1 MB in size. Responses larger than 1 MB are returned unmodified. For large responses, consider enabling CloudFront's built-in compression (which has no size limit) or compressing at the origin server instead.

Test with curl: "curl -H "Accept-Encoding: br, gzip" -I https://your-cloudfront-domain.com/". Look for Content-Encoding: br or Content-Encoding: gzip in the response headers. You can also check CloudWatch Logs in us-east-1 for Lambda@Edge execution logs — they appear in log groups named /aws/lambda/us-east-1.your-function-name.