cdknextjsexports3dynamicrouting

package module
v1.2.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 7, 2024 License: Apache-2.0 Imports: 10 Imported by: 0

README

Next.js Static Export S3 Site with Dynamic Routing

NPM

View on Construct Hub

Have a more complex use case for Next.js 13? Perhaps check out cdk-nextjs-standalone.

Deploy a static export Next.js site to Cloudfront and S3 while maintaining the ability to use dynamic routes.

This effectively takes all of the benefits of Next.js, including routing, code-splitting, static HTML exporting, and also gives you the benefits of a SPA (single page application). This will be mostly useful for client-generated pages, but you can also partially server side generate some data should you choose.

This may also be useful if you use Next.js SSR in other frontends, and just want to keep a consistent experience for your developers.

Getting Started

You can use this construct effectively with no props, but here is a minimal example with a custom domain:

export class MyStaticSiteStack extends cdk.Stack {
    private readonly hostedZone: route53.IHostedZone;
    private readonly customDomainName: string;
    private readonly site: NextjsExportS3DynamicRoutingSite;

    constructor(scope: sst.App, id: string, props?: sst.StackProps) {
        super(scope, id, props);

        this.hostedZone = this.findHostedZone();
        this.customDomainName = "yourdomain.com";

        this.site = this.createNextJsSite();
        this.createDnsRecord();
    }

    private findHostedZone(): route53.IHostedZone {
        return route53.HostedZone.fromLookup(this, "HostedZone", {
            domainName: this.customDomainName,
        });
    }

    private createNextJsSite(): NextjsExportS3DynamicRoutingSite {
        const certificate = new acm.Certificate(
            this,
            "Certificate",
            {
                domainName: this.customDomainName,
                validation: acm.CertificateValidation.fromDns(this.hostedZone),
            }
        );

        return new NextjsExportS3DynamicRoutingSite(this, "NextJsSite", {
            distributionProps: {
                certificate,
                domainNames: [this.customDomainName],
            }
        });
    }

    private createDnsRecord = (): route53.ARecord => {
        return new route53.ARecord(this, `AliasRecord`, {
            recordName: this.customDomainName,
            target: route53.RecordTarget.fromAlias(
                new r53Targets.CloudFrontTarget(
                    this.site.cloudfrontDistribution
                )
            ),
            zone: this.hostedZone,
        });
    };
}

There are no outside requirements for this construct, and it will delete all of its resources when the stack is deleted.

Documentation

Overview

Deploy a static export Next.js site to Cloudfront and S3 while maintaining the ability to use dynamic routes.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewNextjsExportS3DynamicRoutingSite_Override

func NewNextjsExportS3DynamicRoutingSite_Override(n NextjsExportS3DynamicRoutingSite, scope constructs.Construct, id *string, props *NextjsExportS3DynamicRoutingSiteProps)

func NextjsExportS3DynamicRoutingSite_IsConstruct

func NextjsExportS3DynamicRoutingSite_IsConstruct(x interface{}) *bool

Checks if `x` is a construct.

Returns: true if `x` is an object created from a class which extends `Construct`. Deprecated: use `x instanceof Construct` instead.

func NextjsExportS3DynamicRoutingSite_RECOMMENDED_CACHE_POLICY() *awscloudfront.CachePolicyProps

Types

type NextjsExportS3DynamicRoutingDistributionProps

