Next.js provides multiple data-fetching methods, each tailored for different use cases. In this blog, we'll focus on two methods: getServerSideProps and getStaticProps.
1. getServerSideProps: Fetching Data on Each Request
When you need fresh data on every request, such as in a dashboard or dynamic content that changes frequently, getServerSideProps is your go-to method. It runs on the server side and fetches data before rendering the page.
Here’s how you can implement it in a Next.js page:
export async function getServerSideProps(context) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${context.params.id}`);
const data = await res.json();
return {
props: { post: data },
};
}
export default function BlogPost({ post }) {
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
}
In this example, we are using getServerSideProps to fetch a blog post based on its id. This ensures that every time a user visits a blog page, the most up-to-date data is fetched and rendered on the server.
2. getStaticProps: Pre-rendering at Build Time
On the other hand, when your content doesn’t change often (such as a marketing page or a blog with static content), you can use getStaticProps. This method pre-fetches data at build time and serves the same static HTML to all users.
Here’s an example using getStaticProps:
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await res.json();
return {
props: { posts: data },
};
}
export default function BlogList({ posts }) {
return (
<div>
{posts.map(post => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
))}
</div>
);
}
In this case, the blog posts are fetched once at build time. This approach is ideal for content that doesn't change frequently, as it reduces server load and results in faster response times.