In Next.js, the built-in fetch API is your primary tool for retrieving data. It's a powerful and flexible way to interact with external APIs and data sources, whether you're running it on the server or the client. Next.js enhances the native fetch with automatic deduplication and caching, making your data fetching more efficient and performant.
The core concept is straightforward: you use fetch just like you would in a standard browser environment, but Next.js adds intelligent caching layers behind the scenes.
async function getData() {
const res = await fetch('https://api.example.com/data');
if (!res.ok) {
throw new Error('Failed to fetch data');
}
return res.json();
}When you use fetch within Server Components, Next.js provides automatic request deduplication. This means if you call fetch multiple times with the same URL within a single render pass, Next.js will only execute the request once, significantly reducing redundant network calls and improving performance.
graph TD;
A[Component Rendering] --> B{Multiple fetch calls to same URL?};
B -- Yes --> C[Next.js Deduplication];
C --> D[Single Network Request];
B -- No --> D;
D --> E[Data Retrieved];
Next.js also leverages caching for fetch requests. By default, data fetched with fetch is cached on the server for the lifetime of the component. This means that subsequent renders of the same component, or even different components requesting the same data, will use the cached result instead of making a new network request.
You can control the caching behavior of fetch using options. For instance, cache: 'no-store' will prevent caching and always fetch fresh data, which is useful for dynamic or frequently changing information. Conversely, cache: 'force-cache' (the default) ensures data is cached.
async function getLiveStockData() {
const res = await fetch('https://api.example.com/stocks/live', {
cache: 'no-store'
});
if (!res.ok) {
throw new Error('Failed to fetch live stock data');
}
return res.json();
}