type NextjsExportS3DynamicRoutingDistributionProps struct {
	// Additional behaviors for the distribution, mapped by the pathPattern that specifies which requests to apply the behavior to.
	// Default: - no additional behaviors are added.
	//
	AdditionalBehaviors *map[string]*awscloudfront.BehaviorOptions `field:"optional" json:"additionalBehaviors" yaml:"additionalBehaviors"`
	// A certificate to associate with the distribution.
	//
	// The certificate must be located in N. Virginia (us-east-1).
	// Default: - the CloudFront wildcard certificate (*.cloudfront.net) will be used.
	//
	Certificate awscertificatemanager.ICertificate `field:"optional" json:"certificate" yaml:"certificate"`
	// Any comments you want to include about the distribution.
	// Default: - no comment.
	//
	Comment *string `field:"optional" json:"comment" yaml:"comment"`
	// The default behavior for the distribution.
	//
	// Optional and Partial here, not usually either in the CDK.
	DefaultBehavior *PartialBehaviorOptions `field:"optional" json:"defaultBehavior" yaml:"defaultBehavior"`
	// The object that you want CloudFront to request from your origin (for example, index.html) when a viewer requests the root URL for your distribution. If no default object is set, the request goes to the origin's root (e.g., example.com/).
	// Default: - no default root object.
	//
	DefaultRootObject *string `field:"optional" json:"defaultRootObject" yaml:"defaultRootObject"`
	// Alternative domain names for this distribution.
	//
	// If you want to use your own domain name, such as www.example.com, instead of the cloudfront.net domain name,
	// you can add an alternate domain name to your distribution. If you attach a certificate to the distribution,
	// you must add (at least one of) the domain names of the certificate to this list.
	// Default: - The distribution will only support the default generated name (e.g., d111111abcdef8.cloudfront.net)
	//
	DomainNames *[]*string `field:"optional" json:"domainNames" yaml:"domainNames"`
	// Enable or disable the distribution.
	// Default: true.
	//
	Enabled *bool `field:"optional" json:"enabled" yaml:"enabled"`
	// Whether CloudFront will respond to IPv6 DNS requests with an IPv6 address.
	//
	// If you specify false, CloudFront responds to IPv6 DNS requests with the DNS response code NOERROR and with no IP addresses.
	// This allows viewers to submit a second request, for an IPv4 address for your distribution.
	// Default: true.
	//
	EnableIpv6 *bool `field:"optional" json:"enableIpv6" yaml:"enableIpv6"`
	// Enable access logging for the distribution.
	// Default: - false, unless `logBucket` is specified.
	//
	EnableLogging *bool `field:"optional" json:"enableLogging" yaml:"enableLogging"`
	// How CloudFront should handle requests that are not successful (e.g., PageNotFound).
	// Default: - No custom error responses.
	//
	ErrorResponses *[]*awscloudfront.ErrorResponse `field:"optional" json:"errorResponses" yaml:"errorResponses"`
	// Controls the countries in which your content is distributed.
	// Default: - No geographic restrictions.
	//
	GeoRestriction awscloudfront.GeoRestriction `field:"optional" json:"geoRestriction" yaml:"geoRestriction"`
	// Specify the maximum HTTP version that you want viewers to use to communicate with CloudFront.
	//
	// For viewers and CloudFront to use HTTP/2, viewers must support TLS 1.2 or later, and must support server name identification (SNI).
	// Default: HttpVersion.HTTP2
	//
	HttpVersion awscloudfront.HttpVersion `field:"optional" json:"httpVersion" yaml:"httpVersion"`
	// The Amazon S3 bucket to store the access logs in.
	//
	// Make sure to set `objectOwnership` to `s3.ObjectOwnership.OBJECT_WRITER` in your custom bucket.
	// Default: - A bucket is created if `enableLogging` is true.
	//
	LogBucket awss3.IBucket `field:"optional" json:"logBucket" yaml:"logBucket"`
	// An optional string that you want CloudFront to prefix to the access log filenames for this distribution.
	// Default: - no prefix.
	//
	LogFilePrefix *string `field:"optional" json:"logFilePrefix" yaml:"logFilePrefix"`
	// Specifies whether you want CloudFront to include cookies in access logs.
	// Default: false.
	//
	LogIncludesCookies *bool `field:"optional" json:"logIncludesCookies" yaml:"logIncludesCookies"`
	// The minimum version of the SSL protocol that you want CloudFront to use for HTTPS connections.
	//
	// CloudFront serves your objects only to browsers or devices that support at
	// least the SSL version that you specify.
	// Default: - SecurityPolicyProtocol.TLS_V1_2_2021 if the '@aws-cdk/aws-cloudfront:defaultSecurityPolicyTLSv1.2_2021' feature flag is set; otherwise, SecurityPolicyProtocol.TLS_V1_2_2019.
	//
	MinimumProtocolVersion awscloudfront.SecurityPolicyProtocol `field:"optional" json:"minimumProtocolVersion" yaml:"minimumProtocolVersion"`
	// The price class that corresponds with the maximum price that you want to pay for CloudFront service.
	//
	// If you specify PriceClass_All, CloudFront responds to requests for your objects from all CloudFront edge locations.
	// If you specify a price class other than PriceClass_All, CloudFront serves your objects from the CloudFront edge location
	// that has the lowest latency among the edge locations in your price class.
	// Default: PriceClass.PRICE_CLASS_ALL
	//
	PriceClass awscloudfront.PriceClass `field:"optional" json:"priceClass" yaml:"priceClass"`
	// The SSL method CloudFront will use for your distribution.
	//
	// Server Name Indication (SNI) - is an extension to the TLS computer networking protocol by which a client indicates
	// which hostname it is attempting to connect to at the start of the handshaking process. This allows a server to present
	// multiple certificates on the same IP address and TCP port number and hence allows multiple secure (HTTPS) websites
	// (or any other service over TLS) to be served by the same IP address without requiring all those sites to use the same certificate.
	//
	// CloudFront can use SNI to host multiple distributions on the same IP - which a large majority of clients will support.
	//
	// If your clients cannot support SNI however - CloudFront can use dedicated IPs for your distribution - but there is a prorated monthly charge for
	// using this feature. By default, we use SNI - but you can optionally enable dedicated IPs (VIP).
	//
	// See the CloudFront SSL for more details about pricing : https://aws.amazon.com/cloudfront/custom-ssl-domains/
	// Default: SSLMethod.SNI
	//
	SslSupportMethod awscloudfront.SSLMethod `field:"optional" json:"sslSupportMethod" yaml:"sslSupportMethod"`
	// Unique identifier that specifies the AWS WAF web ACL to associate with this CloudFront distribution.
	//
	// To specify a web ACL created using the latest version of AWS WAF, use the ACL ARN, for example
	// `arn:aws:wafv2:us-east-1:123456789012:global/webacl/ExampleWebACL/473e64fd-f30b-4765-81a0-62ad96dd167a`.
	// To specify a web ACL created using AWS WAF Classic, use the ACL ID, for example `473e64fd-f30b-4765-81a0-62ad96dd167a`.
	// See: https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateDistribution.html#API_CreateDistribution_RequestParameters.
	//
	// Default: - No AWS Web Application Firewall web access control list (web ACL).
	//
	WebAclId *string `field:"optional" json:"webAclId" yaml:"webAclId"`
}

