getServerSideProps
getServerSideProps
is a Next.js function that can be used to fetch data and render the contents of a page at request time.
Example
You can use getServerSideProps
by exporting it from a Page Component. The example below shows how you can fetch data from a 3rd party API in getServerSideProps
, and pass the data to the page as props:
When should I use getServerSideProps
?
You should use getServerSideProps
if you need to render a page that relies on personalized user data, or information that can only be known at request time. For example, authorization
headers or a geolocation.
If you do not need to fetch the data at request time, or would prefer to cache the data and pre-rendered HTML, we recommend using getStaticProps
.
Behavior
getServerSideProps
runs on the server.getServerSideProps
can only be exported from a page.getServerSideProps
returns JSON.- When a user visits a page,
getServerSideProps
will be used to fetch data at request time, and the data is used to render the initial HTML of the page. props
passed to the page component can be viewed on the client as part of the initial HTML. This is to allow the page to be hydrated correctly. Make sure that you don't pass any sensitive information that shouldn't be available on the client inprops
.- When a user visits the page through
next/link
ornext/router
, Next.js sends an API request to the server, which runsgetServerSideProps
. - You do not have to call a Next.js API Route to fetch data when using
getServerSideProps
since the function runs on the server. Instead, you can call a CMS, database, or other third-party APIs directly from insidegetServerSideProps
.
Good to know:
- See
getServerSideProps
API reference for parameters and props that can be used withgetServerSideProps
.- You can use the next-code-elimination tool to verify what Next.js eliminates from the client-side bundle.
Error Handling
If an error is thrown inside getServerSideProps
, it will show the pages/500.js
file. Check out the documentation for 500 page to learn more on how to create it. During development, this file will not be used and the development error overlay will be shown instead.
Edge Cases
Caching with Server-Side Rendering (SSR)
You can use caching headers (Cache-Control
) inside getServerSideProps
to cache dynamic responses. For example, using stale-while-revalidate
.
However, before reaching for cache-control
, we recommend seeing if getStaticProps
with ISR is a better fit for your use case.