Fetching data in Next.js - Beginner's guide
17/12/2023
10 min
Bartosz Lewandowski
Fetching data in Next.js - Beginner's guide
17/12/2023
10 min
Bartosz Lewandowski
Table of Contents
Also check out: Rendering in Next.js - server and client components in a nutshell
Effective and optimal data fetching is essential for ensuring smooth and responsive web applications. In this article, we will focus on various aspects and techniques of data fetching in the context of Next.js. We will discuss methods that will help in efficient data management, caching, and revalidation to provide the best user experience.
Fetching data on the server using fetch
Next.js, as a modern framework for React, brings significant improvements in the data fetching process, surpassing the boundaries of the standard Web API fetch interface. This extension allows developers not only to perform network requests but also to have precise control over how the responses from these requests are cached and revalidated. As a result, applications built with Next.js can be more efficient, reducing server load and speeding up access to frequently used data.
Automatic query memorization
Another important feature offered by Next.js is the ability to automatically memorize fetch queries during the rendering of the React component tree. This means that queries executed within components can be intelligently managed by the framework, increasing performance by avoiding unnecessary repetitions of the same queries. This is particularly useful in scenarios where data is frequently reused in different parts of the application.
Impact on performance
Thanks to these advanced features, Next.js significantly impacts performance. Reducing the number of server requests and effectively using caching means faster page load times. As a result, users receive smoother and more satisfying experiences, which is a key element of success for modern web applications.
Data Caching
Caching involves storing data so that it does not have to be fetched from an external source with every request. By default, Next.js automatically caches the values returned by fetch in the server cache.
Caching example
The force-cache value is default, meaning we don't have to add it every time.
Data Revalidation
Data revalidation is a key element in managing cached data in web applications. In the context of Next.js, revalidation allows for refreshing stored data, ensuring that users receive the most up-to-date information. There are two main approaches to revalidation: time-based and on-demand.
Time-based revalidation
Time-based revalidation, as the name suggests, involves automatically refreshing data after a specified time. This is particularly useful in scenarios where data changes in a predictable manner or where data freshness is not critical but still important.
Example:
In the above example, revalidate: 3600 means that the data will be automatically revalidated (refreshed) every hour. This means that if the data has been fetched and cached, it will not be fetched again from the server for the next hour. After this time, on the next request, Next.js will fetch fresh data.
On-demand revalidation
In addition to time-based revalidation, there is also the option for on-demand revalidation. This method is useful in situations where data needs to be refreshed immediately after certain events, such as after a user updates content or receives new data from an external source.
On-demand revalidation can be achieved in several ways, including through special API functions provided by Next.js, such as revalidatePath and revalidateTag. They allow for dynamically triggering the revalidation process, which is particularly useful in dynamic and interactive applications.
Example: Let's assume we have a Next.js application that uses data from a product collection. We want this data to be revalidated immediately after a new product is added.
Step 1: Fetch with cache tag
In the above example, the fetch query is tagged with products-collection, allowing easy identification and grouping of queries related to the product collection.
Step 2: Revalidation by tag When a new product is added, we want the data to be revalidated immediately. We can do this by triggering on-demand revalidation using revalidateTag.
In this scenario, when the addProduct function is called, after successfully adding the product to the collection, data revalidation tagged with products-collection is triggered.
Route segment config
In Next.js, route.ts, page.tsx, and layout.tsx files can export specific settings that affect the behavior of a given page or API. For example, to change the runtime environment to Edge instead of the default Node.js, we use the following declaration:
Configuration options
dynamic: This option gives control over how the page is rendered. You can enforce dynamic or static behavior, which is useful in various scenarios, such as creating highly interactive pages or pages that rarely change. Possible options are:
- auto: default behavior, as observed so far.
- force-dynamic: disables cache; all fetch queries are fetched every time, as with cache: 'no-store'.
- error: enforces static rendering; using dynamic functions or cache: 'no-store' results in an error.
- force-static: enforces static rendering; dynamic functions return empty objects.
dynamicParams: Specifies behavior when a page has a defined generateStaticParams function, but the user visits an address with parameters not included in this function.
- true: default behavior; dynamic pages are generated ad hoc.
- false: if a parameter was not returned by generateStaticParams, visiting such a subpage results in a 404 error.
revalidate: Modifies the default revalidate value for fetch on a given page.
- false: default behavior.
- 0: enforces dynamic data fetching; works like cache: 'no-store'.
- Any other integer value in seconds.
preferredRegion: Preferred deployment region; depends on the hosting platform. It can be a string or an array, with the default value all.
fetchCache: Advanced setting allowing more precise control over cache behavior for fetch. Possible options are:
- auto: default behavior.
- default-cache: changes the default cache option for fetch to force-cache.
- only-cache: changes the default cache option for fetch to force-cache and throws an error when trying to use a different value.
- force-cache: overrides the cache option for fetch to force-cache.
- default-no-store: changes the default cache option for fetch to no-store.
- only-no-store: changes the default cache option for fetch to no-store and throws an error when trying to use a different value.
- force-no-store: overrides the cache option for fetch to no-store.
Summary
Fetching, caching, and revalidating data in Next.js provides numerous opportunities for optimization and improving user experience. The presented methods and code examples form a solid foundation for utilizing these techniques in practice. If you want to learn how to further speed up your site in Next.js, don't miss our next post Optimizations in Next.js - How to speed up your site? You'll find practical tips and techniques to help you further improve your application's performance.
Frequently Asked Questions
- What is Next.js and why is it used for data fetching? Next.js is a modern framework for React that streamlines the data fetching process in web applications. It uses an extended version of fetch for optimizing application performance and responsiveness.
- How does Next.js improve the data fetching process? Next.js introduces advanced features such as automatic fetch query memorization and intelligent cache management, which increases application performance and reduces server load.
- What is data caching and how is it implemented in Next.js? Caching is the storage of data in memory to avoid re-fetching it from external sources. Next.js automatically caches values returned by fetch, increasing application performance.
- What are the methods of data revalidation in Next.js? Next.js offers two main methods of data revalidation: time-based and on-demand. Time-based revalidation automatically refreshes data after a specified time, while on-demand revalidation allows for immediate data refresh after specific events.
- What is Route Segment Config in Next.js? Route Segment Config is a set of settings in Next.js that allow for customizing the behavior of a page or API. You can, for example, change the runtime environment to Edge, control page rendering, or modify cache behavior for fetch.
- What are the main benefits of using Next.js for data fetching? Next.js offers increased performance through better data fetching management, automatic caching, and revalidation. This enhances user experience by providing faster page loads and up-to-date information.
- Are there any advanced cache settings in Next.js? Yes, Next.js allows for advanced cache control through options such as default-cache, only-cache, force-cache, and others, enabling precise configuration of cache behavior for fetch.
Bartosz Lewandowski
CEO