Next.js Server Side Rendering and getInitialProps
February 02, 2020
We take a look at the power of Next.js and how it handles fetching data using getInitialProps. We also cover some of the gotchas when working with server side rendering since the code runs on both the Node server as well as the Client/Browser.
Key Takeaways From The Video:
4:35 - Pages without the getInitialProps function will be considered by Next.js as a Static Page. If all of your pages are static, you can essentially use it as a static site generator.
5:34 - Code in Next.js will be run both on the server side as well as the client/browser side. Trying to use something like window.location will fail on the server side because the window object only exists on the client side.
8:33 - In order to fetch data using getInitialProps, we need to use the 'isomorphic-unfetch' package because that will work on both server and client.
10:05 - When using getInitialProps, the object that is returned will end up as props in the React component. The props will also include the url object.
11:33 - When visiting a page in Next.js directly, it will fire getInitialProps on the server and the data will be fetched on the server. If, however, you route to the page using the component, the data will be fetched in the browser.
13:14 - The fetched data from getInitialProps will show in when you view the web page's source code. This is the main reason to use the Server Side Rendering powers of Next.js
16:00 - When building the site, Next.js will automatically determine if a page should be static or server side rendered. If you have any pages with SSR, then you'll need to deploy a Node server in order to host the site.
19:54 - You don't have to use SSR. If you don't need the getInitialProps function and want data, you can use traditional data fetching methods like useEffect or fetch on componentDidMount.
If you like the YouTube content, please support it by subscribing to the channel!