This short and straight-to-the-point article shows you how to read and display data from a local JSON file in Next.js. This is useful if you want to build a small web app quickly without having to code the backend or spend time setting up and connecting the database.
Dummy Data
Here’s the JSON data that’ll be used in our example. It’s just some mocking blog posts:
{
"posts": [
{
"id": 1,
"title": "Post 1",
"content": "This is the full content of post 1"
},
{
"id": 2,
"title": "Post 2",
"content": "This is the full content of post 2"
},
{
"id": 3,
"title": "Post 3",
"content": "This is the full content of post 3"
},
{
"id": 4,
"title": "Post 4",
"content": "This is the full content of post 4"
}
]
}
Writing Code
1. Initialize a new Next.js project:
npx create-next-app example
You can choose whatever name you want.
2. In the root directory of your project (at the same level as package.json and next.config.js), create a new file named data.json. Copy the dummy data you’ve seen in the preceding section and paste it into your data.json. Here’s mine:
3. To read data from the JSON file, we’ll use the getStaticProps() function and the fs Promises API (this is a built-in feature of Node.js so that you don’t have to install any third-party packages).
Remove all of the default code in pages/index.js, then add the following:
// pages/index.js
import Head from 'next/head'
export default function Home(props) {
const posts = props.posts;
return (
<div style={{ padding: 30 }}>
<Head>
<title>Sling Academy</title>
</Head>
<div>
{posts.map(post =>
<div
key={post.id}
style={{ padding: 20, borderBottom: '1px solid #ccc' }}>
<h2>{post.title}</h2>
<p>{post.content}</p>
</div>)}
</div>
</div>
)
}
// Fetching data from the JSON file
import fsPromises from 'fs/promises';
import path from 'path'
export async function getStaticProps() {
const filePath = path.join(process.cwd(), 'data.json');
const jsonData = await fsPromises.readFile(filePath);
const objectData = JSON.parse(jsonData);
return {
props: objectData
}
}
Note that you should only import fsPromises and path right before the function getStaticProps(). Otherwise, you are very likely to encounter an unwanted outcome.
4. Get your Next.js app up and running with the command below:
npm run dev
Finally, open a web browser and go to http://localhost:3000. You should see something like this:
That’s it.
Practice More: Download and try to render data from a large JSON file at https://api.slingacademy.com/v1/sample-data/files/employees.json. This file contains information about employees in a fiction software company.
Conclusion
You’ve learned how to fetch and render data from a JSON file in Next.js. This can help you quickly develop and deploy small websites with little effort (however, if you want to build a large project, then you will need a real backend and set up a real database like PostgreSQL, MySQL, MongoDB, etc.).