0

I want to serve static file in my Next.js app and it is throwing me an error each time it wants to use import fs from 'fs';

I'm supposed not obligated to yarn add fs in order to use fs, why is it giving me this?

My next.config.js is pretty much empty:


const nextTranslate = require('next-translate');

module.exports = {
  ...nextTranslate(),
};

My current dynamic post page is:

/** @format */
import fs from 'fs';

export default function Doc() {
  return <div>Enter</div>;
}

export const getStaticPaths = async () => {
  return {
    paths: [],
    fallback: false,
  };
};

Still I get this error:

enter image description here

I even tried to start a new project and it fails too once I try to use fs. Does it needs to be installed globally in my computer? I have node (v14.15.1) installed for sure.

2
  • It seems your code is executed on the Frontend? Does this help stackoverflow.com/questions/50830572/… ?
    – Dario
    Jan 22, 2021 at 14:27
  • You can't use NodeJS modules like fs from the browser. JavaScript running in the browser isn't allowed to access the filesystem, for obvious security reasons.
    – Thomas
    Jan 22, 2021 at 14:27

1 Answer 1

2

fs is a module that is built into Node.js and depends on Node.js APIs.

It cannot run in a browser. So it cannot run in a typical React component.

You can use it in a server-side only module in Next.js but if you want to use it in a component then you'll probably need to replace it with an HTTP module like Axios and write a server-side endpoint to request your data from.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.