Wednesday, 15 March 2017

ES6 import happening before .env import

Importing a library that requires an environment variable from my dotenv file crashes my app because the dotenv file is not loaded on time.

// server.js

require('dotenv').config({ silent: process.env.NODE_ENV === 'production' })

console.log("Here is the env var: ", process.env.SPARKPOST_API_KEY)

import express from 'express'

(...)

Which logs the appropriate env var

And

// somecontroller.js

import SparkPost from 'sparkpost'

var sparky = new SparkPost()  // uses process.env.SPARKPOST_API_KEY

Which crashes with error

Error: Client requires an API Key.

The API key is there, so it seems that somecontroller.js is instantiating new SparkPost() before the dotenv file gets loaded.

How do I work around this?



via softcode

No comments:

Post a Comment