56

I understand that Nextjs is a Node framework that requires server capabilities and therefore, using it for server-side rendering could not be hosted on an S3 only. However, does that mean that the only alternative is to host the entire app on an EC2 - which is significantly more expensive - or is there another mid-way solution?

Thanh-Quy Nguyen
  • 2,995
  • 7
  • 30
  • 46
  • Amplify Hosting supports apps created using the Next.js framework. When you deploy your app, Amplify automatically detects SSR–you do not have to perform any manual configuration in the AWS Management Console. https://docs.aws.amazon.com/amplify/latest/userguide/server-side-rendering-amplify.html – Avinandan May 12 '23 at 14:11

6 Answers6

75

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 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 Serverless framework?
Serverless Framework Open Source lets you develop applications with serverless architectures and deploy using AWS Lambda, Azure Functions, Google CloudFunctions & more.

Q. What is Serverless-Next.js?
This is a Serverless component built just for deploying 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 thru a free course by Serverless community called Serverless for Frontend Developers

EDIT: 03/03/2021

@super7egazi put forward a genuine concern in the comment below. Thankfully there are 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

Pratik149
  • 1,109
  • 1
  • 9
  • 16
  • @Thanh-QuyNguyen I have updated my answer with slightly better explanation. Also if you ever try deploying your Next.js app on AWS lambda using serverless-next.js, and if you happen to save some credits/money over time, then don't forget to mark this answer as accepted. :D – Pratik149 May 19 '20 at 17:02
  • 1
    I've actually been working on this all day before you answer and yes, this seems to be the most cost-effective way to deploy a NextJS app to AWS. However, I've been encountering an issue with next-i18n which is currently not working with Serverless. The team is on it though, and it's in the beta. I just didn't have enough time to make it work today – Thanh-Quy Nguyen May 19 '20 at 20:03
  • 1
    Oh that's great. And I see Serverless framework is yet to mature. I never worked with next-i18n library, but I hope they come up with a fix for it very soon. – Pratik149 May 20 '20 at 20:13
  • 10
    Great answer! one thing to keep in mind that this architecture is cheap, but it is not good for SEO. AWS lambda goes into cold mode which means that if no one is hitting the site, the first hit to the site will take longer time to finish. For example, Google crawler can hit the site when it has been unused for some time, and your site will respond in longer than usual time because it is the first call after it has been idle. Just keep this in mind if SEO is important for you. – super7egazi Sep 15 '20 at 13:34
  • Concerning SEO - if you deploy NextJS to a VPS (AWS, Digital Ocean, Heroku etc) AKA not on vercel, the nextJS server will act like a regular express server. So the API routes will just be regular API endpoints. No cold start issue – Clifford Fajardo Mar 18 '21 at 23:58
  • As we can only deploy 250mb code into lambda, when project grows and we are using many node modules. How we can handle such scenario? – krunal shah Apr 30 '21 at 03:45
  • You can also deploy Next.js apps to your AWS account using CDK with the SST framework. Compatible with Next.js 11. Here's an example https://serverless-stack.com/examples/how-to-create-a-nextjs-app-with-serverless.html – Frank Sep 22 '21 at 20:32
  • Can it be used freely for a company based repo? I am confused by their pricing docs which mentions this as `Personal Github Organizations only`. Not sure what orgs mean here. Do they mean personal accounts only? – HalfWebDev Oct 16 '22 at 15:02
  • Found this package - https://www.npmjs.com/package/lambda-warmer that uses the same technique mentioned in the blog to keep lambda warm. – Kshateesh May 24 '23 at 05:53
43

AWS Next.js Terraform module

We created an Open Source Terraform module as a lower cost alternative to the Serverless framework for this use case. Instead of relying only on Lambda@Edge for all SSR operations we use Lambda@Edge only for routing (as some kind of reverse proxy) and then redirect the request internally via API Gateway to an regional Lambda.

