简体   繁体   中英

process.env variables give me undefined in node/typescript

My folder structure is like this:

backend/src/index.ts

backend/.env

backend/environment.d.ts

the 3 files have the following contents:

//index.ts
import express, {Application} from 'express';
import {config} from 'dotenv';
import {set, connect} from 'mongoose';

config({path: __dirname + '../.env'});

const MONGO_KEY = process.env.MONGO_KEY;
const PORT = 5000;
const HOST = 'localhost';

const app: Application = express();

const initDB = (key: string): void => {
  set('useCreateIndex', true);
  set('useFindAndModify', false);
  connect(key, {useNewUrlParser: true, useUnifiedTopology: true})
    .then(() => console.log('MongoDB connected!'))
    .catch((err: Error) => console.log(err));
};

console.log(MONGO_KEY);
if (MONGO_KEY) {
  initDB(MONGO_KEY);
}

app.listen(PORT, HOST, () =>
  console.log(`App running at http://${HOST}:${PORT}`)
);

//.env
MONGO_KEY="some_string"

// environments.d.ts
declare global {
  namespace NodeJS {
    interface ProcessEnv {
      MONGO_KEY: string;
    }
  }
}

export {};

The console.log of MONGO_KEY gives me undefined. I tried most of the solutions I found here and nothing worked so far. I have @types/node installed.

A second problem is the if check (I want to get rid of that). In the environment.d.ts file, I said that MONGO_KEY is a string, but ts thinks it's a string or undefined. I feel like I have to import the file somewhere.

EDIT: changing

config({path: __dirname + '../.env'});

to

config();

seemed to solve my problem. however, I changed it to that because it stopped working in the first place, so it's still weird.

EDIT 2: In case someone faces the same problem: I had routes imported from other files that had process.env variables in them and the dotenv.config() import was placed below those routes, so of course those variables were undefined.

If your js file is /home/alex/foo.js , then your __dirname is /home/alex .

This means that:

config({path: __dirname + '../.env'});

will become:

config({path: '/home/alex../.env'});

My general advice is: don't concatenate paths manually, use path.join() for consistent cross-platform behavior that adds/removes the exact correct amount of slashes.

use this command in your scripts: node -r dotenv/config your_main-file_name.js

for more details check out: https://www.npmjs.com/package/dotenv

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM