npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@composurecdk/cloudfront

v0.8.3

Published

Composable CloudFront distribution builder with well-architected defaults

Readme

@composurecdk/cloudfront

CloudFront builders for ComposureCDK.

This package provides a fluent builder for CloudFront distributions with secure, AWS-recommended defaults. It wraps the CDK Distribution construct — refer to the CDK documentation for the full set of configurable properties.

Distribution Builder

import { createDistributionBuilder } from "@composurecdk/cloudfront";
import { S3BucketOrigin } from "aws-cdk-lib/aws-cloudfront-origins";

const cdn = createDistributionBuilder()
  .origin(S3BucketOrigin.withOriginAccessControl(bucket))
  .comment("My website CDN")
  .build(stack, "CDN");

Every DistributionProps property (except defaultBehavior.origin) is available as a fluent setter on the builder. The origin is set via the dedicated .origin() method, which supports Ref for cross-component wiring.

Cross-component wiring

The origin method accepts a Ref for use in composed systems:

import { compose, ref } from "@composurecdk/core";
import type { BucketBuilderResult } from "@composurecdk/s3";

const cdn = createDistributionBuilder().origin(
  ref<BucketBuilderResult>("site", (r) => S3BucketOrigin.withOriginAccessControl(r.bucket)),
);

compose({ site: createBucketBuilder(), cdn }, { site: [], cdn: ["site"] }).build(stack, "Website");

Secure Defaults

createDistributionBuilder applies the following defaults. Each can be overridden via the builder's fluent API.

| Property | Default | Rationale | | --------------------------------------- | --------------------- | ------------------------------------------------------------------------------------------ | | accessLogs | { prefix: "logs/" } | Auto-creates an S3 logging bucket for the access log audit trail under the logs/ prefix. | | priceClass | PRICE_CLASS_100 | North America and Europe edge locations — sufficient and cost-effective. | | httpVersion | HTTP2_AND_3 | Enables HTTP/2 and HTTP/3 (QUIC) for improved performance. | | defaultRootObject | "index.html" | Standard for static website hosting. | | minimumProtocolVersion | TLS_V1_2_2021 | Requires TLS 1.2+ to prevent older, less secure protocol negotiation. | | defaultBehavior.viewerProtocolPolicy | REDIRECT_TO_HTTPS | Ensures all viewer traffic is encrypted in transit. | | defaultBehavior.responseHeadersPolicy | SECURITY_HEADERS | Applies managed security headers (HSTS, X-Content-Type-Options, etc.). |

These defaults are guided by the AWS Well-Architected Security Pillar.

The defaults are exported as DISTRIBUTION_DEFAULTS for visibility and testing:

import { DISTRIBUTION_DEFAULTS } from "@composurecdk/cloudfront";

Overriding defaults

import { PriceClass, ViewerProtocolPolicy } from "aws-cdk-lib/aws-cloudfront";

const cdn = createDistributionBuilder()
  .origin(myOrigin)
  .priceClass(PriceClass.PRICE_CLASS_ALL)
  .accessLogs(false)
  .defaultBehavior({ viewerProtocolPolicy: ViewerProtocolPolicy.ALLOW_ALL })
  .build(stack, "CDN");

Access logging

CloudFront standard access logging is configured through a single .accessLogs(config) setting. By default, the builder creates a dedicated logging bucket (using @composurecdk/s3 with its secure defaults, plus BUCKET_OWNER_PREFERRED object ownership which CloudFront standard logging requires) and writes logs under logs/. The created bucket is returned in the build result:

const result = createDistributionBuilder().origin(myOrigin).build(stack, "CDN");

result.distribution; // Distribution
result.accessLogsBucket; // Bucket | undefined

.accessLogs(config) accepts either false to disable access logging, or an object describing how to handle logs:

import { Duration } from "aws-cdk-lib";

// Disable access logging entirely
createDistributionBuilder().origin(myOrigin).accessLogs(false);

// Auto-create a logging bucket with a custom prefix
createDistributionBuilder().origin(myOrigin).accessLogs({ prefix: "cdn/" });

// Include cookies in the logs
createDistributionBuilder().origin(myOrigin).accessLogs({ includeCookies: true });

// Auto-create and customize the logging sub-builder
createDistributionBuilder()
  .origin(myOrigin)
  .accessLogs({
    configure: (sub) => sub.lifecycleRules([{ id: "ShortLogs", expiration: Duration.days(180) }]),
  });

// Bring your own destination bucket
createDistributionBuilder().origin(myOrigin).accessLogs({ destination: myBucket });

// Bring your own destination with a prefix and cookies
createDistributionBuilder()
  .origin(myOrigin)
  .accessLogs({ destination: myBucket, prefix: "cdn/", includeCookies: true });

destination and configure cannot be combined — the destination bucket is user-managed and is not built by this builder.

The config object replaces the default wholesale rather than merging with it. For example, .accessLogs({ includeCookies: true }) does not preserve the default prefix: "logs/" — restate any default you want to keep.

The auto-created logging bucket uses DEFAULT_ACCESS_LOG_BUCKET_LIFECYCLE_RULES from @composurecdk/s3: incomplete multipart uploads are aborted after 7 days and access log objects expire after 2 years (matching the default LogGroup retention so the audit window is consistent across log destinations). CloudFront never deletes its own logs, so this lifecycle is the only thing that bounds the bucket's growth.

