meanjs best practice to setup process evn for database - heroku

In my attempt to get a 'hello world' skill with meanjs.org product, I cloned 0.4.2 and setup a mongolab account.
I opened > config > env > development.js, to setup db URL, where I have this:
db: {
uri: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://' + (process.env.DB_1_PORT_27017_TCP_ADDR || 'localhost') + '/mean-dev',
For trial, I simply replaced process.env.MONGOLAB_URI with my URL from mongolab and everthing worked for sure, but I doubt this is the way to go. I see a Procfile there, may be I should specify the process.env.MONGOLAB_URI there? Where I could specify it, so that if I upload it to Heroku, say, it will setup the process.env.MONGOLAB_URI and no edit will be needed here please?
p.s. I googled and searched SOF

Well just a small progress,
I got to my gulpfile.js and setup a task as:
gulp.task('setmydb', function () {
process.env.MONGOLAB_URI =
'mongodb://mylogin:mypassword#ds157479.mlab.com:57479/meantst1';
});
Then at the end of the file, added into the task sequence:
// Run the project in development mode
gulp.task('default', function (done) {
runSequence('env:dev', 'lint', ['setmydb','nodemon', 'watch'], done);
});
Well it worked, but I'm still not sure if this indeed is how it must be done! So please help me get sure.

Just in case if someone else also needed, this is how I solved my problem:
Setting configuration variables | Heroku
I first followed the Heroku getting started and edited their app there, added this root:
app.get('/envtst', function(request, response) {
var xterm = process.env.XVAR ==='yes' ? 'yes' : 'no';
response.send(xterm);
});
Then pushed the app to Heroku and also setup my test variable XVAR via command line:
heroku config:set XVAR=yes
finally, opened the root in browser and verified.

Related

Heroku failed to load ./.env

My Problem
I am having trouble loading my environment variables on Heroku production.
When pushing to Heroku I get following error message during the build script:
Failed to load ./.env.
Current Setup
I am using a .env file in the root of my app locally. I can succesfully load my environment variables using the dotenv-webpack plugin as follows:
//webpack.config
const Dotenv = require('dotenv-webpack')
module.exports = {
// other settings...
plugins: [
new Dotenv(),
]
};
Loading the environment variables:
//server.js
require('dotenv').config();
console.log(process.env.MY_VARIABLE);
This works like a charm locally, but fails on Heroku.
Note: My config vars have been set on Heroku, so that's not the problem.
What I tried
I have already tried to force load the .env file from the root of my app like this:
new Dotenv({ path: path.resolve(__dirname, './.env') });
Someone also pointed out that the Heroku environment might be system wide environment variables so I tried to load them using:
new Dotenv({ systemVars: true });
Neither of these attempts worked for me.
My guess
I have noticed that Heroku saves their .env file under ./tmp/build_someRandomBuildId/.env. My guess is that the .env file is not on the root of the directory, hence why dotenv can't find it. There is also no way to hardcode the location of this file in my Webpack configuration as the build ID is randomized with every build. Is there a way to tell Webpack to look for the file in a dynamic location?
Today i stumbled upon this problem, i tried several solutions but none worked. My App was working locally but in production mode (heroku) it was not loading process.env correctly.
then i found this https://www.npmjs.com/package/dotenv-webpack
//webpack.config.js
plugins: [
new Dotenv({ systemvars: true }),
],
Just setting systemvars to true does the trick..
For now I have tested this using different keys for the .env file and the heroku dashboard; They are not connected, and they replace themself correctly in production or dev mode.
Use the package "dotenv-webpack" instead of "dotenv".
I hope this saves some time to anyone facing the same problem
I finally found the solution, leaving this here for others who have the same problem as I did.
I used dotenv-webpack to set my environment variables locally, which worked like a charm. Heroku on the other hand sets their environment variables automatically, so there is no need to set them yourself. There is no need to look for a .env file. All I had to do was split up my webpack.config in 2 separate files.
//webpack.dev
require('dotenv').config();
plugins: [
new Dotenv()
],
Load .env file locally.
//webpack.prod
require('dotenv').config();
plugins: [
new webpack.DefinePlugin({
'process.env': {
'YOUR_VARIABLE': JSON.stringify(process.env.YOUR_VARIABLE),
}
});
]
Get your environment variables from Heroku and write them to your own process.env
If you are not using Webpacks, the idea's solution is similar to the accepted answer.
Heroku works on "production" mode by default, so if the problem in Heroku is with Dotenv (which should not be used anyways in Heroku), disable the use of Dotenv in production time like this:
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config() }
}
...and then, access env variables just by doing:
var someVar = process.env.SOME_VARIABLE;
Don't forget to set the environment variables on Heroku first by using Console Commandline in your app's dashboard, or with an app.json file.

