How to access .env file variables in TypeScript using dotenv?

Viewed 3767

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

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.

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

Related