In Next.js, there are several approaches for data fetching depending on your requirements and preferences:
Static Generation (getStaticProps/getStaticPaths): Use this approach when you have content that can be pre-rendered at build time. Data fetching occurs at build time, and the pre-rendered HTML is served to the client. This is great for static content like blog posts, marketing pages, etc.
export async function getStaticProps() {
const data = ... // Fetch data from your API or database
return {
props: {
data,
},
}
}
Server-Side Rendering (getServerSideProps): Use this approach when you need to fetch data on each request. Data fetching occurs on the server-side, and the page is rendered with the fetched data. This is useful for pages with dynamic data that changes frequently.
export async function getServerSideProps() {
const data = ... // Fetch data from your API or database
return {
props: {
data,
},
}
}
Client-Side Rendering (useSWR, SWR, or directly with fetch): Use this approach when you need to fetch data client-side after the initial page load. This is great for data that frequently changes and doesn’t need to be indexed by search engines.
import useSWR from 'swr'
function MyComponent() {
const { data, error } = useSWR('/api/data', fetcher)
if (error) return <div>Error fetching data</div>
if (!data) return <div>Loading...</div>
return (
<div>
{data.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
)
Incremental Static Regeneration (ISR): Introduced in Next.js 9.5, ISR allows you to update static content without rebuilding the entire site. You can specify a revalidation interval to fetch updated data and rebuild pages with the new content.
export async function getStaticProps() {
const data = ... // Fetch data from your API or database
return {
props: {
data,
},
revalidate: 60, // Revalidate every 60 seconds
}
}