data fetching and caching in next js
user profile avatar
the don
Author

Published on • 🕑3 min read

Data Fetching and Caching in NextJS

3likes16

Blog views1.7K

Listen to this blog
share this blog

Share Post

logoData Fetching and Caching in NextJS


Facebook
X
Whatsapp
Telegram
Reddit
Linkedin
Instapaper
Pinterest
Email
QR Code
More..

In the realm of web development, data fetching stands tall as a fundamental aspect, akin to the very fabric that weaves together intricate applications. In this journey through the corridors of React and Next.js, let’s delve into the art of fetching, caching, and revalidating data, unraveling the mysteries and unveiling the potentials that lie within.

Fetching Data on the Server with fetch

The saga begins with the native fetch API, a trusty companion in the quest for data. Next.js, with its adept prowess, extends fetch to the server, empowering developers to configure caching and revalidating behaviors with finesse. Whether it’s within Server Components, Route Handlers, or Server Actions, the landscape is ripe for exploration.

async function fetchData() {
  try {
    const res = await fetch('https://api.example.com/...')
    if (!res.ok) {
      throw new Error('Failed to fetch data')
    }
    return res.json()
  } catch (error) {
    console.error('Error fetching data:', error)
  }
}

Caching: The Guardian of Data

As data flows into our applications, caching emerges as a stalwart guardian, ensuring swift access and reducing the burden on our sources. Next.js, ever vigilant, automatically caches fetch responses on the server, unleashing the power of the Data Cache.

// Utilizing cache-control for caching
fetch('https://...', { cache: 'force-cache' })

Revalidating Data: Keeping It Fresh

Yet, in the ever-changing landscape of data, staleness looms as a lurking shadow. Fear not, for revalidation comes to our aid, breathing life into our cache and ensuring our data remains as fresh as the morning dew. With Next.js, we wield the power to revalidate data based on time or demand, sculpting experiences that stand the test of time.

// Revalidating at timed intervals
fetch('https://...', { next: {cache:"force-cache", revalidate: 3600 } })

On-Demand Revalidation: A Call to Action

In the throes of interaction, on-demand revalidation emerges as our trusted ally. Whether it’s a form submission or an event trigger, the ability to summon forth the latest data at our command ensures our applications remain responsive and relevant.

import { NextRequest } from 'next/server'
import { revalidateTag } from 'next/cache'
export async function GET(request: NextRequest) {
  const tag = request.nextUrl.searchParams.get('tag')
  revalidateTag(tag)
  return Response.json({ revalidated: true, now: Date.now() })
}
// Summoning on-demand revalidation
revalidateTag('collection')

Opting Out and Beyond

Yet, in the vast tapestry of options, lies the freedom to choose. Next.js bestows upon us the power to opt out of caching, to dance to our own rhythm, and to dictate the flow of data according to our needs. From individual fetch requests to segment-wide configurations, the canvas is ours to paint.

// Opt out of caching for all data requests in the route segment
export const dynamic = 'force-dynamic'

Journey Beyond: Client-Side Adventures

As we traverse the realms of React and Next.js, we encounter the duality of client-side fetching. From the hallowed halls of Route Handlers to the enigmatic realms of third-party libraries like SWR and TanStack Query, the journey continues, each path leading to new discoveries and boundless possibilities.

In the grand tapestry of web development, data fetching, caching, and revalidation stand as pillars of strength, guiding our journey and shaping our experiences. With Next.js as our companion, let us embark on this odyssey, where each line of code is a step closer to unlocking the full potential of the digital realm.

Like what you see? Share with a Friend

share this blog

Share

Share Post

logoData Fetching and Caching in NextJS


Facebook
X
Whatsapp
Telegram
Reddit
Linkedin
Instapaper
Pinterest
Email
QR Code
More..

3 Comments

16 Likes

Comments (3)

sort comments

Before you comment please read our community guidelines


Please Login or Register to comment

user profile avatar

Tech Tales Team

Admin

Published on

time to invalidate that cache

GIF

Tutor JulietHide Reply

Tutor Juliet

Nov 3, 2024

Go fetch 😂

GIF

user profile avatar

the don

Author
Admin

Published on

This makes it easier. However, you should be keen since some content might fail to reflect that often, especially if you have longer revalidate time. The trick is to set a shorter period.

user profile avatar

Tutor Juliet

Published on

NextJS goes full God Mode with caching but their current version allows you to opt into caching and choose what to cache😃

GIF