vighnesh153
vighnesh153

Reputation: 5388

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

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

Upvotes: 13

Views: 7064

Answers (2)

vighnesh153
vighnesh153

Reputation: 5388

I came across OpenNext that takes the Next.js build output and converts it into a package that can be deployed to any functions as a service platform.

Following is the architecture that they follow (as of March 6, 2024). For latest updated architecture, visit their advanced/architecture page.

Upvotes: 1

ofhouse
ofhouse

Reputation: 3256

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

Upvotes: 19

Related Questions