Differences from cloudfront.DistributionProps: - defaultBehavior is optional.

type NextjsExportS3DynamicRoutingSite

type NextjsExportS3DynamicRoutingSite interface {
	constructs.Construct
	CloudfrontDistribution() awscloudfront.Distribution
	// The tree node.
	Node() constructs.Node
	S3Bucket() awss3.Bucket
	ViewerRequestCloudfrontFunction() awscloudfront.Function
	// Returns a string representation of this construct.
	ToString() *string
}

Deploy an exported, static site using Next.js. Compatible with a Next 13 project using /pages routing. See: For Static Site Limitations: https://nextjs.org/docs/advanced-features/static-html-export

Additional Limitations: - Cloudfront function size is capped at 10KB. This may be exceeded if the amount of pages (page types, not static pages with many static paths) is extremely large, as each represents a JSON object in the code. - For estimation, if we assume around 1000 characters of natural overhead and average 100 characters per page type, this calculates to about 90 page types (files in the pages folder).

func NewNextjsExportS3DynamicRoutingSite

func NewNextjsExportS3DynamicRoutingSite(scope constructs.Construct, id *string, props *NextjsExportS3DynamicRoutingSiteProps) NextjsExportS3DynamicRoutingSite

type NextjsExportS3DynamicRoutingSiteProps

type NextjsExportS3DynamicRoutingSiteProps struct {
	// Passthrough props to customize the S3 bucket.
	// Default: {
	// publicReadAccess: false,
	// blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
	// autoDeleteObjects: true,
	// removalPolicy: cdk.RemovalPolicy.DESTROY,
	// }.
	//
	BucketProps *awss3.BucketProps `field:"optional" json:"bucketProps" yaml:"bucketProps"`
	// Passthrough props to customize the Cloudfront distribution.
	// Default: Sets up the S3 Origin and Cache Policy.
	//
	DistributionProps *NextjsExportS3DynamicRoutingDistributionProps `field:"optional" json:"distributionProps" yaml:"distributionProps"`
	// Default: ./.next
	//
	NextBuildDir *string `field:"optional" json:"nextBuildDir" yaml:"nextBuildDir"`
	// The relative path to the Next.js project.
	// Default: ./out
	//
	NextExportPath *string `field:"optional" json:"nextExportPath" yaml:"nextExportPath"`
	// Passthrough props to customize the S3 Origin.
	// Default: S3 Origin defaults.
	//
	S3OriginProps *awscloudfrontorigins.S3OriginProps `field:"optional" json:"s3OriginProps" yaml:"s3OriginProps"`
}

