2

I'm trying to use a .env file to store API keys in a TypeScript React project. My .env file is in the root of the project and I'm trying to access its variables from src/index.tsx via process.env.

.env:

FOO=foo

src/index.tsx:

import * as dotenv from "dotenv";

console.log(dotenv.config()); // prints TypeError: fs.readFileSync is not a function
console.log(process.env.FOO); // prints undefined

It looks like dotenv.config() throws in an error so I think that's where the problem is. Just not sure how to fix it. I've tried moving .env into the src directory and passing a path into the function, e.g. dotenv.config({ path: `${__dirname}/.env` }) but still getting the same error.

dotenv seems to be the most common way to use environment variables in a Node.js project, but if there are better alternatives I'd be interested in hearing those too.

Any thoughts & ideas would be appreciated.

2 Answers 2

1

Renaming the environment variable to REACT_APP_FOO and restarting react-scripts seems to do the trick. It works without calling dotenv.config(). Not really sure why it works this way so I would be interested to hear someone's insight on this.

Sign up to request clarification or add additional context in comments.

Comments

0

You can access variables by first calling require('dotenv').config() at your project root. then you can use them like process.env.FOO.

You have to consider to call the process.env.FOO

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.