1

I am creating a node js application as a Contentful UI Extension. The code is hosted here: https://github.com/doodybrains/media-tagging-extension

A lot of the gulp file is boiler plate but in the end everything gets bundled into an index.html file. I know that env variables shouldn't be called or processed in the client code but I don't know how to get them in there before the project is built. When I run the repo in development and call process.env.NAME_OF_TOKEN from src/index.js it returns undefined. I have tried import dotenv, creating a gulp env pipeline etc.

ANY ADVICE will be so helpful. The app is being deployed to Netlify and I already have the env variables set up there as well.

thank you

Manish Balodia
  • 1,863
  • 2
  • 23
  • 37
  • I don't think you can use env inside your src/index.js since it's client side, and gulp cannot precompile that for you, either. Maybe you should import those vars from a json file instead of a dotenv file? – NoobTW Aug 27 '18 at 02:49
  • I like the idea but how do I use the json file without submitting it to source code? – user10277744 Aug 27 '18 at 03:05

1 Answers1

0

You can create another js file which can use NODE_ENV to set correct variable. I prefer calling a service to get all my properties on app start and set in some map. I use the map to set the value in different places in my code.

Some sample code...

const env = process.env.NODE_ENV || 'local';
const sit = {
    URL: 'sit url',
    HOST: 'sit host',
    ENV: 'sit'
};
const uat = {
    URL: 'uat url',
    HOST: 'uat host',
    ENV: 'uat'
};

var property_service_url = config[env].URL;
var property_service_host = config[env].HOST;

Before starting your app, you can set the NODE_ENV=environment. For example in linux.

export NODE_ENV=uat

This will make sure that environment set correctly. Now in your app.js for , you can call the service to load your properties. If you don't want to call a service, you can set it in the same way the URL and HOST are set.

SK -
  • 459
  • 5
  • 15