Skip to content

pavinthan/cdk-nextjs

Repository files navigation

Deploy NextJS with CDK

View on Construct Hub

What is this?

A CDK construct to deploy a NextJS 12.3.0+ app using AWS CDK.

Uses the standalone output build mode.

Quickstart

import path from 'path';
import { Nextjs } from 'cdk-nextjs-standalone';

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

Documentation

Available on Construct Hub.

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 translates between a APIGatewayProxyV2 request/response and Next request/response.

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 and middleware.

The @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.

Status

This is experimental and a work in progress. I hope others can benefit from it and contribute to make it more stable and featureful.

I have managed to get the server bundling working even under the most finicky of circumstances (pnpm monorepo). Server-side rendering works. Static files and public files work.

Depdendencies

NextJs requires the sharp native library. It is provided in a zip file from lambda-layer-sharp.

All other required dependencies should be bundled by NextJs output tracing. This standalone output is included in the lambda function bundle.

Cold start performance

Testing with sst-prisma

Duration: 616.43 ms Billed Duration: 617 ms Memory Size: 2048 MB Max Memory Used: 131 MB Init Duration: 481.08 ms

On my nextjs app using Material-UI

Duration: 957.56 ms Billed Duration: 958 ms Memory Size: 1024 MB Max Memory Used: 127 MB Init Duration: 530.86 ms

next-server-mui

Heavily based on

This module is largely made up of code from the above projects.

Questions

  • Do we need to manually handle CloudFront invalidation? It looks like BucketDeployment takes care of that for us
  • How is the public dir supposed to be handled? (Right now using an OriginGroup to look in the S3 origin first and if 403/404 then try lambda origin)
  • Is there anything we should be doing with the various manifests nextjs spits out? (e.g., not sure what the purpose of this is)
    • Do we need to create static routes? Or anything else?
  • Do we need to handle ISR?
  • How should images be handled?

Serverless-stack (SST) wrapper

export interface NextjsSstProps extends NextjsProps {
  app: App;
}

class NextjsSst extends Nextjs {
  constructor(scope: Construct, id: string, props: NextjsSstProps) {
    const app = props.app;

    super(scope as any, id, {
      ...props,
      isPlaceholder: app.local,
      tempBuildDir: app.buildDir,

      // make path relative to the app root
      nextjsPath: path.isAbsolute(props.nextjsPath) ? path.relative(app.appPath, props.nextjsPath) : props.nextjsPath,
    });

    this.registerSiteEnvironment();
  }

  protected registerSiteEnvironment() {
    const environmentOutputs: Record<string, string> = {};
    for (const [key, value] of Object.entries(this.props.environment || {})) {
      const outputId = `SstSiteEnv_${key}`;
      const output = new CfnOutput(this, outputId, { value });
      environmentOutputs[key] = Stack.of(this).getLogicalId(output);
    }

    const app = this.node.root as App;
    app.registerSiteEnvironment({
      id: this.node.id,
      path: this.props.nextjsPath,
      stack: Stack.of(this).node.id,
      environmentOutputs,
    } as BaseSiteEnvironmentOutputsInfo);
  }
}

To-do

Edge functions

It should be possible to build the lambda handler as a Lambda@Edge function, the main blocker is resolving the CDK tokens in env vars on the server side because edge functions cannot have environment variables. These tokens are not present at build-time. One of these issues needs to be fixed for that to work most likely: vercel/next.js#40827 aws/aws-cdk#19257

About

Deploy a NextJS application using AWS CDK

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 100.0%