The APIs of higher level constructs in this module are experimental and under active development. They are subject to non-backward compatible changes or removal in any future version. These are not subject to the Semantic Versioning model and breaking changes will be announced in the release notes. This means that while you may use them, you may need to update your source code when upgrading to a newer version of this package.
Deploy Next.js apps on AWS with the AWS CDK.
NextjsGlobalFunctions
, NextjsGlobalContainers
, NextjsRegionalContainers
.overrides
.NextjsRegionalContainers
)."standalone"
. Learn more here about Standalone Output.npm install cdk-nextjs
cdk deploy
import { App, Stack } from "aws-cdk-lib";
import { Construct } from "constructs";
import { fileURLToPath } from "node:url";
import { NextjsGlobalFunctions } from "cdk-nextjs";
class NextjsStack extends Stack {
constructor(scope: Construct, id: string) {
super(scope, id, props);
new NextjsGlobalFunctions(this, "Nextjs", {
healthCheckPath: "/api/health",
buildContext: fileURLToPath(new URL("..", import.meta.url)),
});
}
}
const app = new App();
new NextjsStack(app, "nextjs");
See examples/ for more usage examples.
NextjsGlobalFunctions
Architecture includes AWS Lambda Functions to respond to dynamic requests and CloudFront Distribution to globally serve requests and distribute static assets. Use this construct when you have unpredictable traffic, can afford occasional latency (i.e. cold starts - typically 1% of production traffic), and/or want the most granular pricing model. (code)
NextjsGlobalContainers
Architecture includes ECS Fargate containers to respond to dynamic requests and CloudFront Distribution to globally serve requests and distribute static assets. Use this option when you have predictable traffic, need the lowest latency, and/or can afford a less granular pricing model. (code)
NextjsRegionalContainers
Architecture includes ECS Fargate containers to respond to dynamic requests and Application Load Balancer to regionally serve requests. Use this options when you cannot use Amazon CloudFront (i.e. AWS GovCloud). (code)
The simplest path to deploy Next.js is on Vercel - the Platform-as-a-Service company behind Next.js. However, deploying to Vercel can be expensive and some developers want all of their workloads running directly on AWS. Developers can deploy Next.js on AWS through AWS Amplify Hosting, but Amplify does not support all Next.js features and manages AWS resources for you so they cannot be customized. If Amplify meets your requirements we recommend you use it, but if you want to use all Next.js features or want more visibility into the AWS resources then this construct is for you.
NextjsGlobalFunctions
or NextjsGlobalContainers
(which use CloudFront), the number of top level files/directories cannot exceed 25, the max number of behaviors a CloudFront Distrubtion supports. We recommend you put all of your public assets into one top level directory (i.e. public/static) so you don't reach this limit. See CloudFront Quotas for more information.NextjsGlobalFunctions
, when revalidating data in Next.js (i.e. revalidatePath), the CloudFront Cache will still hold stale data. You'll need to use AWS SDK JS V3 CreateInvalidationCommand to manually invalidate the path in CloudFront. See more here.NextjsGlobalFunctions
, setting an Authorization header won't work by default because of Lambda Function URL with IAM Auth is already using the Authorization header. You can use the AWS_LWA_AUTHORIZATION_SOURCE
environment variable of AWS Lambda Web Adapter to set an alternative Authorization header in the client which will then be set to the Authorization header when it reaches your app.This construct by default implements all AWS security best practices that a CDK construct library reasonably can considering cost and complexity. Below are additional security practices we recommend you implement within your CDK app. Please see them below:
NextjsGlobalFunctions
and NextjsGlobalContainers
, CloudFront Access Logs. See examples/ for sample implementation.NextjsGlobalContainers
and NextjsRegionalContainers
, ALB HTTPS ListenerWIP
Steps to build locally:
git clone https://github.com/cdklabs/cdk-nextjs.git
cd cdk-nextjs
pnpm i && pnpm compile && pnpm build
This project uses Projen, so make sure to not edit Projen created files and only edit .projenrc.ts.
Q: How does this compare to cdk-nextjs-standalone? A: cdk-nextjs-standalone relies on OpenNext. OpenNext injects custom code to interact with private Next.js APIs. While OpenNext is able to make some optimizations that are great for serverless environments, this comes at an increase maintenance cost and increased chances for breaking changes. A goal of cdk-nextjs is to customize Next.js as little as possible to reduce the maintenance burden and decrease chances of breaking changes.
Q: Why not offer API Gateway version of construct? A: API Gateway does not support streaming.
Q: Why EFS instead of S3? A: Next.js has 3 types of server caching that are persisted to disk: Data Cache, Full Route Cache, and Image Optimization. Cached data is persisted at .next/cache/fetch-cache, cached full routes are persisted at .next/server/app, and optimized images are persisted at .next/cache/images. Next.js provides a way to customize where cached data or cached full routes are persisted through the Custom Next.js Cache Handler, but there currently is no way to persist optimized images. Therefore, we need a way to persist cached data at the file system level which is transparent to Next.js. To do this, we use Amazon Elastic File System (EFS). Benefits of EFS include being able to cache any Next.js data persisted to disk and therefore being flexible to adapt to Next.js as the framework evolves caching additional types of data. One exception to not using the Custom Next.js Cache Handler is to support Data Cache Time-based Revalidation when using AWS Lambda functions. Functions only run when they are responding to a request preventing time-based revalidation unlike containers with AWS Fargate which run continually. For functions, an Amazon SQS Queue and consuming function that will make a HEAD request with x-prerender-revalidate header needed for Next.js to update cache.
Q: How customizable is the cdk-nextjs
package for different use cases?
A: The cdk-nextjs
package offers deep customization through prop-based overrides. These can be accessed in the construct props, allowing you to override settings like VPC configurations, CloudFront distribution, and ECS/Fargate setup. For example, you can modify nextjsBuildProps
to customize the build process or use nextjsDistributionProps
to adjust how CloudFront handles caching and routing. This level of control makes it easy to adapt the infrastructure to your application’s specific performance, networking, or deployment needs.
Q: How can I use a custom domain with cdk-nextjs
?
A: To use a custom domain, you can configure the distribution
prop within constructs like NextjsGlobalFunctions
or NextjsGlobalContainers
. By providing an ACM certificate and overriding relevant properties such as nextjsDistributionProps
, you can customize the CloudFront distribution to handle your domain. This allows CloudFront to route traffic through your custom domain while managing SSL termination for secure HTTPS connections.
This construct was built on the shoulders of giants. Thank you to the contributors of cdk-nextjs-standalone and open-next.
Thank you for helping other developers deploy Next.js apps on AWS