Giter VIP home page Giter VIP logo

ember-cli-dotenv's Introduction

main branch build npm version Ember Observer Score

ember-cli-dotenv

Compatibility

  • Ember.js v4.8 or above
  • Ember CLI v4.8 or above
  • Node.js v18 or above

Installation

ember install ember-cli-dotenv

Upgrading to 2.0.0

  • ember install ember-cli-dotenv@^2.0.0
  • open config/dotenv.js and ember-cli-build.js
  • Move/convert the dotEnv application options from ember-cli-build.js to the function declared within config/dotenv.js

Embroider Compatibility

This was addon was designed to work with classic Ember CLI build pipeline and approach used here simply does not work under Embroider.

For Ember apps using Embroider, it's recommended to use @embroider/macros to pass Node.js environment variable(s) to Ember code. In ember-cli-build.js, do:

require('dotenv').config();

let app = new EmberApp(defaults, {
  '@embroider/macros': {
    // this is how you configure your own package
    setOwnConfig: {
      DROPBOX_KEY: process.env.DROPBOX_KEY
    },
    // this is how you can optionally send configuration into your
    // dependencies, if those dependencies choose to use
    // @embroider/macros configs.
    setConfig: {
      'some-dependency': {
        DROPBOX_KEY: process.env.DROPBOX_KEY
      },
    },
  },
});

In case if you need to consume env variable(s) only in FastBoot mode and ensure they don't get transferred to browser in config/fastboot.js, do:

require('dotenv').config();

module.exports = function(environment) {
  const myGlobal = {
    DROPBOX_KEY: process.env.DROPBOX_KEY,
  };

  return {
    buildSandboxGlobals(defaultGlobals) {
      return Object.assign({}, defaultGlobals, {
        myGlobal,
      });
    },
  };
}

What is Ember CLI Dotenv?

This addon allows you to write environment variables in a .env file and expose them to your Ember app through the built-in config/environment.js that you can import in your app. For example, you might be building an app with Dropbox and don’t want to check your key into the repo. Put a .env file in the root of your repository:

DROPBOX_KEY=YOURKEYGOESHERE

Next, configure config/dotenv.js.

// config/dotenv.js
module.exports = function(env) {
  return {
    clientAllowedKeys: ['DROPBOX_KEY'],
    // Fail build when there is missing any of clientAllowedKeys environment variables.
    // By default false.
    failOnMissingKey: false
  };
};

All keys in .env are currently injected into node’s process.env. These will be available in your config/environment.js file:

// config/environment.js
module.exports = function(environment) {
  return {
    MY_OTHER_KEY: process.env.MY_OTHER_KEY
  };
};

You can then use the node process environment variables in other ember-cli-addons, such as express middleware or other servers/tasks.

Security: environment variables in config/environment.js are never filtered unlike using .env and clientAllowedKeys. Remember to use the environment variable passed into your config function to filter out secrets for production usage. Never include sensitive variables in clientAllowedKeys, as these will be exposed publicly via Ember's <meta name="app/config/environment"> tag.

Then, you can access the environment variables anywhere in your app like you usually would.

import ENV from "my-app/config/environment";

console.log(ENV.DROPBOX_KEY); // logs YOURKEYGOESHERE

You can read more about dotenv files on their dotenv repository.

All the work is done by ember-cli and dotenv. Thanks ember-cli team and dotenv authors and maintainers! Thanks Brandon Keepers for the original dotenv ruby implementation.

FastBoot support

This addon supports FastBoot via fastbootConfigTree build hook (requires ember-cli-fastboot 1.1.0 or higher). Use fastbootAllowedKeys configuration option to make variables available in FastBoot mode when Ember application is rendered server-side.

// ember-cli-build.js

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    dotEnv: {
      clientAllowedKeys: ['DROPBOX_KEY'],
      fastbootAllowedKeys: ['MY_API_SECRET', 'MY_OTHER_API_SECRET']
    }
  });

  return app.toTree();
};

Note: keys listed in fastbootAllowedKeys are not added to Ember's <meta name="app/config/environment"> tag and are not available to Ember application when it runs in browser.

Multiple Environments

Sometimes people may want to use different .env file than the one in project root. This can be configured as below:

