avatarLorenzo Zarantonello

Summary

The provided content outlines a method for reading local JSON data within a Next.js application using getStaticProps and Node.js's fs/promises for static generation, emphasizing the importance of not exposing the JSON file in the public folder.

Abstract

The article discusses a technique for utilizing static JSON files as a simple database substitute to prototype a Next.js application. It explains the security risks of placing a JSON file in the public directory and instead recommends creating a dedicated json folder at the root level of the application. The author provides a step-by-step guide on setting up JSON data, creating a utility function within a lib folder to read and parse the JSON file, and integrating this data into the Home component using getStaticProps. The process involves importing necessary modules from Node.js, reading the file asynchronously, parsing the JSON content, and passing the data to the Home component as props. Additionally, the article hints at future content on writing data to the local JSON file using Next.js API Routes and provides links to related resources and the author's other works.

Opinions

  • The author suggests that using static JSON files can be an efficient way to mock a database for prototyping purposes in Next.js applications.
  • It is implied that exposing a JSON file by placing it in the public folder is not secure and should be avoided.
  • The author emphasizes the utility of getStaticProps for data fetching during the static generation process in Next.js.
  • The article conveys the importance of understanding promise-based file system operations when working with Node.js's fs/promises module.
  • The author expresses the intention to further explore the topic by discussing methods for writing data to a local JSON file in upcoming content.
  • The author encourages readers to subscribe for updates and to engage with their content across various platforms, indicating a commitment to building a community around their technical writing.

NEXT.JS

Read Local JSON Data With Next.js

Read Local JSON Data With Next.js, getStaticProps, And Node.js fs/promises

Static JSON files can be a quick way to mock a simple database and build a prototype of a Next.js app. While the official documentation uses a markdown file, JSON data is more common, and here is how to use it.

Static Generation To Read Local JSON

While we could store a JSON file in the public folder, that would make it visible. Exposing your database is rarely a good idea. So we create a new folder at the root level, and we call it json.

Set Up JSON Data

Inside the JSON folder, create a file called data.json in which we can copy-paste some JSON data. I took the following JSON example from ietf.org.

{ "store": {
    "book": [
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      },
      { "category": "fiction",
        "author": "Herman Melville",
        "title": "Moby Dick",
        "isbn": "0-553-21311-3",
        "price": 8.99
      },
      { "category": "fiction",
        "author": "J. R. R. Tolkien",
        "title": "The Lord of the Rings",
        "isbn": "0-395-19395-8",
        "price": 22.99
      }
    ],
    "bicycle": {
      "color": "red",
      "price": 19.95
    }
  }
}

Read JSON Data

Create another folder at the root level of the application and call it lib. Inside the lib folder create a file and name it localdata.js.

In localdata.js we are going to create a utility function to read data from the JSON file. Here is localdata.js:

// lib/localdata.js

import fsPromises from 'fs/promises';
import path from 'path'

export async function getLocalData() {
  // Get the path of the json file
  const filePath = path.join(process.cwd(), 'json/data.json');
  // Read the json file
  const jsonData = await fsPromises.readFile(filePath);
  // Parse data as json
  const objectData = JSON.parse(jsonData);

  return objectData
}

In short, getLocalData retrieves data from the JSON file using the Node.js fs/promises. If you want to understand what this code does, read the following steps.

Import from Node.js fs

import fsPromises from 'fs/promises';
import path from 'path'

First, we import fsPromises and path from the Node.js fs module.

The Node.js fs module allows access to file system operations, like reading and writing on a file on your system. These operations are asynchronous by default, therefore we have to think and handle them like promises.

Getting Data From Local JSON

export async function getLocalData() {
  // Get the path of the json file
  const filePath = path.join(process.cwd(), 'json/data.json');
  // Read the json file
  const jsonData = await fsPromises.readFile(filePath);
  // Parse data as json
  const objectData = JSON.parse(jsonData);

  return objectData
}

Since the fsPromises module provides promise-based file system operations, we need to use an async function that we call getLocalData.

The first line in getLocalData constructs the file path to the JSON file using path.join. In this way, we join the current working directory (process.cwd()) with the relative path 'json/data.json' to the JSON file we created earlier.

The second line uses the fsPromises.readFile method to read the contents of the JSON file. Since this is an async operation, the method returns a promise that resolves to the file data. We store the result in the jsonData variable.

We then use the JSON.parse function to parse the data as JSON.

Finally, the function returns the parsed object data.

In short, now we have an async function called getLocalData that reads and parses the JSON file returning JSON data.

Display Data In Home — index.js

Now, we can display data in the Home component (index.js) by using the async getStaticProps function that is used in index.js.

Rememeber that getStaticProps() is used for data fetching during the static generation process and is asynchronous.

// pages/index.js

import Head from 'next/head';
import styles from '../styles/Home.module.css';
import getLocalData from './lib/localdata';

export async function getStaticProps() {
  const localData = await getLocalData();
  // log in terminal bacause getStaticProps is executed server-side
  console.log(localData); 
  return {
    props: { localData },
  };
}

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

Inside getStaticProps(), we call the getLocalData function, that we imported above.

The fetched data is assigned to the localData variable.

Finally, we pass localData as props to the Home component that uses this function.

This piece of code makes our JSON data available in Home, using destructuring to extract the localData property from the object:

// pages/index.js

...
export async function getStaticProps() { ... }
export default function Home({ localData }) { 
  ...
} 

Within Home we can access and use the localData prop just like any other variable. So we add:

// pages/index.js

...
export async function getStaticProps() { ... }

export default function Home({ localData }) { 
  return (
   ...

        <ul>
          {localData.store.book.map(({ id, author, title }) => (
            <li key={id}>
              <b>
                {author} - {title}
              </b>
            </li>
          ))}
        </ul>
   ...   
  );
}

And we get to something like:

Show JSON data on Next.js

You can find the code on StackBlitz while I am working on the next post about writing data on the local JSON file.

Here is another way to read and write data on a JSON file in Next.js.

Since getStaticProps is executed during the build process, any changes made to the data.json file will only be reflected when you rebuild your app, which is not what you want in production.

One way to write data on a local JSON file is by using API Routes.

More content at PlainEnglish.io.

Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

React
Nextjs
JavaScript
Json
Front End Development
Recommended from ReadMedium