4️⃣

4.4 Route Handlers and Data Fetching

Prerendering

Before data-fetching, we must understand another fundamental concept: pre-rendering. Each page in Next.js is pre-rendered, meaning the html is generated beforehand. Next.js uses a process called hydration, where during the initial page load, Next.js sends down pre-rendered HTML along with the necessary JavaScript bundle specific to that page. Once the page is loaded, the javascript is executed and makes the page interactive–the act of hydration.
Next.js supports two types of pre-rendering:
  1. Static Generation (SSG):
      • HTML pages are generated at build time.
      • During the build process, all pages specified in the pages directory are pre rendered with an HTML file for each page.
      • The HTML files are then served by a CDN or web server
      • Suitable for content that doesn't need to be updated often or relies on data fetched at build time.
  1. Server-side Rendering (SSR):
      • Pre-renders pages on each request made by a user.
      • When a page is visited, the server executes the page code and generates the HTML dynamically.
      • Useful for pages that need up-to-date data or dynamic content not generated at build time.
We can choose which pre-rendering method to use for each page using route handlers to fetch data like getStaticProps (for Static Generation) or getServerSideProps (for Server-side Rendering). Most pages tend to use static generation, as it is much faster than rendering the page at every request, except when page content must change with every request such as a world clock. Pages that do not require external data are automatically rendered statically.

Static and Dynamic Generation

To specify static generation while importing data from an external source, export an asynchronous function called getStaticProps. This will run at build-time and we can then retrieve external data to send to the page:
notion image
To specify dynamic generation, export an async function named getServerSideProps from the page file:
notion image

Client-side Rendering

Finally, to prevent pre-rendering, we can use client-side rendering. This pre-renders the parts of the page for which external data is required, then external data is retrieved and added while the page loads. This can be done by defining an initiate state, setting up an event handler/ function to trigger the rendering, then using the useState hook to manage the state of the component. As covered in the React JS chapter, this can be done as follows:
notion image

Dynamic URLs

In addition to generating page content dependent on external data, we can also generate page paths dependent on external data. This is known as using dynamic URLs. We can statically generate pages with the following method:
  • We start by creating a dynamic [id].js file as in part 1.
  • Inside the dynamic page component file, export an async function named getStaticPaths to generate the paths for the dynamic routes at build time:
notion image
• In the same file, export another async function named getStaticProps. This function fetches the necessary data for each dynamic route:
notion image
• In the page component, access the retrieved data via props:
notion image
  • With this setup, Next.js will generate static HTML pages for each dynamic route specified in getStaticPaths. It’ll fetch the necessary data for each route during build-time using getStaticProps, which will then be passed as props to the page component, enabling pre-rendering of dynamic pages.
  • We can customize the paths array generated in getStaticPaths to include specific dynamic parameters based on the data source.
  • The fallback property can be set to false, true, ‘blocking’
    • Set it to false if the dynamic routes to be rendered are predefined, as this will result in a 404 error for paths not returned by getStaticPaths
    • Set it to true when new routes are frequently added, as this will result in a ‘fallback’ version of the page being created on the first request so that paths not generated at build time to send to the page
Set it to ‘blocking’ to fully render the page before delivering it to the client, as new paths will be server-side rendered and cached for future requests

Previous Section

Next Section

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.