Next.js 14: Efficient Data Fetching with Fetch API Caching

Hardik Desai
2 min readMar 29, 2024

--

If you’re familiar with the features of Next.js 14, you’ve likely encountered the term caching. In this blog, we’ll explore the best practices for fetching and caching data on the server side.

What is Data Caching?

Data caching is like keeping important notes handy for quick reference, speeding up software performance by storing and reusing frequently accessed data, crucial in Next.js for faster page loading and a smoother user experience.

Route handlers and pages within the app directory of a Next.js app, named page.tsx are inherently server components by default. These components are built upon the same foundation.

Previously, in the pages directory for server-side data fetching, methods like getStaticProps and getServerSideProps were commonly used. However, in the new version, the approach remains quite similar, emphasizing ease of use and familiarity for developers.

Here’s a quick example to demonstrate: consider a simple page created within app/page.tsx Since it’s a server component, data can be fetched like this:

export default async function Home() {
const res = await fetch("/api/get-post");
const data = await res.json();

return (
<main className="p-24">
<h1>NEXT.js 14</h1>
{data?.posts?.map((post: any) => (
<p key={post.id}>{post.title}</p>
))}
</main>
);
}

Caching:

In the fetch function, there’s an optional argument called cache, where force-cache is the default value in server components.

// 'force-cache' is the default, and can be omitted
fetch('https://...', { cache: 'force-cache' })

To avoid caching data, we can set it as follows:

fetch(`https://...`, { cache: 'no-store' })

Adding no-store ensures that new data is fetched with each reload.

Revalidating:

Revalidating is akin to the previous Incremental Site Generation feature. By setting a time in seconds, it retains cache for a specific duration, refreshing data upon page refresh. This functionality is valuable for managing dynamic data scenarios.

// Revalidate at most every hour
fetch('https://...', { next: { revalidate: 3600 } })

Note: When utilizing route handlers as an API, remember that GET requests result in indefinite data caching, making revalidation inapplicable. For scenarios requiring revalidation, opt for POST requests instead of GET.

Conclusion

In summary, this blog has discussed how data caching in Next.js improves performance and user experience. It covered default caching in server components and the importance of revalidation in different request methods. By using these techniques effectively, developers can achieve faster page loading and a smoother user experience.

--

--

Hardik Desai
Hardik Desai

Written by Hardik Desai

Transforming ideas into seamless online solutions

No responses yet