Nextjs data fetching: getStaticProps

Nextjs data fetching: getStaticProps

Next.js includes a number of methods for fetching data from an API or other service. Such techniques may be employed for either server-side rendering or for making static pages. Next.js's data fetching methods include the getStaticProps, getStaticPaths, and getServerSideProps methods. By making use of these methods, we can create SEO friendly sites with Next.js.

SPAs or single page apps are the modern kind of websites! In a nutshell they work by calling an API repeatedly and inserting fetched data dynamically on the page. This is a good approach but if you want to your webiste to be discovered by search engines you need to go back to the old approach which is server-side rendering but with new techniques and tools. Next.js includes all the required tools to create modern websites server-rendered or statically generated to take benefits of both the old and modern eras.

Next.js offers multiple options for retrieving or fetching data, which can be used to make API calls or access data from other sources, and can then be rendered in a variety of ways.

We primarily use the two functions below in Next.js to retrieve data:

  • For static generation, the getStaticProps method is called upon to fetch data during the static generation process.
  • To aid in pre-rendering dynamic routes, getStaticPaths is used in addition to getStaticProps.
  • Data is fetched on every request using getServerSideProps (for server-side rendering).
  • getInitialProps can also used to fetch data but it's not recommended in newer versions of Next.js.

Creating a Next.js project

Let's get started by creating a new Next.js project using the create-next-app tool.

Open a new command-line interface and run the following command:

npx create-next-app nextjsdemo

Next, you can run the following commands to start the development server:

cd nextjsdemo
npm run dev

You server will be running at http://localhost:3000.

Now suppose we need to a create a blog or an information website, which generally need to be SEO-friendly, we'll need to have all remote data data at build time to generate the static pages, with all the required data, that can deployed and discovered by search engines.

Next.js provides the getStaticProps method which allows developers to fetch data at build time when generating your static website:

export async function getStaticProps(context) {
  return {
    props: {}, // will be passed to the page component as props
  }
}

We simply need to write the code for fetching data inside the body of this method and then return the fetched data using the props of the returned object.

Let's use this method to fetch some data at the phase of static page generation. Open the pages/index.js file and start by adding the following import:

import Link from "next/link"

Next, add yje code for fetching some data:

export const getStaticProps = async () => {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts");
  const data = await res.json(); 
  console.log(data);
  return {
    props: { data: data },
  };
};

Please note that the output of the console.log() will be shown when building your site at the terminal not on the browser's console.

The props that we return from the getStaticProps function will be received by the Home component.

Next, let's get the fetched data via the props object and render them:

export default function Home(props) {
  const posts = props.data;
  return (
    <div>
      <h1>Blog: { posts.length } </h1>
      <ol>
        {posts.map((post) => (
          <li key={post.id}>
            <Link
              href={{
                pathname: "/[id]",
                query: { id: post.id },
              }}
            >
              <a>{post.title}</a>
            </Link>
          </li>
        ))}
      </ol>
    </div>
  )
}

Now what if we need to fetch or show a post by its ID? We simply need to way to get the ID in the getStaticProps() method. This is how:

export const getStaticProps = async ({ params }) => {

  const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${params.id}`);
  const data = await res.json(); 
  return {
    props: {
      post,
    },
  };
};

In this case, the post's id can be found in the URL of the current page by looking at the parameter params.

After requesting information from the API, the result is returned to the component as props.


  • Date: