DEV Community

Francis Adediran
Francis Adediran

Posted on

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

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

Top comments (12)

Collapse
 
mick62 profile image
mick62 •

When the app starts up it's crucial to first check whether all config parameters got a value (explicitly from an environment variables or via a default value).
This "fail early" behavior is important e.g. for apps deployed via kubernetes. If there is a problem the app (container/pod) should signal en error to kubernetes on start-up. So the attempt to deploy a new version fails and will be rolled back to the previous version.
Your example code would try to send a request to an empty url getting an inherited error w/o the chance to handle the root cause automatically.

Collapse
 
allindeveloper profile image
Uchendu Precious •

Please can you throw more light on this.. i am experiencing a similar issue. i have a react app deployed to kubernetes that's not reading the env variable

Collapse
 
mick62 profile image
mick62 • • Edited

Our app reads environment variables at start-up like this:

const envVarReader = new EnvVarReader();
export const envVar = {
UserBaseUrl: envVarReader.getURL('USER_SERVICE_URL'),
EtlUrl: envVarReader.getURL('ETL_SERVICE_URL')
}
envVarReader.checkVariables() // will throw an exception in case of errors
// with a message containing descriptions for all found problems

I wrote a small class 'EnvVarReader' which reads from 'process.env', checks and transforms the string values to the expected type. A missing or malformed URL will e.g. result in an exception thrown by 'checkVariables' at start-up.

Project time pressure kept me from making class 'EnvVarReader' available on github until now. But it seems I should take my time to just do that now.

Thread Thread
 
allindeveloper profile image
Uchendu Precious •

Thanks for the clarity

Thread Thread
 
growthfirst profile image
growthfirst •

mick62
Can you share with us how you built envVarReader ?

Collapse
 
frankfont profile image
Frank Font •

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

Collapse
 
rongem profile image
rongem •

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

Collapse
 
mohamednashad profile image
NSD •

You have a get method here, how can we add a create method
like this
export const API = axios.create({ baseURL: baseUrl });

Collapse
 
asadsaleh profile image
AsadSaleh •

Thank you, you helped me

Collapse
 
codenamecookie profile image
CodenameCookie •

Im getting: npm ERR! code EINVALIDTAGNAME

Collapse
 
mehtabahmed176 profile image
Mehtab Ahmed •

Thank you so so much, "google search/Stackoverflow readings lead to partial and confusing solutions" the same happened to me.

Collapse
 
ruberoni profile image
Ruben Paredes •

For the people still with problems configuring dotenv, in its official repository is a guide just for typescript:
github.com/motdotla/dotenv/tree/ma...