0
0
NextJSframework~5 mins

Why caching is central to Next.js

Choose your learning style9 modes available
Introduction

Caching helps Next.js show pages faster by saving parts of the website. This means users don't have to wait long for pages to load.

When you want your website to load quickly for visitors.
When your site has pages that don't change often.
When you want to reduce the work your server does.
When you want to save data so users can see it even if offline.
When you want to improve your website's performance on slow internet.
Syntax
NextJS
export async function getStaticProps() {
  // fetch data here
  const data = {};
  return {
    props: { data },
    revalidate: 60, // cache this page for 60 seconds
  };
}

revalidate tells Next.js how long to keep the cached page before updating it.

Caching works automatically with Next.js data fetching methods like getStaticProps.

Examples
This caches the page for 10 seconds before Next.js fetches fresh data.
NextJS
export async function getStaticProps() {
  return {
    props: { message: 'Hello!' },
    revalidate: 10,
  };
}
Server-side rendering does not cache by default, so pages load fresh every time.
NextJS
export async function getServerSideProps() {
  // No caching here, runs on every request
  return { props: { time: Date.now() } };
}
This caches the page for one hour, good for content that changes rarely.
NextJS
export async function getStaticProps() {
  return {
    props: { data: 'Static content' },
    revalidate: 3600, // cache for 1 hour
  };
}
Sample Program

This Next.js page shows the time it was generated. It caches the page for 30 seconds, so users see the same time if they visit within that period. After 30 seconds, Next.js updates the page with the new time.

NextJS
export async function getStaticProps() {
  const time = new Date().toLocaleTimeString();
  return {
    props: { time },
    revalidate: 30,
  };
}

export default function TimePage({ time }) {
  return (
    <main>
      <h1>Current Time</h1>
      <p>This page was generated at: {time}</p>
      <p>It will update every 30 seconds.</p>
    </main>
  );
}
OutputSuccess
Important Notes

Caching improves speed but remember to set the right time so users get fresh data when needed.

Next.js handles caching automatically when you use revalidate with static props.

Too long caching can show old data; too short caching can reduce performance benefits.

Summary

Caching saves website parts to load pages faster.

Next.js uses caching with revalidate to control how often pages update.

Good caching balances fresh data and fast loading.