When you developing your servers, do you have the need to have different values for certain configurations depending on the current environment:
If the answer is YES, and you've never worked with environment variables before - this short tutorial is for you!
Let's assume that you already have a configured server with TypeScript.
Step 1: Add dotenv dependency
Add the dependency to your project
npm install dotenv --save
Step 2: Create env files
We need different configuration variables when configuring our servers. For example, you will need different addresses, ports, and so on for the databases or any other services, you will use.
In this tutorial, we will create two files:
.env.production- containing all the variables for the production configuration
.env.development- containing all of the variables for the development configuration
Let's assume that you're using Amazon's S3 service
Create the following two files:
Step 3: Create a config file
We will extract the loading of the env variables into a separate file:
If you import this config into your app, you will notice that the env variables will not be found in the
process.env. This is because TypeScript doesn't know about them.
Let's create a new file:
If you haven't mentioned the types directory in your TypeScript configuration, you will have to add it in the
tsconfig.json in the typesRoot:
Step 4: Use the env variables in your app
Include the config.ts in your server configuration file:
import config from './config'
And now you can use the env variables by calling:
Step 5: How to start the server in production mode
When you want to use your production configuration, you have to specify the
NODE_ENV when starting the server.
NODE_ENV=production node src/app.js
This is a really small tutorial on how to use env variables for the different environments you want to run your servers.
Happy coding! 👨💻