getting error : TypeError: fs.readFileSync is not a function

1.9k views Asked by At

getting error : TypeError: fs.readFileSync is not a function when i tried to use get value from .env file, can anyone please help me why i am getting this error? here i have uploaded my code, can anyone please help me how to resolve this issue ? any help will be really appreciated.

const dotenv = require('dotenv').config();
const fs = require('fs');
const envConfig = dotenv.parse(fs.readFileSync('.env'))
for (const k in envConfig) {
  process.env[k] = envConfig[k]
}
1

There are 1 answers

0
Necromancer On

Firstly I want to remind that fs will not work in the browser. This is by design as to protect your filesystem from potential security threats.

Did you use create-react-app when you were creating ReactJs project?

If it is the case, the following solution will fix this issue.

In your .env file, you have to append REACT_APP_ to all env variables to make it work.

Don't forget to restart your server after changing it.

For example :

This works -

REACT_APP_MYVAR=yourSecret

This doesn't

MYVAR=yourSecret

You can read the reference link in here. https://create-react-app.dev/docs/adding-custom-environment-variables/