cachingnext.jsamazon-ecsaws-lambda-edge

How to cache a Server Side Rendered Page using Dynamic Routes with Next.js


I'm deploying a Next.js Application on AWS using ECS/Fargate (can't use Amplify due to custom logging and monitoring required). My Application is using api-routes and dynamic-routes with Server-Side-Rendering(getServerSideProps).

Lets say for the SSRed page the URL is something like: domain.com/foopage/[id]?powerlevel=10000.

The Code Looks something like:

// pages/foopage/[id].tsx

import React from "react";
import type { GetServerSideProps } from "next";
import Head from "next/head";

export default function FooPage({ id }: Record<string, string>) {
  return (
    <div>
      <Head>
        <title>Title</title>
      </Head>
      <main>
        <h1>
          Say Hi to <a href="https://sample-url.com/id">{id}</a>!
        </h1>
      </main>
    </div>
  );
}

export const getServerSideProps: GetServerSideProps = async (context) => {
  context.res.setHeader(
    "Cache-Control",
    "public, s-maxage=10, stale-while-revalidate=59"
  );
  const { id } = context.query;
  const response = await fetch(
    `${process.env.CMS_URL}/api/configurations?id=${id}`
  );
  const jsonResponse = await response.json();

  return {
    props: { id },
  };
};

I want to cache these pages so that the server doesn't have to generate the page every time.

I know that if you are using Vercel, Edge Caching works without configuration. But I'm bound to use AWS due to business-requirements. So how exactly to do it in AWS? Is it possible to do using Lambda@Edge and if so what could be the possible lambda function?


Solution

  • I know that if you are using Vercel, Edge Caching works without configuration. But I'm bound to use AWS due to business-requirements. So how exactly to do it in AWS?

    If you want edge caching, you need to use a CDN. Amazon's CDN is CloudFront.