11 Feb 2024
getServerSideProps is an asynchronous function provided by Next.js that allows you to fetch data and pre-render a page on the server side. It runs at request time for every incoming request to the page, enabling dynamic data fetching and server-side rendering of pages in Next.js applications. This function is particularly useful for pages that require fresh or dynamic data on each request, or for scenarios where static generation is not feasible or appropriate.
Key important points about getServerSideProps:
-
Server-side Data Fetching:
getServerSidePropsis used to fetch data on every request to the page. This means that the data is fetched at request time on the server, ensuring that the page always renders with fresh data. -
Asynchronous Function:
getServerSidePropsmust be an asynchronous function that returns an object with the data that needs to be passed to the component for rendering. -
Context Parameter: It receives a context object as a parameter which contains various properties including
req(the HTTP request object) andres(the HTTP response object). -
Data Fetching: Inside
getServerSideProps, you can fetch data from any data source, like a database, an API, or the file system. -
Blocking Data: The data fetching is blocking, which means that the page will not be rendered until the data fetching is complete. This can affect the performance of the page, especially if the data fetching takes a long time.
-
Props Injection: The data returned from
getServerSidePropsis injected into the component as props. These props can then be used to render the page. -
Dynamic Routes:
getServerSidePropsis particularly useful for dynamic routes where the data depends on the URL parameters. -
No Static Generation: Unlike
getStaticProps,getServerSidePropsdoes not generate static HTML at build time. Instead, it fetches data on each request, which makes it suitable for scenarios where the data changes frequently or cannot be pre-rendered.
Example demonstrates how you can use getServerSideProps in a TypeScript Next.js application to fetch data from an API and pass it as props to a page component.
// pages/examplePage.tsx
import { GetServerSideProps, NextPage } from 'next';
interface ExampleData {
message: string;
}
interface ExamplePageProps {
data: ExampleData;
}
const ExamplePage: NextPage<ExamplePageProps> = ({ data }) => {
return (
<div>
<h1>Example Page</h1>
<p>{data.message}</p>
</div>
);
};
export const getServerSideProps: GetServerSideProps<ExamplePageProps> = async () => {
// Fetching data from an API endpoint
const response = await fetch('https://api.example.com/data');
const data: ExampleData = await response.json();
// Pass fetched data as props to the page component
return {
props: {
data,
},
};
};
export default ExamplePage;
Explanation:
- We import
GetServerSidePropsandNextPagefrom Next.js.GetServerSidePropsis a type for defining server-side props fetching function, andNextPageis a type for defining a Next.js page component. - We define two TypeScript interfaces:
ExampleDatarepresents the structure of the data we expect to receive from the API, andExamplePagePropsrepresents the props that our page component will receive. - Our page component,
ExamplePage, accepts props of typeExamplePagePropsand renders thedata.messagevalue. - We define the
getServerSidePropsfunction. It must be exported from the page and it must return an object with apropskey. This function is executed on the server side and its return value is used to populate props for the page component. - Inside
getServerSideProps, we fetch data from an API endpoint (https://api.example.com/data) usingfetch. We parse the JSON response into our definedExampleDatatype. - We return an object from
getServerSidePropswith apropskey, containing the fetched data. This data will be passed as props to theExamplePagecomponent.