In a Next.js project, if you need to fetch data from an API before rendering a single page, you have several options depending on whether you're working with server-side or client-side data fetching. Here are the recommended approaches:
1. Server-Side Rendering (SSR)
If you want to fetch data on the server for each request, you can use getServerSideProps. This is useful if the data changes frequently and needs to be up-to-date with every request.
// pages/matter/[id].js
import React from 'react';
function MatterPage({ data }) {
// Render the data
return (
<div>
<h1>Data for Matter Page</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
export async function getServerSideProps(context) {
const { id } = context.params;
const res = await fetch(`https://your-site.com/api/myroute?id=${id}`);
const data = await res.json();
return {
props: { data }, // will be passed to the page component as props
};
}
export default MatterPage;
2. Static Generation with Revalidation (ISR)
If your data can be static for a period of time, you can use getStaticProps with Incremental Static Regeneration. This approach is efficient and makes your pages load quickly.
// pages/matter/[id].js
function MatterPage({ data }) {
return (
<div>
<h1>Data for Matter Page</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
export async function getStaticProps({ params }) {
const res = await fetch(`https://your-site.com/api/myroute?id=${params.id}`);
const data = await res.json();
return {
props: { data },
revalidate: 10, // Revalidate the data every 10 seconds
};
}
export async function getStaticPaths() {
// Specify dynamic routes that should be pre-rendered
// Fetch all IDs that you want to pre-render
const res = await fetch(`https://your-site.com/api/all-matter-ids`);
const ids = await res.json();
const paths = ids.map((id) => ({
params: { id: id.toString() },
}));
return {
paths,
fallback: 'blocking',
};
}
export default MatterPage;
3. Client-Side Fetching
If you prefer to fetch data on the client side, you can do so using React's useEffect hook or React Query. This method is suitable if the data is not necessary for the initial page load or if you want to load it after the page has been displayed.
// pages/matter/[id].js
import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
function MatterPage() {
const router = useRouter();
const { id } = router.query;
const [data, setData] = useState(null);
useEffect(() => {
if (id) {
fetch(`/api/myroute?id=${id}`)
.then((res) => res.json())
.then((data) => setData(data));
}
}, [id]);
if (!data) return <p>Loading...</p>;
return (
<div>
<h1>Data for Matter Page</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
export default MatterPage;
Choose the approach that best fits your use case. SSR is ideal for dynamic data, ISR for data that changes less frequently, and client-side fetching for data that can be loaded after initial render.