Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot find module 'fs/promises' even when I use the fs code only inside "getStaticProps()" - next js

So, I use latest version of next js ^11.1.2. According to the documentation, using server side (node js) codes inside getStaticProps() function is fine as it removes the 'fs' import from the client side build.

But in my case its not working.

The following code is what I did...

    import fs from "fs/promises";
    import path from "path";
    
    function HomePage(props) {
      return (
        <ul>
          {props.products.map((el) => (
            <li key={el.id}>{el.title}</li>
          ))}
        </ul>
      );
    }
    
    export async function getStaticProps() {
      try {
        let data = await fs.readFileSync(
          path.join(process.cwd(), "data", "dummy-backend.json")
        );
        console.log(data);
        data = JSON.parse(data);
        return {
          props: {
            products: data.products,
          },
        };
      } catch (err) {
        console.log(err);
        return {
          props: {
            products: [],
            error: "Error in fetching data",
          },
        };
      }
    }
    
    export default HomePage;

Picture of the error displayed in the terminal

And I'm in the development environment.

like image 291
Dikshitkumar Avatar asked Dec 14 '25 09:12

Dikshitkumar


1 Answers

Use

import { promises as fs } from 'fs';

Instead of

import fs from "fs/promises";

and change fs.readFileSync to fs.readFile.

like image 194
Efe Celik Avatar answered Dec 16 '25 00:12

Efe Celik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!