Deploy a static export Next.js site to Cloudfront and S3 while maintaining the ability to use dynamic routes.

Deploys Cloudfront, a Cloudfront Function, an S3 Bucket, and an S3 Deployment.

With defaults set, if this construct is removed, all resources will be cleaned up.

type PartialBehaviorOptions

type PartialBehaviorOptions struct {
	// HTTP methods to allow for this behavior.
	// Default: AllowedMethods.ALLOW_GET_HEAD
	//
	AllowedMethods awscloudfront.AllowedMethods `field:"optional" json:"allowedMethods" yaml:"allowedMethods"`
	// HTTP methods to cache for this behavior.
	// Default: CachedMethods.CACHE_GET_HEAD
	//
	CachedMethods awscloudfront.CachedMethods `field:"optional" json:"cachedMethods" yaml:"cachedMethods"`
	// The cache policy for this behavior.
	//
	// The cache policy determines what values are included in the cache key,
	// and the time-to-live (TTL) values for the cache.
	// See: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html.
	//
	// Default: CachePolicy.CACHING_OPTIMIZED
	//
	CachePolicy awscloudfront.ICachePolicy `field:"optional" json:"cachePolicy" yaml:"cachePolicy"`
	// Whether you want CloudFront to automatically compress certain files for this cache behavior.
	//
	// See https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ServingCompressedFiles.html#compressed-content-cloudfront-file-types
	// for file types CloudFront will compress.
	// Default: true.
	//
	Compress *bool `field:"optional" json:"compress" yaml:"compress"`
	// The Lambda@Edge functions to invoke before serving the contents.
	// See: https://aws.amazon.com/lambda/edge
	//
	// Default: - no Lambda functions will be invoked.
	//
	EdgeLambdas *[]*awscloudfront.EdgeLambda `field:"optional" json:"edgeLambdas" yaml:"edgeLambdas"`
	// The CloudFront functions to invoke before serving the contents.
	// Default: - no functions will be invoked.
	//
	FunctionAssociations *[]*awscloudfront.FunctionAssociation `field:"optional" json:"functionAssociations" yaml:"functionAssociations"`
	// The origin request policy for this behavior.
	//
	// The origin request policy determines which values (e.g., headers, cookies)
	// are included in requests that CloudFront sends to the origin.
	// Default: - none.
	//
	OriginRequestPolicy awscloudfront.IOriginRequestPolicy `field:"optional" json:"originRequestPolicy" yaml:"originRequestPolicy"`
	// The response headers policy for this behavior.
	//
	// The response headers policy determines which headers are included in responses.
	// Default: - none.
	//
	ResponseHeadersPolicy awscloudfront.IResponseHeadersPolicy `field:"optional" json:"responseHeadersPolicy" yaml:"responseHeadersPolicy"`
	// Set this to true to indicate you want to distribute media files in the Microsoft Smooth Streaming format using this behavior.
	// Default: false.
	//
	SmoothStreaming *bool `field:"optional" json:"smoothStreaming" yaml:"smoothStreaming"`
	// A list of Key Groups that CloudFront can use to validate signed URLs or signed cookies.
	// See: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent.html
	//
	// Default: - no KeyGroups are associated with cache behavior.
	//
	TrustedKeyGroups *[]awscloudfront.IKeyGroup `field:"optional" json:"trustedKeyGroups" yaml:"trustedKeyGroups"`
	// The protocol that viewers can use to access the files controlled by this behavior.
	// Default: ViewerProtocolPolicy.ALLOW_ALL
	//
	ViewerProtocolPolicy awscloudfront.ViewerProtocolPolicy `field:"optional" json:"viewerProtocolPolicy" yaml:"viewerProtocolPolicy"`
	// The origin that you want CloudFront to route requests to when they match this behavior.
	Origin awscloudfront.IOrigin `field:"optional" json:"origin" yaml:"origin"`
}

Options for creating a new behavior.

origin is optional here, not usually in the CDK.

Directories

Path Synopsis
Package jsii contains the functionaility needed for jsii packages to initialize their dependencies and themselves.
Package jsii contains the functionaility needed for jsii packages to initialize their dependencies and themselves.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL