Part 16: Reading Files in Next.js with getStaticProps

[Pages] Loading Data

[Pages] Loading Data

In our previous exploration of Next.js, we delved into how the getStaticProps function works. Now, we're taking it a step further by learning how to load post data from a file, specifically a JSON file. This post will guide you through the process of reading a file using Node.js capabilities within a Next.js application.

The Task: Loading Data from a JSON File

Our goal is to load post data from a JSON file named first-post.json, which contains details like the title and body of our post. By using a JSON file, we simplify our task and focus solely on reading the file content without diving into parsing Markdown just yet.

Understanding the Environment

Since getStaticProps runs on the server side in a Node.js environment, we have access to Node.js APIs, which are not available in the client-side browser environment. This allows us to utilize the Node.js fs (File System) module to read files.

Step-by-Step Implementation

  1. Create the JSON File

    First, ensure you have a JSON file with the post data. Create a file named first-post.json in the content/posts directory with the following content:

    // content/posts/first-post.json
    {
      "title": "First Post",
      "body": "My first post, in a JSON file."
    }
  2. Reading the File in getStaticProps

    Next, we'll modify our getStaticProps function to read this file:

    // pages/posts/first-post.js
    import { readFile } from 'fs/promises';
    import Head from 'next/head';
    
    export async function getStaticProps() {
      console.log('[FirstPostPage] getStaticProps()');
      const data = await readFile('content/posts/first-post.json', 'utf8');
      const post = JSON.parse(data);
      return {
        props: { post },
      };
    }
    
    function FirstPostPage({ post }) {
      console.log('[FirstPostPage] render:', post);
      return (
        <>
          <Head>
            <title>{`${post.title} - My Blog`}</title>
          </Head>
          <main>
            <h1>{post.title}</h1>
            <p>{post.body}</p>
          </main>
        </>
      );
    }
    
    export default FirstPostPage;

    -Import the readFile Function:** We import readFile from the fs/promises module, which allows us to read files asynchronously using promises.

    • Read the JSON File: We call readFile with the path to our JSON file and specify the encoding as utf8. This function returns the file content as a string.

    • Parse the JSON Content: We use JSON.parse to convert the string into a JavaScript object.

    • Return the Parsed Data: We return the parsed post data as props to our component.

  3. Verify the Output

    When you run your app and navigate to the post page, the server logs will display the data being read from the file, and the page will render the post title and body as defined in first-post.json.

Conclusion

By leveraging Node.js's file system module within the getStaticProps function, we can read local files on the server side. This approach opens up many possibilities for loading and managing content in a Next.js application, providing a flexible way to handle data at build time. As we continue our journey, we'll explore how to parse Markdown and integrate more complex data sources. For now, mastering file reading in Node.js gives us a solid foundation for dynamic content management.

Last updated