Skip to content

Repository files navigation

Lambda@Edge Function Controller

A simple and efficient controller for managing AWS Lambda@Edge functions in CloudFront distributions.

Overview

Lambda@Edge Function Controller is a TypeScript library that provides a clean API for attaching and detaching Lambda@Edge functions to/from CloudFront distributions. It handles the complex CloudFront configuration updates automatically, making it easy to manage edge functions in your CDN setup.

Features

  • Simple API: Easy-to-use methods for attaching and detaching Lambda@Edge functions
  • Event Type Support: Supports all Lambda@Edge event types (viewer-request, viewer-response, origin-request, origin-response)
  • Automatic Configuration: Automatically generates and updates CloudFront distribution configurations
  • TypeScript Support: Full TypeScript support with comprehensive type definitions
  • AWS SDK v3: Built with the latest AWS SDK for JavaScript v3
  • Logging: Built-in logging with Bunyan for debugging and monitoring
  • Flexible Configuration: Support for custom AWS clients and configurations

Use Cases

  • A/B Testing: Quickly switch between different Lambda@Edge functions for testing
  • Feature Flags: Enable/disable features at the edge without redeploying
  • Security Updates: Rapidly deploy security patches to edge functions
  • Performance Optimization: Test different edge function configurations
  • Development Workflow: Manage edge functions across different environments
  • Disaster Recovery: Quickly rollback to previous edge function versions

Installation

npm install lambda-edge-controller
# or
yarn add lambda-edge-controller

Quick Start

Basic Usage

import { LambdaEdgeController } from 'lambda-edge-controller';

// Create a controller instance
const controller = new LambdaEdgeController(
  'arn:aws:lambda:us-east-1:123456789012:function:my-edge-function:1',
  'viewer-request'
);

// Attach the Lambda@Edge function to a CloudFront distribution
await controller.attachEdgeFunction('E1234567890ABCD');

// Detach the Lambda@Edge function from a CloudFront distribution
await controller.detachEdgeFunction('E1234567890ABCD');

Advanced Usage with Custom Configuration

import { LambdaEdgeController } from 'lambda-edge-controller';
import { CloudFrontClient } from '@aws-sdk/client-cloudfront';

// Create a custom CloudFront client
const cloudfrontClient = new CloudFrontClient({
  region: 'us-east-1',
  credentials: {
    accessKeyId: 'YOUR_ACCESS_KEY',
    secretAccessKey: 'YOUR_SECRET_KEY'
  }
});

// Create controller with custom client
const controller = new LambdaEdgeController(
  'arn:aws:lambda:us-east-1:123456789012:function:my-edge-function:1',
  'viewer-request',
  { cloudfront: cloudfrontClient }
);

// Enable debug logging
controller.enableDebugger();

// Attach edge function
await controller.attachEdgeFunction('E1234567890ABCD');

API Reference

Constructor

new LambdaEdgeController(
  lambdaArn: string,
  eventType?: EventType,
  client?: ControllerClient
)

Parameters:

  • lambdaArn: The ARN of your Lambda@Edge function
  • eventType: The CloudFront event type (default: 'viewer-request')
  • client: Optional custom AWS clients

Event Types:

  • viewer-request: Function executes before CloudFront forwards a request to the origin
  • viewer-response: Function executes before CloudFront returns the response to the viewer
  • origin-request: Function executes before CloudFront forwards the request to the origin
  • origin-response: Function executes after CloudFront receives the response from the origin

Methods

attachEdgeFunction(distributionId: string): Promise<any>

Attaches the Lambda@Edge function to the specified CloudFront distribution.

detachEdgeFunction(distributionId: string): Promise<any>

Removes the Lambda@Edge function from the specified CloudFront distribution.

enableDebugger(): this

Enables detailed logging for debugging purposes.

disableDebugger(): this

Disables detailed logging.

Testing with Examples

The project includes comprehensive examples and testing utilities in the examples/ directory.

Setup for Testing

  1. Install dependencies:
