Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are you supposed to do client-side data fetching on route transition with getServerSideProps?

Tags:

next.js

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 or getServerSideProps instead of getInitialProps.

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?

like image 270
Dmitry Minkovsky Avatar asked Apr 05 '20 15:04

Dmitry Minkovsky


1 Answers

getServerSideProps

getServerSideProps only runs on server-side and never runs on the browser. If a page uses getServerSideProps , 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

like image 130
felixmosh Avatar answered Oct 11 '22 21:10

felixmosh