Executing shell command after Webpack post build

I have a Laravel project and as you know when you deploy your app everything in your public directory should be copied over to your htdocs or public_html directory to hide your application's code.
I am using webpack to build my react code and everything else and each time I change my javascript webpack does what I want, it sees I make a change and then it builds it.
However I want to add one additional command after it builds and that is to copy everything from the public directory into the correct directory in htdocs/public_html.
So far I read up on this question here Run command after webpack build
It works and I can get the echo to work but I'm not sure why cp isn't working. Echo works but how do I know what shell commands I can use?
I tried 'cp' and even 'copy-item' which is powershell, but none are working.
This is my plugin so far, I figured I needed to change the directory to be safe
before copying anything over but again, nothing is working.
mix.webpackConfig(webpack => {
return {
plugins: [
new WebpackShellPlugin({
onBuildStart: ['echo "Starting Build ..."'],
onBuildEnd: ["cd 'E:\\xammp\\apps\\FactorioCalculator'",
"cp '.\\public\\*' '..\\..\\htdocs\\FactorioCalculator\\' -f -r"]
})
]
};
});
You could always use the copyDirectory mix method. Just put something like the following at the bottom of your webpack.mix.js file:
mix.copyDirectory('public', '../../htdocs/FactorioCalculator/')
You might have to change your path to ..\\..\\htdocs\\FactorioCalculator\\ as per the path in your question (I only have my mac with me so I'm unable to test on my other machine).
To answer you original question, if you want to execute a command each time webpack finishes building you can use the mix.then() which takes a closure.

Node Env not set?

This is a general question though I haven't found where I am going wrong.
Using Windows Server with Azures kudu stand alone to host a local project.
Also using React, Webpack, Redux
Windows environment var is set to production
Package.json has set NODE_ENV=production && etc.. for
both start and build scripts
web.config has iisnode node_env=production
running node I get the node_env is indeed production
However when I build it's giving me the development build when I do something like
if (process.env.NODE_ENV === 'production') {
module.exports = require('./buildProduction.js')
}
else {
module.exports = require('./buildDevelopment.js')
}
What gives?
I came to the same conclusion and searched why this is and thanks to neagtivetwelve for the comment # https://github.com/webpack/webpack/issues/1720
In short setting
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
}),
fixes the issue. Instead of
new webpack.DefinePlugin({
'process.env.NODE_ENV': process.env.NODE_ENV,
}),
Even though I have in the build script to set the session NODE_ENV var and set within the system environment vars I would still get the wrong result until this change was made even though opening node from cmd and typing process.env.NODE_ENV yields the correct result.
Anyway I hope it helps someone else.

Set host name as an environment variable in Heroku review app

