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
Folder StructureDependencies
"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
Similar Reads
Functions in Next JS
Next.js provides a suite of functions and hooks that enhance server-side rendering, static generation, routing, and more. These functions are essential for managing data fetching, handling requests, and optimizing performance in Next.js applications. Next.js FunctionsNext.js functions simplify serve
4 min read
Next.js Data Fetching
Next.js Data Fetching refers to the process of getting data from a server or an API and displaying it on a webpage. Next.js offers multiple data-fetching methods to handle server-side rendering, static generation, and client-side rendering. These methods enable you to fetch and manage data efficient
6 min read
cookies in Next JS
Next.js provides cookies methods that allow you to store small pieces of data on the client side. It provides methods to store, delete, components and retrieve the cookie. cookies function can only used in server components. To store and delete the cookie at the client side using the cookies functio
3 min read
Fonts in Next JS
The font module in next.js allows to add any external or local fonts. Fonts are used to style the components and to increase the readability of the application. The font is associated with the style, size, width, and typeface i.e. design of the letters. We can customize the font according to our cho
6 min read
Server Actions in Next.js
Server actions in Next.js refer to the functionalities and processes that occur on the server side of a Next.js application. It enables efficient, secure handling of server-side operations like data fetching, form processing, and database interactions, enhancing application security and performance
4 min read
CSS-in-JS Next JS
CSS-in-JS in Next.js enables you to write CSS styles directly within your JavaScript or TypeScript files. This approach allows you to scope styles to components and leverage JavaScript features, improving maintainability and modularity. In this article learn how to use CSS-in-JS in NextJS its syntax
3 min read
Next.js Function Fetch
Next.js is a React framework that enhances UI development with built-in features like server-side rendering and static site generation. It supports data fetching both on the server and client sides, enabling developers to load and manage data efficiently. By utilizing functions like fetch, Next.js a
6 min read
Next.js Installation
Next.js is a popular React framework that enables server-side rendering and static site generation. It is easy to learn if you have prior knowledge of HTML, CSS, JavaScript, and ReactJS. Installing Next.js involves setting up Node.js and npm, creating a new Next.js project using npx create-next-appa
4 min read
Next.js Introduction
Next.js is a powerful and flexible React framework that has quickly become popular among developers for building server-side rendered and static web applications. Created by Vercel, Next.js simplifies the process of developing modern web applications with its robust feature set. In this article, weâ
5 min read
File Conventions in Next.js
The Next.js file conventions include specific directories and filenames like pages, app, layout.js, and middleware.js, which automatically define routes, layouts, middleware, and other configurations, ensuring a structured and efficient project organization. In this article, we will learn about the
5 min read