The Best Way To Fetch Data in Next.js

Remote Upskill
6 min readJul 25, 2022
Photo by Hunter Harritt on Unsplash

Please note that Next.js version 13 has been released but if you haven’t updated to this latest version i.e. you are still using version 12 or lower, then the details below on fetching data still applies.

You can find more information about Next.js latest release here:

If you want to brush up on your Math fundamentals, we’ve just published a book on Gumroad, which you can find here:

If you are thinking of switching to a career in tech or changing to a new tech job, here are some job sites you can get started with:

Photo by Mukuko Studio on Unsplash

Do something today!

This lesson aims to provide you with a brief introduction on data fetching with Next.js.

First, let’s look at what you will get from this tutorial:

  • Understand the difference between Server-side rendering (aka SSR) v.s. Client-side rendering (aka CSR)
  • how to fetch data with getServerSideProps (for Server-side rendering)
  • how to fetch data with getStaticProps (for Static-site generation aka SSG)
  • How to fetch data after Next.js has served your website to the browser

Note: You need Node.js installed on your local machine. You can find out how to install Node.js and Next.js on your local machine by reading this lesson here.

What is Server-side rendering?

This is basically when data is fetched and loaded into your HTML before you serve the HTML as a webpage to the user’s browser.

There are two ways to do server-side rendering in Next.js:

  • getStaticProps (used with getStaticPaths)
  • getServerSideProps

Note: Only use “getStaticProps” and “getServerSideProps” in Pages and not in your components. If you are confused about Pages and Components — then think of it like this — Pages are the complete webpages you see on a Next.js website and components are the small building blocks that make up a single webpage.

We will first look at how to use getServerSideProps to fetch and load data into our Next.js pages. And then from Pages we load the data into the React components.

If you need help with handling loading between page changes in Next.js, here is a short guide for you:

For example, if you wanted to load some data into your React components on your Homepage with Next.js, your code would probably look something like this:

import React, { useEffect, useState } from 'react';
import Head from "next/head"
const Homepage = ({ preRenderedData }) => {const [dataInsideTheComponent, setComponentData] = useState([]); useEffect(() => { if(preRenderedData) { setComponentData(preRenderedData) } }, []); return (
<>
<Head>
<title>{`My Homepage`}</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<div>
{dataInsideTheComponent ? dataInsideTheComponent : ''}
</div>
</>
)
};
export async function getServerSideProps() {

let dataFromSomeAPI = await fetch(`https://api.somdata.com/v1`)

return {props: {preRenderedData: dataFromSomeAPI}}
}

What is happening in the code above?

Note: You can use Pages in your Next.js application to fetch different data for different pages based on different routing logic. For example, we could use “www.example.com/user” to fetch the user data and display it.

On the Homepage, we first use getServerSideProps to make an API call to our API or some other 3rd party API to fetch the initial data needed for our website when it first loads in the user’s browser.

Tip: as an optimisation, you can use “getStaticProps” instead of “getServerSideProps” on the Homepage. Getting data with getStaticProps is faster than getting data with getServerSideProps.

Note: it is important to understand the difference between initial data and user request data. The former is data fetched when your website first loads in a browser and is not dependent on any user’s requests or you can think of it like — the data will be the same for the webpage regardless of what the user’s interaction is on the website. The latter, however, is dependent on a user’s request so the data is fetched at request time.

We use the “await” keyword to make sure that we wait for the data to come back before passing it into our Homepage component as props.

let dataFromSomeAPI = await fetch(`https://api.somdata.com/v1`)

We then use Javascript’s destructuring to access to the data inside the props object, like so:

({ preRenderedData })

We then use ‘useEffect’ to check if the data is available or not and if it is then we use the props data to set the data in our Homepage component.

setComponentData(preRenderedData)

Lastly, we use conditional rendering to check when the data becomes available in the component.

<div>
{dataInsideTheComponent ? dataInsideTheComponent : ''}
</div>

So what is the difference between getStaticProps and getServerSideProps?

As a rule of thumb:

  • use getStaticProps for the initial data you render onto your webpage when the user first opens up your website in their browser. This is the initial data — which is not affected by the users’ actions on your website.
  • use getServerSideProps for data that is dependent on the actions made by the user on your website. For example, when a user clicks on an image on your homepage, you will take the user to a new page and load the data specifically related to that image for the user.

So how can we fetch data from the client side (i.e. after the page has already been loaded in the user’s browser)?

The short answer is — we can simply fetch data from inside a React component using a handler function.

I am going to show you how with as little code as possible.

For example, if we wanted to fetch a course associated with a courseId, we could create a button like this in our React component.

<div                                                         
key={`some-unique-key`}
className={`${styles.buttons}`}
onClick={(e) => viewCourse(e, courseId)}
>
View Course
</div>

What is happening in the code?

key={`some-unique-key`}
  • We need to give the element a unique key as this is a button rendered in a list of buttons
import styles from './Course.module.css';className={`${styles.buttons}`}
  • We then add the styles to the button using CSS modules (supported out of the box in Next.js)
onClick={(e) => viewCourse(e, courseId)}
  • This attaches an event handler to the button so that whenever someone clicks the button, the “viewCourse” function will execute.
import axios from 'axios'const viewCourse = async (e, courseId) => {
const response = await axios.get(`my/database/${courseId}`);
console.log(`log response`, response)
};
  • We then use our courseId to find the related course stored in our database. We make the API call with ‘axios’, a library for managing HTTPS requests and response.

Our other guides on Next.js:

If you are thinking of switching to a career in tech or changing to a new tech job, here are some job sites you can get started with:

Start planning for your new journey today!

If you need help with learning Javascript or your Javascript coding interview, you can reach out to us at team@remoteupskill.com

We publish short tech tutorials on a regular basis so consider subscribing to our Medium Blog.

Until next time — keep coding while moving small steps forward on this coding adventure of yours.

But more importantly, stay focused!

--

--