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.
Tech Tales Team
Published on
time to invalidate that cache
Tutor Juliet
• Nov 3, 2024Go fetch 😂
the don
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.
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😃