// config/dotenv.js
module.exports = function(env) {
  return {
    clientAllowedKeys: ['DROPBOX_KEY'],
    path: './path/to/.env'
  };
};

In addition, you may also customize for different environments:

// config/dotenv.js
module.exports = function(env) {
  return {
    clientAllowedKeys: ['DROPBOX_KEY'],
    path: `./path/to/.env-${env}`
  };
};

With the above, if you run ember build --environment production, the file ./path/to/.env-production will be used instead.

Environment Specific Use

Sometimes people may want to only initiate the dotenv file in one or more environments (e.g. not in production) This can be configured as below:

// config/dotenv.js
module.exports = function(env) {
  return {
    enabled: env !== 'production' // default is TRUE for any environment
  };
};

When enabled is set to false, the dotenv protocol will not be used at all. This is great for quieting errors and side issues when deploying with a service like Heroku, where you can use environment variables set within the service and avoid storing a .env file in your repo.

Compatibility

This addon supports the Ember 2.x series, but it is also backwards-compatible down to Ember-CLI 0.1.2 and Ember 1.7.0.

For FastBoot support you need Ember 2.3 or higher (2.12.0 and higher is prefereable by ember-cli-fastboot) and ember-cli-fastboot 1.1.1 or higher.

Other Resources

Contributing

See the Contributing guide for details.

License

This project is licensed under the MIT License.

ember-cli-dotenv's People

Contributors

artemgurzhii avatar davideferre avatar dependabot[bot] avatar dschmidt avatar elwayman02 avatar fivetanley avatar gfmartinez avatar gniquil avatar ibroadfo avatar jasonmit avatar jeffreybiles avatar kalachevdev avatar matthewlehner avatar ondrejsevcik avatar opsb avatar oxodesign avatar sandydoo avatar sergeastapov avatar wkoffel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ember-cli-dotenv's Issues

Trying to understand the value of this

I'm trying to understand the value of this for ember client side applications. I get that having a .env file helps you to keep from having to include the file in your repo, and is a good place to put secure keys.

However, with a client side application, those keys are exposed in plain text no mater what via the environment meta, and even if that was not how Ember handled it, they would be exposed somewhere in the compiled JS somewhere.