Recommended Alarms

The builder creates AWS-recommended CloudWatch alarms by default. No alarm actions are configured — access alarms from the build result to add SNS topics or other actions.

| Alarm | Metric | Default threshold | Created when | | --------------- | ----------------------------- | ----------------- | ------------ | | errorRate | 5xxErrorRate (Average, 1 min) | > 5 (5%) | Always | | originLatency | OriginLatency (p90, 1 min) | > 5000ms | Always |

The originLatency alarm requires additional CloudFront metrics to be enabled on the distribution. With the default treatMissingData: NOT_BREACHING, the alarm will not fire when additional metrics are not enabled.

Function-level alarms (FunctionValidationErrors, FunctionExecutionErrors, FunctionThrottles) require per-function dimensions. Use addAlarm to add them — see Custom alarms below.

The defaults are exported as DISTRIBUTION_ALARM_DEFAULTS for visibility and testing:

import { DISTRIBUTION_ALARM_DEFAULTS } from "@composurecdk/cloudfront";

Customizing thresholds

Override individual alarm properties via recommendedAlarms. Unspecified fields keep their defaults.

const cdn = createDistributionBuilder()
  .origin(myOrigin)
  .recommendedAlarms({
    errorRate: { threshold: 2, evaluationPeriods: 3 },
    originLatency: { threshold: 3000 },
  });

Disabling alarms

Disable all recommended alarms:

builder.recommendedAlarms(false);
// or
builder.recommendedAlarms({ enabled: false });

Disable individual alarms:

builder.recommendedAlarms({ errorRate: false });

Custom alarms

Add custom alarms alongside the recommended ones via addAlarm. The callback receives an AlarmDefinitionBuilder typed to the CloudFront Distribution.

For function-level alarms, provide the function name dimension:

import { Metric } from "aws-cdk-lib/aws-cloudwatch";

const cdn = createDistributionBuilder()
  .origin(myOrigin)
  .addAlarm("functionErrors", (alarm) =>
    alarm
      .metric(
        (dist) =>
          new Metric({
            namespace: "AWS/CloudFront",
            metricName: "FunctionExecutionErrors",
            dimensionsMap: {
              DistributionId: dist.distributionId,
              FunctionName: "MyViewerRequestFn",
              Region: "Global",
            },
            statistic: "Sum",
            period: Duration.minutes(1),
          }),
      )
      .threshold(0)
      .greaterThan()
      .evaluationPeriods(5)
      .datapointsToAlarm(5)
      .description("CloudFront function execution errors detected"),
  );

Applying alarm actions

Alarms are returned in the build result as Record<string, Alarm>:

const result = cdn.build(stack, "CDN");

const alertTopic = new Topic(stack, "AlertTopic");
for (const alarm of Object.values(result.alarms)) {
  alarm.addAlarmAction(new SnsAction(alertTopic));
}

Cross-region alarm builder

CloudFront emits all metrics to us-east-1 only. CloudWatch alarms are regional, so alarms created in any other region never fire — they exist but receive no data. When the distribution lives in a stack outside us-east-1, use createCloudFrontAlarmBuilder to put the alarms in a separate us-east-1 stack.

The standalone builder reads the distribution's result (including the inline-function entries) and produces the same alarm surface — distribution-level recommended alarms, per-function recommended alarms, and any custom addAlarm alarms.

import { compose, ref } from "@composurecdk/core";
import {
  createDistributionBuilder,
  createCloudFrontAlarmBuilder,
  type DistributionBuilderResult,
} from "@composurecdk/cloudfront";

compose(
  {
    cdn: createDistributionBuilder()
      .origin(siteOrigin)
      .defaultBehavior({
        functions: [{ eventType: FunctionEventType.VIEWER_REQUEST, code }],
      })
      .recommendedAlarms(false), // suppress all alarms in the dist's own stack

    cdnAlarms: createCloudFrontAlarmBuilder()
      .distribution(ref<DistributionBuilderResult>("cdn"))
      .recommendedAlarms({ errorRate: { threshold: 2 } })
      .addAlarm("custom4xx", (a) =>
        a
          .metric(
            () =>
              new Metric({
                namespace: "AWS/CloudFront",
                metricName: "4xxErrorRate",
                statistic: "Average",
              }),
          )
          .threshold(5)
          .greaterThan(),
      ),
  },
  { cdn: [], cdnAlarms: ["cdn"] },
)
  .withStacks({
    cdn: siteStack, // e.g. eu-west-2
    cdnAlarms: usEast1Stack, // typically your existing certStack
  })
  .build(app, "App");

Set crossRegionReferences: true on both stacks so CDK can export DistributionId from the site stack and import it in the alarm stack.

recommendedAlarms: false on createDistributionBuilder is the master kill switch for both distribution-level and per-function recommended alarms. Custom alarms added via addAlarm are unaffected — call .addAlarm() on the standalone alarm builder if you want those to live in the us-east-1 stack too.

Examples

  • StaticWebsiteStack — S3 + CloudFront static website with OAC, error pages, and content deployment