Search code examples
amazon-web-servicesnext.jsaws-cdkvercel

How to deploy NextJS on AWS, the same way Vercel does?


I want to deploy NextJS on AWS using AWS CDK for a POC and was looking at options. In the NextJS docs, it says that we can just create an instance and run npm run build && npm start, it will start the service for us. However, this is not the most optimised way of deploying.

Vercel deploys this in the most optimized way possible: enter image description here

How can I do the same with AWS? How can I serve the static assets and pages via Cloudfront CDN and the server side rendered pages and APIs via either Lambda or ECS? Is there a step by step guide that I can follow to split out the build files for the same?

Other options I explored

  • AWS Amplify: As it is a premium service, I feel doing all this by my self would be a lot cheaper and gives me more flexibility in CDK (I am not sure how Amplify works behind the scenes to deploy the nextjs assets on a S3 + Cloudfront + Lambda stack)
  • serverless framework: There is a plugin to deploy nextjs. But, I want to have full control over the deployment and don't want to depend on any external framework. Want to do it natively using AWS CDK.

Any pointers to do this natively using AWS CDK would be helpful. Thanks.


Solution

  • Deploying Next.js as a serverless application requires a bunch of services when you don't want to pack the whole Next.js server into a single Lambda.

    My current setup of AWS services to achieve this looks like the following: enter image description here

    It consists of 3 main resources:

    1. CloudFront
      This works as a serverless reverse proxy that routes the traffic from the Internet to S3 (JavaScript, prerendered pages) or Lambda (Server rendered pages).
      When using the image optimization capabilities of Next.js you also need an extra service that provides the API for it.
    2. S3
      Since you don't want to invoke Lambdas just to serve static content, you need a S3 bucket where those files are stored and served from.
    3. Lambda
      The Lambdas are then used to serve the server generated pages (SSR & API). They contain a minimal version of the Next.js server (e.g. without the static files that are served from S3).

    I built this setup with Terraform, so there is no native CDK solution available at this time. But most of it could be simply translated to CDK since the model behind Terraform and CDK is pretty much the same.

    Source code of the Terraform module is available on GitHub: https://github.com/milliHQ/terraform-aws-next-js