Create an online IDE with Angular 6 + NodeJS ~ Part #2
Configure Environment Variables
Node apps, like most, work with multiple environments, that can be accessed through proccess.env.NODE_ENV
value.The common environments are âdevelopmentâ, âtestingâ and âproductionâ (the aliases are âdevâ, âtestâ, âprodâ).To clarify, NODE_ENV
value (the current environment) configured by an âentityâ from outside the appâs borders (E.g. the developer manually, or some NPM script).
Using the above, we can easily define different behavior in different environments, a little example (only to simplify the concept of different behaviorââânot a real-life example)Â :
const curEnv =proccess.env.NODE_ENV; let dbUri; if (curEnv == 'prod') { dbUri = '
prod.example-db.com';// database for production
test.example-db.com';} else if (curEnv == 'test') { dbUri = '// database for testing
} else { dbUri = '
dev.example-db.com';// database for
development}db.connect(dbUri); //
different db on different environments
What a mass for something as trivial as assigning a value đTry to avoid the approach of assigning a value to environment-depend variables (like dbUri
The strategy commonly used to solve this issue is to store all the environment-depend values in one json file, and in one occasion, assign those values to the global object process.env
 , and with that, all this messy conditional value assignment we used in the example is gone đ.
Now, all the environment-depend values, or values that considered sensitive from a security aspect (E.g. external API credentials, secret keys) will be stored on config.json
file;
here youâll assign all the properties from one of the environments keys (that corresponds to the current environment) on config.json
to process.env
object.
Side-Noteâââyouâre usingrequire(â./config.jsonâ)
and not the typicalimport
statement.Âimport
statement must be called on the top of aÂ.ts
file, before all other definitions, and in this case you must importconfig.json
inside the if block. Way is that ?Âconfig.json
containing sensitive data, and will not be stored on git or the server (youâll deploy to) for this app production, so importingconfig.json
file on production will cause the app to crash, luckily đ the condition on the if statement [lines 14â20] will never be satisfied on production and the code inside it wonât be executed đ.
import config.ts
file on server.ts
 ;
import * as express from "express";import * as bodyParser from "body-parser";import './config/config.ts'; // include the '.ts' extensionimport { appRoutes } from './routes/app.routes';
class ExpressApp { .... ...