title: process.env variables give me undefined in node/typescript
body: <p>My folder structure is like this:</p>
  
  <p>backend/src/index.ts</p>
  
  <p>backend/.env</p>
  
  <p>backend/environment.d.ts</p>
  
  <p>the 3 files have the following contents:</p>
  
  <pre><code>//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 =&gt; {
    set('useCreateIndex', true);
    set('useFindAndModify', false);
    connect(key, {useNewUrlParser: true, useUnifiedTopology: true})
      .then(() =&gt; console.log('MongoDB connected!'))
      .catch((err: Error) =&gt; console.log(err));
  };
  
  console.log(MONGO_KEY);
  if (MONGO_KEY) {
    initDB(MONGO_KEY);
  }
  
  app.listen(PORT, HOST, () =&gt;
    console.log(`App running at http://${HOST}:${PORT}`)
  );
  </code></pre>
  
  <hr>
  
  <pre><code>//.env
  MONGO_KEY="some_string"
  </code></pre>
  
  <hr>
  
  <pre><code>// environments.d.ts
  declare global {
    namespace NodeJS {
      interface ProcessEnv {
        MONGO_KEY: string;
      }
    }
  }
  
  export {};
  </code></pre>
  
  <p>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. </p>
  
  <p>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.</p>
  
  <p>EDIT:
  changing </p>
  
  <pre><code>config({path: __dirname + '../.env'});
  </code></pre>
  
  <p>to</p>
  
  <pre><code>config();
  </code></pre>
  
  <p>seemed to solve my problem. however, I changed it to that because it stopped working in the first place, so it's still weird.</p>
  
  <p>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.</p>