How to Fix Slow Loading Time for Your Next.js App deployed on AWS Amplify

Rav Arty
3 min readMar 8, 2024

--

AWS Amplify offers very convenient and fast deployments for Next.js apps. However, it’s not all that shiny once you go into production. I noticed that my simple website — https://www.useconverter.com/ — had a very long loading time, up to 12 seconds. That’s excessive for a website that doesn’t use any backend to load the main page.

After spending a lot of time trying to change various header settings, I found a very simple and cost-effective solution to this problem — Route 53 Health Checks. You can set your main domain as a destination for the health check, but it’s better to create an endpoint with a simple response.

I will provide two versions of code: one for App routers and another for Pages routers.

NextJs Page Router

To create an endpoint in older NextJS, go to api folder and create a file — healthcheck.ts:

import { NextApiRequest, NextApiResponse } from "next";

export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.setHeader("Cache-Control", "no-store");
res.status(200).json({ status: "ok" });
}

It’s crucial to set header to — res.setHeader(“Cache-Control”, “no-store”)

It’s crucial to set the header to res.setHeader(“Cache-Control”, “no-store”). If you don’t set the header to “no-store”, Route 53 Health Checks will make the first request to the server, and all subsequent requests would be redirected to a cached version instead of the server. This will pretty much nullify the whole point of creating a custom health check.

NextJs App Router

File structure: /app/api/healthcheck/route.ts

export async function GET(request: Request) {
return new Response("ok", {
status: 200,
headers: {
"content-type": "application/json",
"cache-control": "no-store",
},
});
}

Route53 Health Check

Now, the most interesting part. We need to a Health Check in Route 53.

Open AWS Console and find Route 53

Route 53 Dashboard

Select “Health checks” from the left side menu and click on “Create health check” button

Create health check

On Step 1 we need to configure our health check:

Name: useconverter (use your domain name without domain extension)

What to monitor: Endpoint (leave default)

Specify endpoint by: Domain name

Protocol: HTTPS

Domain name: www.useconverter.com

Port: 443 (default)

Path: /api/healthcheck (endpoint we created in NextJs earlier)

In advanced configuration leave all default values. You can of course change Health checker regions but I would recommend to use default values.

On Step 2 you can leave Create Alarm as No

After creating a Health check you should see something like this:

As for the cost, it will be around $1 per month. I have two websites and it was $1.59 for the last month.

Route 53 Health Check billing

For the time being, that is the easiest and cheapest solution to fix slow loading time on Amplify.

--

--