Next.js: Reading and Display Data from a Local JSON File

Last updated on May 21, 2022 A Goodman Loading... Post a comment

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 kindacode-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>KindaCode.com</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
  }
}

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.

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).

If you’d like to explore more new and interesting things about Next.js and modern React development, take a look at the following articles:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles