Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.8K
Views
TypeError: fs.readFileSync is not a function in Next.js

In a JSON file, I save data for a bot in total.json.

{ "guilds": 3, "users": 21 }

In my index.tsx, I would like to put this data in the page, so I try this:

import fs from 'fs';

function stats() {
  const botcount = JSON.parse(fs.readFileSync(`../util/total.json`, { encoding: 'utf8' }));
  const userscount = botcount.users;

  console.log(userscount);
  return userscount;
}

In the terminal, the function correctly returned the number (21), but in my page, I found this error:

TypeError: fs__WEBPACK_IMPORTED_MODULE_6___default(...).readFileSync is not a function
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can only use fs module in Node js NOT in browser. To access JSON data from a file in Nextjs you can use axios or fetch. Here is an example with axios

import axios from 'axios';

  async function stats() {
    var {data} = await axios.get("http://localhost:8888/utils/total.json");//Change this to your url
    const botcount = JSON.parse(data)
    const userscount = botcount.users;

    console.log(userscount);
    return userscount;
  }
about 4 years ago · Juan Pablo Isaza Report

0

As @JaivBhup already mentioned, you can't use fs since it's not browser compatible.

A better approach IMO is to use a backend and fetch data from there (axios is a great package for this). If you don't have a backend of some kind, you should consider using the Next.js api routes.

You can use it as if you have been using Node.js!

See the docs or this could also be useful for you.

// File: pages/api/my-json.js

import fs from 'fs'
import path from 'path'

export default (req, res) => {
  // Let's say your json is in /public/assets/my-json.json
  const filePath = path.resolve('./public', 'assets', 'my-json.json');
  const json = fs.readFileSync(filePath);

  res.statusCode = 200
  res.json(json);
}

The important part is path.resolve(...), which instructs vercel to include the scanned path in the serverless lambda. The shown code works to read images (or other files from your fs) both locally and remotely on vercel!

I tweaked it a little bit, so it loads the json file instead of filenames.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!