I am currently using NextJS 13.5 to build an ecommerce.

In the app/products/[slug]/page.jsx I have product name, description, price and other product related information. I use the generateStaticParams() function in order to statically build each product page with next build.

Having said all that, the problem I am facing is that a product's price cannot be static! Products' prices change frequently, sometimes even daily.

How could I have the price of every product to be dynamic and fetched from the database on each visit, even though the rest of the product page (name, description etc) is static, and basically SSG?

Any knowledge or ideas are appreciated!

1

There are 1 best solutions below

0
On

I had two ideas when reading your question. The first should be accessible on Next.js 13, and the second requires updating to 14.

1. Using fetch with cache: 'no-store'

I found some information in the Next.js Pages -> App Router migration guide that I believe will be relevant in your case.

Explanation:

By setting the cache option to no-store, we can indicate that the fetched data should never be cached. This is similar to getServerSideProps in the pages directory.

Example:

// `app` directory
 
// This function can be named anything
async function getProjects() {
  const res = await fetch(`https://...`, { cache: 'no-store' })
  const projects = await res.json()
 
  return projects
}
 
export default async function Dashboard() {
  const projects = await getProjects()
 
  return (
    <ul>
      {projects.map((project) => (
        <li key={project.id}>{project.name}</li>
      ))}
    </ul>
  )
}

Link

Source: https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration#server-side-rendering-getserversideprops

2. Partial Prerendering

If you upgrade to 14 you can opt in to this experimental feature.

Explanation:

When a user visits a route:

  • A static route shell is served, this makes the initial load fast.
  • The shell leaves holes where dynamic content will load in async.
  • The async holes are loaded in parallel, reducing the overall load time of the page.

This is different from how your application behaves today, where entire routes are either fully static or dynamic.

Links

API reference: https://nextjs.org/docs/app/api-reference/next-config-js/partial-prerendering

Tutorial: https://nextjs.org/learn/dashboard-app/partial-prerendering