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:

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.






