Git Product home page Git Product logo

cdk-nextjs's Introduction

Deploy NextJS with CDK

View on Construct Hub

What is this?

A CDK construct to deploy a NextJS app using AWS CDK. Supported NextJs versions: >=12.3.0+ (includes 13.0.0+)

Uses the standalone output build mode.

Quickstart

Add the dependency [email protected] to your project along with cdk-nextjs-standalone.

npm install -D [email protected] cdk-nextjs-standalone
import path from 'path';
import { Nextjs } from 'cdk-nextjs-standalone';

new Nextjs(this, 'Web', {
  nextjsPath: './web', // relative path to nextjs project root
});

Important Notes

  • Due to CloudFront's Distribution Cache Behavior pattern matching limitations, a cache behavior will be created for each top level file or directory in your public/ folder. CloudFront has a soft limit of 25 cache behaviors per distribution. Therefore, it's recommended to include all assets that can be under a top level folder like public/static/. Learn more in open-next docs here.

Documentation

Available on Construct Hub.

Customization

Increased Security

import { RemovalPolicy, Stack } from "aws-cdk-lib";
import { Construct } from "constructs";
import { CfnWebAcl } from "aws-cdk-lib/aws-wafv2";
import { SecurityPolicyProtocol, type DistributionProps } from "aws-cdk-lib/aws-cloudfront";
import { Nextjs, type NextjsDistributionProps } from "cdk-nextjs-standalone";
import { Bucket, BlockPublicAccess, BucketEncryption } from "aws-cdk-lib/aws-s3";

// Because of `WebAcl`, this stack must be deployed in us-east-1. If you want
// to deploy Nextjs in another region, add WAF in separate stack deployed in us-east-1
export class UiStack {
  constructor(scope: Construct, id: string) {
    const webAcl = new CfnWebAcl(this, "WebAcl", { ... });
    new Nextjs(this, "NextSite", {
      nextjsPath: "...",
      defaults: {
        assetDeployment: {
          bucket: new Bucket(this, "NextjsAssetDeploymentBucket", {
            autoDeleteObjects: true,
            removalPolicy: RemovalPolicy.DESTROY,
            encryption: BucketEncryption.S3_MANAGED,
            enforceSSL: true,
            blockPublicAccess: BlockPublicAccess.BLOCK_ALL,
          }),
        },
        distribution: {
          functionUrlAuthType: FunctionUrlAuthType.AWS_IAM,
          cdk: {
            distribution: {
              webAclId: webAcl.attrArn,
              minimumProtocolVersion: SecurityPolicyProtocol.TLS_V1_2_2021,
            } as DistributionProps,
          },
        } satisfies Partial<NextjsDistributionProps>,
      },
    });
  }
}

Discord Chat

We're in the #open-next channel on the Serverless Stack Discord.

About

Deploys a NextJs static site with server-side rendering and API support. Uses AWS lambda and CloudFront.

There is a new (since Next 12) standalone output mode which uses output tracing to generate a minimal server and static files. This standalone server can be converted into a CloudFront distribution and a lambda handler that handles SSR, API, and routing.

The CloudFront default origin first checks S3 for static files and falls back to an HTTP origin using a lambda function URL.

Benefits

This approach is most compatible with new NextJs features such as ESM configuration, middleware, next-auth, and React server components ("appDir").

The unmaintained @serverless-nextjs project uses the deprecated serverless NextJs build target which prevents the use of new features. This construct was created to use the new standalone output build and newer AWS features like lambda function URLs and fallback origins.

You may want to look at Serverless Stack and its NextjsSite construct for an improved developer experience if you are building serverless applications on CDK.

Dependencies

Built on top of open-next, which was partially built using the original core of cdk-nextjs-standalone.

Heavily based on

Contribute

Hey there, we value every new contribution a lot ๐Ÿ™๐Ÿผ thank you.

Here is a short HowTo before you get started:

  1. Please make sure to create a bug first
  2. Link the bug in your pull request
  3. Run yarn build after you made your changes and before you open a pull request

Projen

Don't manually update package.json or use npm CLI. Update dependencies in .projenrc.js then run yarn projen.

Breaking changes

  • v4.0.0

    • Renamed NextjsLambda to NextjsServer
    • Renamed ImageOptimizationLambda to NextjsImage
    • Renamed NextjsCachePolicyProps.lambdaCachePolicy to NextjsCachePolicyProps.serverCachePolicy
    • Removed NextjsOriginRequestPolicyProps.fallbackOriginRequestPolicy
    • Renamed NextjsOriginRequestPolicyProps.lambdaOriginRequestPolicy to NextjsOriginRequestPolicyProps.serverOriginRequestPolicy
    • Removed NextjsDistribution.staticCachePolicyProps
    • Renamed NextjsDistribution.lambdaCachePolicyProps to NextjsDistribution.serverCachePolicyProps
    • Renamed NextjsDistribution.lambdaOriginRequestPolicyProps to NextjsDistribution.serverOriginRequestPolicyProps
    • Removed NextjsDistribution.fallbackOriginRequestPolicyProps
    • Removed NextjsDistribution.imageOptimizationOriginRequestPolicyProps
    • NOTE: when upgrading to v4 from v3, the Lambda@Edge function will be renamed or removed. CloudFormation will fail to delete the function b/c they're replicated a take ~15 min to delete (more here). You can either deploy CloudFormation with it's "no rollback" feature for a clean deployment or mark the Lambda@Edge function as "retain on delete".
  • v3.0.0: Using open-next for building, ARM64 architecture for image handling, new build options.

  • v2.0.0: SST wrapper changed, lambda/assets/distribution defaults now are in the defaults prop, refactored distribution settings into the new NextjsDistribution construct. If you are upgrading, you must temporarily remove the customDomain on your existing 1.x.x app before upgrading to >=2.x.x because the CloudFront distribution will get recreated due to refactoring, and the custom domain must be globally unique across all CloudFront distributions. Prepare for downtime.

cdk-nextjs's People

Contributors

revmischa avatar khuezy avatar bestickley avatar ansgars avatar jadenv avatar durgaprasad-budhwani avatar kevin-mitchell avatar lagyu avatar keenankaufman avatar xinha-sh avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.