jonchaf
jonchaf

Reputation: 166

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

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.

Upvotes: 2

Views: 6997

Answers (2)

Farhad Azarbarzinniaz
Farhad Azarbarzinniaz

Reputation: 739

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

Upvotes: 0

jonchaf
jonchaf

Reputation: 166

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.

Upvotes: 1

Related Questions