Search code examples
reactjsamazon-web-servicesamazon-s3amazon-ec2next.js

What is the cheapest way to deploy a React app using Next.js SSR on AWS?


I understand that Next.js is a Node.js framework that requires server capabilities and therefore, using it for server-side rendering (SSR) could not be hosted on an S3 instance only.

However, does that mean that the only alternative is to host the entire app on an EC2 instance, which is significantly more expensive, or is there another midway solution?


Solution

  • Next.js SSR + Serverless framework + AWS Lambda

    For deploying your Next.js SSR App, instead of following a traditional approach of managing and running a whole AWS EC2 instance which keeps running 24x7, there is actually one more cost-effective and modern approach which uses AWS lambda and the Serverless framework.

    Q. What is AWS lambda?
    AWS Lambda lets you run code without provisioning or managing servers. You pay only for the compute time you consume.

    Q. What is the Serverless framework?
    Serverless Framework Open Source lets you develop applications with a serverless architecture and deploy using AWS Lambda, Azure Functions, Google CloudFunctions, and more.

    Q. What is Serverless-Next.js?
    This is a Serverless component built just for deploying a Next.js app. Also, any of your assets in the static or public folders are uploaded to S3 and served from CloudFront automatically, so I think this is what you are exactly looking for.

    Below is the architecture explaining how it serves your app to the user.

    Enter image description here

    If you are new to serverless framework, I will suggest you to go through a free course by the Serverless community called Serverless for Frontend Developers

    @super7egazi put forward a genuine concern in the comment below. Thankfully there are a few ways to keep the Lambda function warm. This is the act of sending scheduled ping events to your functions to keep them alive and idle, ready to serve requests.

    You will find various methods and plugins to achieve this, if you just search "How to keep lambda functions warm?" on Google.

    Below are some links which I'm attaching for reference.

    How to keep your lambda functions warm?

    How to Minimize AWS Lambda Cold Starts

    Keep your lambdas warm