When working with Next.js, `getServerSideProps` is a powerful feature that allows you to fetch data on the server side before rendering a page. This function runs on each request, making it ideal for dynamic data that changes frequently. In this response, I will explain how to use `getServerSideProps`, provide practical examples, discuss best practices, and highlight common mistakes to avoid.
To use `getServerSideProps`, you need to export it from your page component. This function can return an object containing props that will be passed to the page component. Here’s a simple example:
import React from 'react';
const MyPage = ({ data }) => {
return (
Data from Server
{JSON.stringify(data, null, 2)}
);
};
export async function getServerSideProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: { data }, // will be passed to the page component as props
};
}
export default MyPage;
The `getServerSideProps` function must return an object with a `props` key. This object can also include a `redirect` key for redirection or a `notFound` key to display a 404 page. Here’s an example of both:
export async function getServerSideProps(context) {
const { id } = context.params;
const res = await fetch(`https://api.example.com/data/${id}`);
if (!res.ok) {
return {
notFound: true, // triggers a 404 page
};
}
const data = await res.json();
return {
props: { data },
};
}
In summary, `getServerSideProps` is a valuable tool in Next.js for fetching data server-side. By following best practices and avoiding common pitfalls, you can effectively utilize this feature to enhance your application's performance and user experience.