So the purpose is not to protect keys, since there is no way to really protect a key in a client side application (at least as far as I'm understanding right now). Basically, for a client side app, the key needs to be a public key any how.

Am I missing something?

Picking a specific dotenv file via CLI param

Hi!

I find splitting dotenv files by environment to be very restricting. I've seen whole blog posts arguing that it's a bad practice.

Instead, I organize my dotenv files by deploy target, e. g. development, staging, production. This unleashes my debugging capabilities, letting me make production builds against a local server and unminified builds against production server.

To achieve that, I use a very simple technique in ember-cli-build.js:

const target     = process.env.APPNAME_DEPLOY_TARGET || 'localhost-4200'
const dotEnvFile = `./.env-${target}`
if (!fs.existsSync(dotEnvFile)) throw new Error(`ember-cli-build.js: dot-env file not found: ${dotEnvFile}`)
      dotEnv: {
        path: dotEnvFile
      }

I believe this should be part of the addon. Doing ember s --dotenv .env-production is a feature that everyone would expect from the addon.

Unable to install v2.0

ember install ember-cli-dotenv@^2.0.0

Command failed: yarn add --dev ember-cli-dotenv@^2.0.0 --non-interactive
error Couldn't find any versions for "ember-cli-dotenv" that matches "^2.0.0"

yarn add v1.3.2
[1/5] Validating package.json...
[2/5] Resolving packages...
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

Error: Command failed: yarn add --dev ember-cli-dotenv@^2.0.0 --non-interactive
error Couldn't find any versions for "ember-cli-dotenv" that matches "^2.0.0"

yarn add v1.3.2
[1/5] Validating package.json...
[2/5] Resolving packages...
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

    at Promise.all.then.arr (/home/user/projects/app/node_modules/execa/index.js:231:11)
    at process._tickDomainCallback (internal/process/next_tick.js:129:7)

Question about use ember-cli-dotenv for other ember addons

According to documentation:

You can then use the node process environment variables in other ember-cli-addons, such as express middleware or other servers/tasks.

It's great, but I don't know how exactly it works, let me explain:

Suppose I'm on developing an addon (or engine in near future), and for sure it will be used in an existed app. The app has already uses ember-cli-dotenv, how addon shares those env variables from target app?

I can imagine like:

  1. Use ember-cli-dotenv in addon as well, use same settings as app already had
  2. When addon is done, remove ember-cli-dotenv dependency, because app will provide same thing
  3. app will install addon, and addon will works as documentation describes

What if addon needs update? install ember-cli-dotenv again and repeat steps above?

I have not do this now, just some assumptions, correct me if wrong and suggestions needed.

This addon is incompatible with [email protected]+

Hi.

Suddenly After updating to [email protected], ember-cli-dotenv stopped passing environment variables. In config/environment.js, process.env does not contain env vars from the dot-env file.

This happened to existing commits that have been working previously. My app uses Yarn with a proper lockfile, so I think it may be something with my OS.

Please help me debug this and figure out the reason.

Generic .env file with specific .env for environments?

Hello,

I'm using this plugin since some time ago, and now I see that if you have a .env file, and other for a concrete environment, it only loads the generic .env, and specific environment file don't load attributes if they are in generic .env. I think should be better if you can have a .env file with generic configuration, and the specific environment file overwrite the generic configuration. It should be change the line:

process.env[key] = process.env[key] || parsedObj[key]

for:

process.env[key] = parsedObj[key] || process.env[key]

Thanks!

ignore exports in variable defs

This is really just a feature request, we typically need exports in our envs that we feed to other systems, and would like to be able to use the same env across systems for simplicity sake. Right now, if the .env (what we use on a rails system) contains an 'export' directive, it will cause ember-cli-dotenv to not pick up the value

So, this does not work for a .env
export KEY=blah

where this will
KEY=blah

Its not a huge issue, just forces us to generate 2 seperate envs rather than be able to use a common one with our values

path option doesn't behave well with ember-cli-deploy's development workflow

I am using this addon with ember-cli-deploy's development workflow. I have 3 different env files for different environments: .env.deploy.${env}.

Here's the config/dotenv.js contents:

/* eslint-env node */

module.exports = function(env) {
  return {
    clientAllowedKeys: [
      'API_HOST',
      'ASSET_HOST',
      'REDIS_URL',
      'SOCKET_URL',
      'S3_BUCKET_NAME',
      'AWS_REGION',
    ],
    path: `./.env.deploy.${env}`
  }
}

Running ember s works fine for the development environment but ember deploy staging and ember deploy production commands seem to not find the correct env file.

Changing the path variable from ./.env.deploy.${env} to ../.env.deploy.${env} does the trick.

`config/dotenv.js` does not respect environment assumed from `ember deploy prod`

Hi!

This is a follow-up to #30.

I use multiple dotenv files -- one per deploy target. My config/dotenv.js has logic to select a specific dotenv file provided in a DOTENV_FILE env var (see #25). If DOTENV_FILE is empty, then it picks a default one depending on environment.

The problem is that config/dotenv.js runs before the ember-cli-deploy pipeline. It selects the development dotenv file, then the ember deploy prod command makes ember-cli-deploy use the production environment. The build becomes faulty.

I have to run DOTENV_FILE=prod ember deploy prod every time, which is annoyingly redundant.

I ended up using this workaround:

function deployEnv () {
  if (
    process.argv[2] === 'deploy'
    && (process.argv[3] === 'prod' || process.argv[3] === 'production')
  ) {
    return 'production'
  }
}

let environment =
  process.env.EMBER_ENV
  || deployEnv()
  || 'development'

Maybe ember-cli-dotenv can do a similar thing to assume the environment. Maybe Ember CLI even offers a more robust way to access the command line params.

Cannot read property 'options' of undefined

Not sure if I've missed anything but seems like this.app is undefined inside the config hook in my app?

TypeError: Cannot read property 'options' of undefined
  at Class.module.exports.config (/ember/node_modules/ember-cli-dotenv/index.js:12:27)

env vars not loaded in `.ember-cli.js`

process.env doesnt have any of our dotenv vars in .ember-cli.js that we have in the rest of the ember app.

.ember-cli.js is executed before our config/dotenv.js.

We were able to work around it by doing this. But it would be nice to use ember-cli-dotenv like we do for all other env vars :) :

// .ember-cli.js

const dotEnv = require('dotenv');
const path = require('path');
const fs = require('fs');
const configDotEnv = require('./config/dotenv');

const { path: configPath } = configDotEnv(
  process.env.NODE_ENV || 'development'
);

const absoluteConfigPath = path.join(__dirname, configPath);
if (fs.existsSync(absoluteConfigPath)) {
  dotEnv.config({ path: absoluteConfigPath });
}

setEdition('octane');

let httpOrHttps = process.env.USE_SSL ? 'https' : 'http';
let port = process.env.USE_SSL ? 443 : 80;

module.exports = {
  disableAnalytics: true,
  port: 4200,
  liveReload: true,
  liveReloadPort: 1337,
  host: '0.0.0.0',
  ...
};

Travis missing ENV vars

Hi,

Wondering if there is something special I need to be doing when using travis.

Here's what I get even when setting the all the keys in travis.

WARNING: [ember-cli-dotenv]: Required environment variable

Any ideas?

Ability to check for variable presence

Hi, it would be nice if there would be an option that ensures that build fails when there is missing environment variable. We do this manually in the ember-cli-build.js at the moment, but I guess this could be a part of this addon.

Basically, when you run ember b --environment production it would check if all defined keys in clientAllowedKeys are not empty, otherwise it would fail the build. This prevents situation when someone is deploying and doesn't have all the required variables set. At the moment, this would pass silently and then you get runtime errors in your app, which is really unfortunate.

Thanks,
Ondrej

Make .env.production effective on ember s -prod

Currently when I do ember s -prod the app doesn't use the settings in .env.production. Only when I do ember build -prod the app will use .env.production settings.

It would be nice if ember s -prod can also use the .env.production.

The default lookup path of .env is not documented

By default .env is expected to by located in the configfolder instead of the root folder of the app. Is this intentional?

// config/dotenv.js
/* eslint-env node */

'use strict';

const path = require('path');

module.exports = function(/* env */) {
  return {
    clientAllowedKeys: [],
    fastbootAllowedKeys: [],
    failOnMissingKey: false,
    path: path.join(__dirname, '.env')
  }
};

Warning of missing .env file

I specified a .env.development style .env, one for each environment.

But when I ran the server, I got these warnings:

{ [Error: ENOENT, no such file or directory '/Users/bmckay/Rails/agent5/.env']
  errno: -2,
  code: 'ENOENT',
  path: '/Users/bmckay/Rails/agent5/.env',
  syscall: 'open' }

Seems like you shouldn't get this error unless there is an environment without a .env file defined, and that it should say something more to that effect.
Possibly only when running that environment as well.

This message got printed out many times, so it added a lot of noise.
As a workaround, I just added an empty .env file for now.

process.env variables are not available to config/environment.js on boot

I have a config/environment.js file that looks like this:

module.exports = function(environment) {
  var ENV = {
    adapterURL: process.env.ADAPTER_URL,
    etc...

When I boot my ember app, process.env.ADAPTER_URL is not set. Only after I change something in config/environment.js and force a re-compilation of that file will my app work.

The issue is that on https://github.com/fivetanley/ember-cli-dotenv/blob/master/index.js#L5 the plugin bails if there is no app. But in order for there to be an app, it needs to load the config/environment.js file in your app. So on the subsequent pass through ember-cli-dotenv there is an app, but at this point the environment.js file has already been loaded.

The problem was caused by this commit: 0909769

I'm happy to submit a pull request, but I'd like some guidance. I my understanding of the problem is correct, I think the options are:

  1. Stop loading environment variables into our app's config. Instead, just let dotenv load them into process.env and then force developers to explicitly reference dotenv from their environment files (which I think was introduced here c885731#diff-168726dbe96b3ce427e7fedce31bb0bcR23)
  2. Force a re-compilation of the ember app's environment.js after we load our config

I vote for option 1, fwiw. I think the problem is that we are setting keys on our app's config.

If you let me know what you think, I'd be happy to code it up!

Use failOnMissingKey in CI build

Is there a way to use failOnMissingKey option in a CI build so it takes process.env variables into account?

If not, that could be an option like systemvars in dotenv-webpack plugin? I could make a PR for this if that makes sense to you

Installation fails with "Cannot read property 'clientAllowedKeys' of undefined"

$ ember --version
ember-cli: 3.4.3
node: 8.10.0
os: darwin x64
$ ember install ember-cli-dotenv
Yarn: Installed ember-cli-dotenv
installing ember-cli-dotenv
Cannot read property 'clientAllowedKeys' of undefined


Stack Trace and Error Report: /var/folders/hb/jkd1b3q16nl2xk1qx58mgl3m0000gn/T/error.dump.eb0a01676b4da93523e75d8b44ee1844.log

The stack trace from the log file listed above:

  - stack: TypeError: Cannot read property 'clientAllowedKeys' of undefined
    at Class.config (/Users/jgreen/projects/remarq-books-ember/node_modules/ember-cli-dotenv/index.js:68:36)
    at addons.reduce (/Users/jgreen/projects/remarq-books-ember/node_modules/ember-cli/lib/models/project.js:323:31)
    at Array.reduce (<anonymous>)
    at Project.getAddonsConfig (/Users/jgreen/projects/remarq-books-ember/node_modules/ember-cli/lib/models/project.js:321:24)
    at Project.configWithoutCache (/Users/jgreen/projects/remarq-books-ember/node_modules/ember-cli/lib/models/project.js:272:31)
    at Project.config (/Users/jgreen/projects/remarq-books-ember/node_modules/ember-cli/lib/models/project.js:255:21)
    at Class._generateFileMapVariables (/Users/jgreen/projects/remarq-books-ember/node_modules/ember-cli/lib/models/blueprint.js:792:40)
    at Promise.then.customLocals (/Users/jgreen/projects/remarq-books-ember/node_modules/ember-cli/lib/models/blueprint.js:825:35)
    at tryCatcher (/Users/jgreen/projects/remarq-books-ember/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:323:19)
    at invokeCallback (/Users/jgreen/projects/remarq-books-ember/node_modules/ember-cli/node_modules/rsvp/dist/rsvp.js:495:31)

Use for local development only

So I want to use .env for local development only. But when my app runs in azure, I want it to read from the azure config settings. Now before I installed your add-on, this worked fine. But not it seems like my project needs a .env file or it breaks. Any ideas?

Started getting this.ui.warn error since yesterday

TypeError: this.ui.warn is not a function
TypeError: this.ui.warn is not a function
    at keys.reduce (/var/lib/jenkins/workspace/.../node_modules/ember-cli-dotenv/index.js:100:19)
    at Array.reduce (native)
    at Class._pickConfigKeys (/var/lib/jenkins/workspace/.../node_modules/ember-cli-dotenv/index.js:94:17)
    at Class.config (/var/lib/jenkins/workspace/.../node_modules/ember-cli-dotenv/index.js:70:17)
    at addons.reduce (/var/lib/jenkins/workspace/.../node_modules/ember-cli/lib/models/project.js:302:31)
    at Array.reduce (native)
    at Project.getAddonsConfig (/var/lib/jenkins/workspace/Portal Deploy BETA/node_modules/ember-cli/lib/models/project.js:300:24)
    at Project.configWithoutCache (/var/lib/jenkins/workspace/.../node_modules/ember-cli/lib/models/project.js:251:31)
    at Project.config (/var/lib/jenkins/workspace/.../node_modules/ember-cli/lib/models/project.js:234:16)
    at Class.included (/var/lib/jenkins/workspace/.../node_modules/ember-browserify/lib/index.js:39:38)Pipeline aborted

Use ember-cli-dotenv with travis-ci.org

Thanks for this great ember-cli addon. I was wondering if there is a possibility to use this with an automatic build system like travis-ci.org. In travis-ci.org I have the possibility to add Environment Variables which can be accessed during the build. Do you already have a best practise way how to do this?

Thanks already for your time and answer.

FastBoot support

Hi!

I'm trying to use ember-cli-dotenv with FastBoot.

My goal is to pass a private key to the FastBoot-driven app without letting the key appear in the public app's source.

With FastBoot, the clientAllowedKeys seems to be ignored: all vars from .env end up in the source even if they're not listed in clientAllowedKeys.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.