Next.js 9.3 introduced getServerSideProps
. In the getInitialProps
documentation it now says:
If you're using Next.js 9.3 or newer, we recommend that you use
getStaticProps
orgetServerSideProps
instead ofgetInitialProps
.
The thing is: getInitialProps
doesn't just provide props on the server side. It also runs on the client and provides props when a route transitions. After an initial server render, if the route changed, getInitialProps
runs on the client. So, how do the new methods introduced in 9.3 account for this pretty basic use case?
getServerSideProps
getServerSideProps
only runs on server-side and never runs on the browser. If a page usesgetServerSideProps
, then:When you request this page directly,
getServerSideProps
runs at the request time, and this page will be pre-rendered with the returned props.When you request this page on client-side page transitions through next/link (documentation) or next/router (documentation), Next.js sends an API request to the server, which runs
getServerSideProps
. It’ll return JSON that contains the result of running getServerSideProps, and the JSON will be used to render the page.All this work will be handled automatically by Next.js, so you don’t need to do anything extra as long as you have
getServerSideProps
defined.
For more info.
getStaticProps
Only runs at build time
When a page with getStaticProps is pre-rendered at build time, in addition to the page HTML file, Next.js generates a JSON file holding the result of running getStaticProps.
This JSON file will be used in client-side routing through next/link (documentation) or next/router (documentation). When you navigate to a page that’s pre-rendered using getStaticProps, Next.js fetches this JSON file (pre-computed at build time) and uses it as the props for the page component. This means that client-side page transitions will not call getStaticProps as only the exported JSON is used.
For more info
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With