I'm using the Review Apps feature integrated with Github on Heroku. In one of my apps, I set an environment variable called HOST_NAME . For example, if the site is http://www.purplebinder.com, then HOST_NAME would be set to www.purplebinder.com. It's used in a couple of places where we work with cookies and in our transactional emails.
When I open up a new pull request and spin up a review app, HOST_NAME should be something like purplebinder-pr-27.herokuapp.com.
Is there a way to set this value automatically? The Heroku documentation on review apps says an env var can inherit a value from the parent app or be hardcoded in app.json. Neither of those approaches work here, because the value needs to be different each time, and also different from the parent app.
Heroku also says an env var can be set "through a generator", but doesn't go into detail about what that is.
This question might be a duplicate of Setting ROOT_URL for Review Apps, but nobody answered that one. It's also similar to How to get Heroku app name from inside the app, but the answers there involved running a script after the app was created - here I'd like to set this value as part of the initial build.
From https://devcenter.heroku.com/articles/github-integration-review-apps#heroku_app_name-and-heroku_parent_app_name:
To help with scripting, two special config vars are available to
review apps. If you specify HEROKU_APP_NAME or HEROKU_PARENT_APP_NAME
as required or optional config vars in your app.json file, Heroku will
set those config vars to the new application name and the parent
application name respectively. They will then be available for use in
the postdeploy script so that you can do more advanced bootstrapping
and configuration.
Here is an example app.json file that uses
HEROKU_APP_NAME and HEROKU_PARENT_APP_NAME:
{
"name":"Advanced App",
"scripts": {
"postdeploy": "rake db:setup && bin/bootstrap"
},
"env": {
"HEROKU_APP_NAME": {
"required": true
},
"HEROKU_PARENT_APP_NAME": {
"required": true
}
}
}
If you add the heroku-buildpack-cli to your parent app, then it enables you to set environment variables from your post-deploy script. The command should look something like the following:
heroku config:set HOST_NAME=${HEROKU_APP_NAME}.herokuapp.com --app ${HEROKU_APP_NAME}
Here's an approach ignoring app.json for Rails installations:
in the relative config/<environment>.rb. I personally use production.rb and staging just references it.
if ENV.fetch("HEROKU_APP_NAME", "").include?("staging-pr-")
ENV["APPLICATION_HOST"] = ENV["HEROKU_APP_NAME"] + ".herokuapp.com"
ENV["ASSET_HOST"] = "https://" + ENV["APPLICATION_HOST"]
config.action_mailer.default_url_options = { host: ENV.fetch("APPLICATION_HOST") }
end
...
It's a bit misleading as the heroku environment variables will still have the old variables, but it works.
You can also create review environment for you application copying staging.rb or production.rb from config/environments. This would be useful.
After adding HEROKU_APP_NAME and HEROKU_PARENT_APP_NAME to your app.json, you can easily set;
config.action_mailer.default_url_options = { host: "#{ENV['HEROKU_APP_NAME']}.herokuapp.com" }
config.action_mailer.asset_host = "http://#{ENV['HEROKU_APP_NAME']}.herokuapp.com"
config.action_controller.asset_host = "#{ENV['HEROKU_APP_NAME']}.herokuapp.com"
config.action_cable.url = "wss://#{ENV['HEROKU_APP_NAME']}.herokuapp.com/cable"

Cloud9 tries to recreate .settings file

I've installed Cloud9 IDE on my linux machine in order to play around with it a bit (I had to use nodejs 0.8 because cloud9 uses a package that depends on node-waf, which is no longer supported by higher versions of nodejs).
I can start it up without problems, however when I try to access Cloud9 via browser, it constantly gives me the error message: File already exists.. Here's a trace from the log:
Error: File already exists.
at module.exports.from (/home/xyz/repos/cloud9/node_modules/vfs-local/localfs.js:678:35)
at Object.fs.exists [as oncomplete] (fs.js:91:19)
Relevant code section:
exists(topath, function(exists){
if (options.overwrite || !exists) {
// Rename the file
fs.rename(frompath, topath, function (err) {
if (err) return callback(err);
// Rename metadata
if (options.metadata !== false) {
rename(WSMETAPATH + from, {
to: WSMETAPATH + to,
metadata: false
}, function(err){
callback(null, meta);
});
}
});
}
else {
var err = new Error("File already exists.");
err.code = "EEXIST";
callback(err);
}
When the error occurs, the topath variable is set to the workspace settings file (/home/xyz/repos/cloud9/workspace/.settings)
Has anyone else had an error like this? How can I resolve it?
thx in advance
Reinstalling cloud9
First option, maybe you could try using this workaround installation procedure:
https://github.com/ajaxorg/cloud9/issues/2904#issuecomment-22518669
Second option, if you are willing to always use an older node-version for running cloud9 as you indicated, I used the following installation procedure and it worked (assuming you already installed nvm). Then you can still use the cloud9.sh-file for starting:
git clone git://github.com/ajaxorg/cloud9.git
cd cloud9
nvm install 0.8.8
sed -i -e 's/~//g' package.json
npm config set ca=""
npm install
sed -i s/connect.session.file/connect.session.memory/ configs/default.js
Not sure if 0.8.8 is the best node-version for cloud9 but it works for me :)
Last step seems necessary because of https://github.com/ajaxorg/cloud9/issues/2005#issuecomment-11372587 :)
Then before starting cloud9 you always have to enter:
nvm use 0.8.8
Or you set 0.8.8 as the default node version if you don't use node much otherwise:
nvm alias default 0.8.8
Fix problem without reinstalling
Third option, if you don't want to repeat the installation procedure you could try just reinstalling the vfs-local-module in the cloud9 directory:
npm install vfs-local#0.3.4
Haven't tested this though :)

Resources