-1

Background: I have 3 different URLs, one per environment (dev, test, prod), and I don't want to expose all the URLs in the client (source code).

How can I expose in the client code, just the one corresponding to the environment in context?

Note: As I understand, I need to do something in the build process using environment variables (I'm using node.js). However, I don't want to touch anything related with webpack, as what I'm trying to do is a standalone package that can be imported in any application regardless of the framework they are using. Webpack plugins/configuration are not an option, but I can use any npm package if required.

  • is this a web application, are you using express? – Zlatan Omerović Jun 14 '17 at 17:27
  • Yes It's a web application and I'm using express, but I think express isn't needed for what I want to do as it's an http server. –  Jun 14 '17 at 17:30
  • express.js has NODE_ENV - which is an environmental variable within the scope of the application. By default installation, it's set for DEBUG, and you can change it to test, production, etc. Read more https://stackoverflow.com/questions/10714315/node-js-express-and-using-development-versus-production-in-app-configure and https://expressjs.com/en/api.html. – Zlatan Omerović Jun 14 '17 at 17:32
  • got your point, but as this is a standalone package i cannot force everyone to use express, so is more related to a conditional config than a conditional express endpoint, developers must be able to use any http server they want like hapi or something. and as I said, this URL is on the client not in the back-end, if was just in the backed there will be not problem at all trying to hide the config –  Jun 14 '17 at 17:36

2 Answers2

0

During your build process, you can check the environment variable and then copy over a config file. For example, you could keep your URIs in /config/<env>.js, and then copy/rename it to /settings.js during the build. Your URL could be exported from that.

TbWill4321
  • 8,626
  • 3
  • 27
  • 25
0

The following npm package fits my requirements completely https://www.npmjs.com/package/config , you can load conditional files based on the node environment variable NODE_ENV, so when NODE_ENV=development, the file /config/development.js is used to create the build. you can use different extensions for the config files, also you can customize the config folder path by changing the environment variable $NODE_CONFIG_DIR heres an example:

const config = require('config');
process.env.$NODE_CONFIG_DIR = './' // relative path ./config

const url = config.get('url'); 
//if NODE_ENV is development will load the file config/development.js

console.log(url);