Pre-rendering and Data Fetching

    Implement getStaticProps

    Pre-rendering in Next.js

    Next.js has two forms of pre-rendering: Static Generation and Server-side Rendering. The difference is in when it generates the HTML for a page.

    • Static Generation is the pre-rendering method that generates the HTML at build time. The pre-rendered HTML is then reused on each request.
    • Server-side Rendering is the pre-rendering method that generates the HTML on each request.

    Importantly, Next.js let's you choose which pre-rendering form to use for each page. You can create a "hybrid" Next.js app by using Static Generation for most pages and using Server-side Rendering for others.

    Using Static Generation (getStaticProps())

    Now, we need to add an import for getSortedPostsData and call it inside getStaticProps in pages/index.js.

    Open pages/index.js in your editor and add the following code above the exported Home component:

    import { getSortedPostsData } from '../lib/posts';
    
    export async function getStaticProps() {
      const allPostsData = getSortedPostsData();
      return {
        props: {
          allPostsData,
        },
      };
    }
    

    By returning allPostsData inside the props object in getStaticProps, the blog posts will be passed to the Home component as a prop. Now you can access the blog posts like so:

    export default function Home ({ allPostsData }) { ... }
    

    To display the blog posts, let's update the Home component to add another <section> tag with the data below the section with your self introduction. Don't forget to also change the props from () to ({ allPostsData }):

    export default function Home({ allPostsData }) {
      return (
        <Layout home>
          {/* Keep the existing code here */}
    
          {/* Add this <section> tag below the existing <section> tag */}
          <section className={`${utilStyles.headingMd} ${utilStyles.padding1px}`}>
            <h2 className={utilStyles.headingLg}>Blog</h2>
            <ul className={utilStyles.list}>
              {allPostsData.map(({ id, date, title }) => (
                <li className={utilStyles.listItem} key={id}>
                  {title}
                  <br />
                  {id}
                  <br />
                  {date}
                </li>
              ))}
            </ul>
          </section>
        </Layout>
      );
    }
    

    You should now see the blog data if you access http://localhost:3000.

    Congratulations! We’ve successfully fetched external data (from the file system) and pre-rendered the index page with this data.

    Let’s talk about some tips for using getStaticProps on the next page.