How do I get my layout component to remain static in Next13 app folder

146 Views Asked by At

I am trying to create a layout component that fetches its own data, I have tried adding the cache: 'force-cache' to the fetch but every time I update my CMS content and refresh my page the new content is loaded. Here is an example of my code:

const getLayoutData = async () => {
 const response = await fetch(
    `https://cdn.contentful.com/spaces/${
      process.env.CONTENTFUL_SPACE_ID
    }/environments/${
      process.env.CONTENTFUL_ENVIRONMENT || "master"
    }/entries/${fieldId}?access_token=${process.env.CONTENTFUL_ACCESS_TOKEN}`,
    {
      cache: "force-cache",
    }
  );

  const {entryTitle, ...headerData} = await response.json();

  return { headerData };
}

export default async function Layout() {
 const data = await getLayoutData();
...
2

There are 2 best solutions below

0
sm3sher On

You can use the getStaticProps() function to fetch data at build time and make it available to your component as a prop. This way, the data will be pre-rendered on the server and will not change when the user refreshes the page:

import getLayoutData from './getLayoutData';

export async function getStaticProps() {
  const data = await getLayoutData();
  return { props: { data } };
}

export default function Layout({ data }) {
  // Use data in your component
  ...
}

Alternatively you could use getServerSideProps(), it runs on the server at request time instead of build time. I would recommend that if you have dynamic data that changes frequently:

import getLayoutData from './getLayoutData';

export async function getServerSideProps(context) {
  const data = await getLayoutData();
  return { props: { data } };
}

export default function Layout({ data }) {
  // Use data in your component
  ...
}
0
Mayank Kumar Chaudhari On

By default, Next.js automatically does static fetches. This means that the data will be fetched at build time, cached, and reused on each request. As a developer, you have control over how the static data is cached and revalidated.

Refer to the docs - https://beta.nextjs.org/docs/data-fetching/fundamentals

Also, this will work in production mode. So, make sure you are using next build && next start and not next dev.

In case you are fetching data from same URL anywhere else, the cache might be getting updated. As Next.js also does request deduplication built into the fetch function itself.