Since we use CloudFront as a reverse proxy we can also split most of the requests for static files against _next/static/* for css, js, etc. and serve them directly by S3 without touching the Lambda@Edge proxy at all.

enter image description here

So the cost per request are different per route:

  • Requests for static assets: css, js, images

    Only costs for CloudFront and S3 (For misses from CloudFront) apply

  • Requests for HTML: Prerendered HTML-Routes or Routes that need Server-Side-Rendering (SSR)

    Costs for Cloudfront, Lambda@Edge (Proxy, metered at 1ms steps) apply.

    • Rewrite routes that serve pre-rendered HTML

      Costs for S3 apply.

    • Routes that use Server-Side-Rendering (SSR)

      Costs for HTTP API-Gateway and regional Lambda (SSR, metered in 1ms steps) apply.

The total costs are usually far below 0.50$ / month for a few thousand requests with this model, while having a fast-serving site powered by CloudFront edge caching.

Find more information on the GitHub repo: https://github.com/dealmore/terraform-aws-next-js

ofhouse
  • 3,047
  • 1
  • 36
  • 42
16

NextJS + Serverless is not Free.

NextJS + Serverless is currently deployed on Lambda Edge which is not free. You do not enjoy the free tier from Lambda (not Lambda@Edge).

Vercel + NextJs is Free

If you have a low traffic website I would recommend you to deploy it with Vercel.com which uses Lambda (AWS Network) on the backend.

*Their hobby version is free and gives generous free traffic and invocation comparable to AWS Lambda Free tier.

Deployment of a NextJS App is as easy as uploading to Github + Vercel's auto deployment with GitHub integration. You do not need to bother about S3, or hosting or your static files, everything gets hosted on Vercel the moment you push to Github. You just need to concentrate on development.

When your your requirement goes up (you go past the Hobby package, and you go past the Pro package), then it becomes more cost effective deploying on Serverless@Edge.

By then, all you need to do is to switch your domain over.

Update: Just deploy it on a VPS

Serverless is a nice concept, and the ability to launch your websites for free on various platform is a plus.

However, cold start can be a big problem as it sometimes take 3-4 seconds to load a page for your visitor.

This is not so much of a problem if you are doing static OR static incremental generation. It's just NO GOOD for getServerSideProps.

If you are struggling for cold starts, trust me and move on to a VPS. A $5 VPS can run a site pretty well.

Someone Special
  • 12,479
  • 7
  • 45
  • 76
  • when you deploy to a VPS, are the files inside the `api` folder just regular server endpoints (which is what I hope) I read somewhere that if you deploy to vercel, the api endpoints are turned to serverless functions. – Clifford Fajardo Mar 18 '21 at 23:35
  • 3
    when u deploy to VPS, yes it runs like how you work with "next dev", everything is serve from your VPS with no speed penalty. You need to start the app with "next build" and "next start", or manage it with "PM2" – Someone Special Mar 19 '21 at 06:40
  • 1
    It's worth mentioning that free Vercel hobby plans are limited to personal, non-commercial use. More info: https://vercel.com/docs/platform/fair-use-policy#commercial-usage – Michal Svorc May 03 '21 at 04:28
7

You can use AWS Lightsail: https://aws.amazon.com/lightsail/

In my experience with nextjs the cloud functions are not a good place to deploy a large application, so, this would be your options:

  1. Only go with cloud functions if your app is super small and is never gonna grow. Cloud function have limitations on file size, dependencies, bundle size, etc, etc, etc
  2. AWS Lightsail: https://aws.amazon.com/lightsail/ and a small VPS that you can set up your self with Nginx and node. Is like $5 / month and you can use your credits.
  3. Same as numbers 1, but on Digital Ocean.
  4. AWS Ec2
alacret
  • 572
  • 4
  • 19
6

Not sure if you have a requirement to host on Amazon or not, but you can host on DigitalOcean for $5/month, or you can host on the free tier for Heroku until you confident you want to move to Amazon you can later move to a more expensive solution and host of EC2:

  • DigitalOcean That will give you 1 GB Memory - 25GB SSD - 1TB Transfer for $5/month
  • Heroku That will give you 512MB Memory - 1 Web and 1 Worker Dyno for free and even if you will pay there are some affordable prices and Heroku is managed service so they will take care of everything and you don't have to set up anything

I believe that should be a good start for you before pay for more expensive solutions

And that answer for your questions, Yes, EC2 is the cheapest for Amazon and Elastic beanstalk if you prefer for a more manged solution within Amazon

mohamed-ibrahim
  • 10,837
  • 4
  • 39
  • 51
  • I actually have "free AWS credits" for a limited amount of time, hence my question. So there is no way to handle the SSR on a let's say "limited EC2" and the static part on an S3 server? The "only" option using only AWS would be going all in on an EC2? – Thanh-Quy Nguyen Apr 26 '20 at 10:44
4

To deploy our nextJs website, we have been using AWS lambda: https://github.com/serverless-nextjs/serverless-next.js It was amazingly simple to use it. Unfortunately sometime the load of the page was very slow. It was from 2 seconds to 7 seconds. It was also confirmed by google search console. enter image description here

We could not find a way to really deep dive this issue and how we were able to solve this, but I suspect a cold start. After some research, AWS it was theoretically possible to solve it with concurrency:

https://aws.amazon.com/blogs/compute/new-for-aws-lambda-predictable-start-up-times-with-provisioned-concurrency/

But I could not managed to make it work, as it is a Lambda@Edge and it is also very expensive! enter image description here

At http://nachonacho.com we focus on SEO, so the time to load the page was our biggest concern.

We finally decided to move to a simple AWS EC2.

Here you have the comparaison:

enter image description here

source: https://www.site24x7.com/

enter image description here

  • Light blue: EC2
  • Dark Blue: Lambda image image

Source: https://www.dareboost.com/

Alan
  • 9,167
  • 4
  • 52
  • 70
  • 1
    Is it possible that your Lambda was cold? I believe there are ways to keep it hot to prevent situations like the above – bmoe24x Nov 17 '20 at 01:42
  • 3
    There are ways to keep a container warm. However, the idea of serverless functions is that it can spin up several containers to server connection spike. You can keep one container warm but you cannot keep all the containers warm. – Someone Special Jun 18 '21 at 05:56
  • @Alan when you moved to AWS ec2 what was the full infrastructure stack? How you implement and achieved "Incremental Static Regeneration"? https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration – Saad Zulfiqar Feb 15 '22 at 14:08