Sling Academy
Home/Next.js/Next.js: Read and Display Data from a Local JSON File

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

Last updated: February 08, 2023

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

Next Article: Passing data via a Link component in Next.js

Previous Article: Next.js getServerSideProps(): Tutorial & Example

Series: Fetching and Rendering Data in Next.js

Next.js

Related Articles

You May Also Like

  • Solving Next.js Image Component Error with CSS Classes
  • How to Use MUI (Material UI) in Next.js 14
  • Fixing Data Update Issues in Next.js Production
  • Fixing Next.js Undefined ENV Variables in Production Build
  • Solving Next.js SyntaxError: Unexpected token ‘export’
  • Next.js Error: Found Page Without a React Component as Default Export – How to Fix
  • Fixing Next.js Error: Blank Page on Production Build
  • Fixing Next.js Error when Importing SVGs: A Step-by-Step Guide
  • Next.js Issue: useEffect Hook Running Twice in Client
  • Fixing ‘self’ is not defined error in Next.js when importing client-side libraries
  • How to Dockerize a Next.js App for Production
  • How to set up Next.js with Docker Composer and Nginx
  • Solving Next.js CORS Issues: A Comprehensive Guide
  • Fixing Next.js Hydration Mismatch Error in Simple Ways
  • Next.js Error: Cannot use import statement outside a module
  • Next.js: How to Access Files in the Public Folder
  • Fixing Next.js Import CSS Error: A Simple Guide
  • Fixing LocalStorage Not Defined Error in Next.js
  • Fixing Next.js Error: No HTTP Methods Exported