DEV Community

loading...

How to add .env and use process.env to your typescript project

francis04j profile image Francis Adediran ・1 min read

I recently came across this problem in my project and the usual google search/Stackoverflow readings lead to partial and confusing solutions.
So i’m going to document my solution, hopefully someone finds it useful.

First install dotenv package

npm install dotenv;
 OR 
yarn add dotenv;

Import to the entry point of your code. This is usually your index.ts, main.ts or app.ts

import * as dotenv from 'dotenv';

//inside your starter code, do this
...
...
dotenv.config();
...

Now you are ready to use, process.env.ENVIRONMENT_VARIABLE with your project.

However, i will recommend creating a config module to put all your environment variables access. This approach has a lot of benefits such as:

  • ease of code refactoring: a single place to update, change any environment variable key or default value. This is better than doing All-files-search of a variable name.
  • ease of testing: you can mock or intercept this.
  • Clean code: this approach is modular and less typing.

Your config module could look like this. endpoints.config.ts

export default {
 UserBaseUrl: process.env.USER_SERVICE_URL ?? '',
 EtlUrl: process.env.ETL_SERVICE_URL ?? ''
}

Now in your code, you can do something like this

import endpoint from '../endpoints.config';
... 
...
const user = await axios.get(endpoint.UserBaseUrl, { params})
...

That’s it!. Feel free to leave a comment if i missed anything or you are having issues with this.
Thanks

Discussion

pic
Editor guide
Collapse
frankfont profile image
Frank Font

Thanks for sharing! Last year I was looking for something like this and it would have helped!

Collapse
codenamecookie profile image
CodenameCookie

Im getting: npm ERR! code EINVALIDTAGNAME

Collapse
rongem profile image
rongem

Good idea, but doesn't work for me. Fields always stay empty. Making fields to functions workd though.