Is there a construct similar to `StaticSite` that ...
# sst
t
Is there a construct similar to
StaticSite
that can be used to set up only CloudFront distribution with custom domain? Default CDK way requires a lot of extra code. If something like this doesn’t exist yet, was thinking a
CDN
construct would be nice 🙂
What im currently doing:
Copy code
import { Stack } from '@serverless-stack/resources';
import {
  DnsValidatedCertificate,
  ICertificate,
} from 'aws-cdk-lib/aws-certificatemanager';
import { Distribution, DistributionProps } from 'aws-cdk-lib/aws-cloudfront';
import {
  AaaaRecord,
  ARecord,
  HostedZone,
  IHostedZone,
  RecordTarget,
} from 'aws-cdk-lib/aws-route53';
import { CloudFrontTarget } from 'aws-cdk-lib/aws-route53-targets';

const createHostedZone = (stack: Stack): IHostedZone => {
  const domainName = process.env.DOMAIN_NAME;
  if (!domainName) {
    throw new Error('DOMAIN_NAME is not set.');
  }
  return HostedZone.fromLookup(stack, 'HostedZone', {
    domainName,
  });
};

const createCertificate = (
  stack: Stack,
  hostedZone: IHostedZone,
  domainName: string,
): ICertificate => {
  return new DnsValidatedCertificate(stack, 'Certificate', {
    domainName,
    hostedZone,
    region: process.env.AWS_REGION,
  });
};

const createRoute53Records = (
  stack: Stack,
  zone: IHostedZone,
  domainName: string,
  distribution: Distribution,
): void => {
  // Create DNS record
  const recordProps = {
    recordName: domainName,
    zone,
    target: RecordTarget.fromAlias(new CloudFrontTarget(distribution)),
  };
  new ARecord(stack, 'AliasRecord', recordProps);
  new AaaaRecord(stack, 'AliasRecordAAAA', recordProps);
};

type CreateDistributionProps = Omit<
  DistributionProps,
  'certificate' | 'domainNames'
> & {
  domainName: string;
};

/**
 * Configures certificate, DNS, and distribution.
 */
export const createDistribution = (
  stack: Stack,
  { domainName, ...distributionProps }: CreateDistributionProps,
): Distribution => {
  const hostedZone = createHostedZone(stack);
  const certificate = createCertificate(stack, hostedZone, domainName);
  const distribution = new Distribution(stack, 'ImageDistribution', {
    ...distributionProps,
    domainNames: [domainName],
    certificate,
  });
  createRoute53Records(stack, hostedZone, domainName, distribution);

  return distribution;
};
Usage:
Copy code
createDistribution(stack, {
    defaultBehavior: {
      origin: originGroup,
    },
    domainName: `image.${process.env.DOMAIN_NAME}`,
  });
f
Hey @Ted Mader, can you share what the use case is? ie. what endpoint/service is the CloudFront distribution origin pointing to?