Open In App

Caching in Next.js

Last Updated : 09 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Caching is all about storing copies of the data in temporary storage, and that stored data is called cache. The main reason to do caching is that, in the future, when that data is needed, it can be served faster, and we don't have to fetch the data from the original source, because that can take some extra time, which can cause a performance issue, if the fetching process is done quite frequently.

Caching in Next.js

Next.js, a popular React framework, offers several caching strategies that developers can use to optimize their applications.

Steps to create the NextJS Application

Step 1: Create a React application using the following command:

npx create-next-app@latest testapp

Step 2: After creating your project folder i.e. testapp, move to it using the following command:

cd testapp

Step 3: After creating the nextJS app we have to create an another directory testpage inside that create a file page.tsx, after all that this is what our project directory will look like.

Project Structure

Screenshot-2024-06-30-015402
Folder Structure

Dependencies

"dependencies":
{
"react": "^18",
"react-dom": "^18",
"next": "14.2.3"
}

Static Generation (SSG)

Static Generation is a method where HTML pages are pre-rendered at build time. This results in faster load times since the content is served as static files. Pages generated this way can also be cached on the CDN level. Incremental Static Regeneration (ISR) allows you to update static content after the site has been built and deployed. With ISR, you can regenerate specific pages based on a predefined interval or trigger, ensuring the content remains fresh without rebuilding the entire site.

Example: By using the revalidate option, Next.js allows you to cache statically generated pages on the server.

export async function getStaticProps() {
const data = await fetchData();
return {
props: {
data,
},
revalidate: 10, // Regenerate the page every 10 seconds
};
}

In this example, the page will be revalidated and regenerated every 10 seconds, ensuring fresh content while maintaining the performance benefits of static generation.

Server-Side Rendering (SSR)

Server-Side Rendering generates HTML pages on each request. While SSR ensures that content is always up-to-date, it can be slower compared to SSG. To improve performance, caching strategies can be implemented to store rendered HTML and reuse it for subsequent requests.

Example: Using HTTP headers, you can instruct the browser to cache server-rendered pages. Here, Cache-Control header specifies that the response can be cached by any cache (public), should be revalidated after 10 seconds (s-maxage=10), and can be served stale while revalidating for up to 59 seconds.

export async function getServerSideProps(context) {
const res = await fetch(`https://...`);
const data = await res.json();

context.res.setHeader(
'Cache-Control',
'public, s-maxage=10, stale-while-revalidate=59'
);

return { props: { data } };
}

API Caching

API routes in Next.js can benefit from caching to reduce latency and server load. Implementing caching in API routes ensures that frequently accessed data is served quickly.

Example: Using a caching library, you can cache API responses in Next.js.

import { NextApiRequest, NextApiResponse } from 'next';
import { cache } from 'some-cache-library';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const cachedData = cache.get(req.url);
if (cachedData) {
res.status(200).json(cachedData);
return;
}

const data = await fetchData();
cache.set(req.url, data, 60); // Cache for 60 seconds

res.status(200).json(data);
}

Client-Side Caching

Client-side caching involves storing data in the browser to reduce the need for repeated network requests. This can be achieved using service workers, local storage, or in-memory caching.

Example: Using the react-query library, you can cache API responses in memory.

import { useQuery } from 'react-query';

function MyComponent() {
const { data, error, isLoading } = useQuery('fetchData', fetchData, {
staleTime: 30000, // Cache data for 30 seconds
});

// Render component
}

Best Practices for Caching in Next.js

  • Use Static Generation with ISR: Prefer static generation for pages that do not change frequently and use ISR for those that need periodic updates.
  • Implement Effective Cache Invalidation: Ensure your cache invalidation strategy aligns with your content update frequency to avoid serving stale content.
  • Leverage Browser Caching: Use HTTP caching headers to instruct browsers to cache static assets like images, scripts, and stylesheets.
  • Monitor and Tune Cache Performance: Continuously monitor cache hit rates and performance metrics to optimize your caching strategy.

Example : In Next.js, server-side rendered pages are automatically cached, retaining state between navigations, while client-side rendered pages do not inherently cache state, resulting in potential data changes with each navigation.

JavaScript
// app > page.tsx (This is the home page, 
// which is directly in the app direcotry in the nextjs application)

import Link from "next/link";

export default function Home() {
  function randomeThreeDigitNumber() {
    return Math.floor(Math.random() * 900) + 100;
}
  return (
    <main className="flex flex-col items-center justify-between p-24">
       <h1>Homepage</h1>
            <h2>{randomeThreeDigitNumber()}</h2>
            <Link href="/testpage">NextPage</Link>
    </main>
  );
}
JavaScript
// app > testpage > page.tsx (This is another page 
// inside the testpage directory inside the app directory)

"use client"
import Link from 'next/link';

export default function Test() {
    function randomeThreeDigitNumber() {
        return Math.floor(Math.random() * 900) + 100;
    }
    return (
        <div className='flex flex-col items-center justify-between p-24'>
            <h1>Nextpage</h1>
            <h2>{randomeThreeDigitNumber()}</h2>
            <Link href="/">Homepage</Link>
        </div>
    )
}

Output


Next Article
Article Tags :

Similar Reads