# Install project dependencies
pnpm install

# Install examples dependencies
cd examples
npm install
  1. Build the library:
# From project root
pnpm run build
  1. Configure environment:
cd examples
npm run setup
# This creates a .env file from env.example
  1. Edit .env file:
# Required settings
LAMBDA_ARN=arn:aws:lambda:us-east-1:123456789012:function:my-edge-function:1
CLOUDFRONT_DISTRIBUTION_ID=E1234567890ABCD

# Optional settings
EVENT_TYPE=viewer-request
AWS_REGION=us-east-1
AWS_PROFILE=default
DEBUG=true

Running Tests

Unit Tests

# Run all unit tests
pnpm test

# Run tests in watch mode
pnpm run test:watch

# Run tests with coverage
pnpm run test:dev

Integration Tests

# Run the comprehensive integration test
cd examples
npm test

# Or directly
node aws-test.js

Manual Testing

# Test specific functionality
node -e "
const { LambdaEdgeController } = require('../dist/index.js');
const controller = new LambdaEdgeController('your-lambda-arn', 'viewer-request');
console.log('Controller created successfully');
"

Test Coverage

The examples directory provides:

  • Basic Tests: Controller creation and configuration validation
  • Advanced Tests: Custom AWS client configuration
  • Integration Tests: Real AWS environment testing
  • Error Handling: Comprehensive error scenarios
  • Configuration Validation: Environment setup verification

Development

Prerequisites

  • Node.js >= 18.18.0 (pnpm 10 needs 18.12+, and the pinned @typescript-eslint/parser 7.x needs ^18.18.0 || >=20)
  • pnpm (the version is pinned by packageManager in package.json; corepack enable picks it up)
  • AWS credentials with CloudFront permissions
  • TypeScript knowledge

Development Commands

# Install dependencies
pnpm install

# Run linter
pnpm run lint
pnpm run lint --fix

# Type check
pnpm run typecheck

# Run tests
pnpm test
pnpm run test:watch

# Build
pnpm run build

# Generate documentation
pnpm run doc

Required IAM Permissions

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "cloudfront:GetDistribution",
        "cloudfront:UpdateDistribution"
      ],
      "Resource": "*"
    }
  ]
}

Release Process

Releases are automated. Merging to main runs semantic-release on CircleCI (config: workflows/publish/npm-polyrepo-semantic-release.yaml in hideokamoto/circleci-configurations, settings: .releaserc.json).

  1. Merge a pull request whose commits follow Conventional Commits.
  2. CircleCI runs lint / typecheck / build / test, decides the next version from the commits since the last v* tag (fix: → patch, feat: → minor, feat!: or BREAKING CHANGE → major; chore:, docs:, ci:, build: etc. do not release), pushes the tag, publishes to npm with OIDC trusted publishing (no npm token), and creates the GitHub Release.

Do not run npm version or npm publish by hand, and do not bump version in package.json (the published version comes from the tag).

Architecture

The library consists of three main components:

  1. LambdaEdgeController: Main controller class for managing edge functions
  2. ConfigUpdator: Handles CloudFront configuration updates
  3. Models: TypeScript interfaces and types

Class Diagram

LambdaEdgeController
├── CloudFrontClient (AWS SDK)
├── ConfigUpdator
└── Logger (Bunyan)

ConfigUpdator
├── Lambda ARN management
├── Event type handling
└── Distribution config updates

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Follow the commit message convention (Conventional Commits)
  4. Run tests and linting
  5. Submit a pull request

Commit Message Format

git commit -m "<type>[optional scope]: <description>

[optional body]

[optional footer]"

Types:

  • feat: New feature
  • fix: Bug fix
  • docs: Documentation changes
  • style: Code style changes
  • refactor: Code refactoring
  • test: Adding or updating tests
  • chore: Maintenance tasks

License

MIT License - see LICENSE file for details.

Support

Related Links


日本語版: README_ja.md

Releases

Packages

Used by

Contributors

Languages