Search code examples
javascriptnode.jsforemanenv

Using .ENV value in NodeJS, Required Key Error in Procfile Definition


I am trying to use the foreman package to see if the way I setup my .env file will work with use in one of my JS files, but when I run nf start server.js I receive the following warnings and then the server never starts. I thought it was related to not calling the variable in the server.js file, but that didn't change anything

[OKAY] Loaded ENV .env File as KEY=VALUE Format
[WARN] No Procfile Found
[OKAY] package.json file found - trying 'npm start'
[OKAY] Trimming display Output to 55 Columns
[WARN] Required Key 'server.js' Does Not Exist in Procfile Definition

Here is how I'm using my .env file:

.env

DB_CONFIGURATION=mongodb://<user>:<pw>.mongolab.com:6383219/db-name

blogDB.js:

var DB_CONFIG = process.env.DB_CONFIGURATION;

module.exports = {
    url : DB_CONFIG;
}

server.js (Where I'm calling the blogDB file)

//Load express
var express = require('express');
var app = express();
var router = express.Router(); // get an instance of the router
var bodyParser = require('body-parser'); // configure app to use bodyParser()
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');

app.use(bodyParser.urlencoded({ extended: true})); // get data from a POST method
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(cookieParser());


var port = process.env.PORT || 8080; // set the port


var blogDB = require('./config/blogDB.js');
mongoose.connect(blogDB.url);

require('./config/passport.js')(passport);


app.set('view engine', 'ejs'); // set ejs as the view engine

app.use(express.static(__dirname + '/public')); // set the public directory

app.use(session({ secret: 'thisisatest' }));
app.use(passport.initialize());
app.use(passport.session());

app.use(flash());



var routes = require('./app/routes');

app.use(routes); // use routes.js


app.listen(port);
console.log('magic is happening on port' + port);

Solution

  • To use Foreman you need to create a file named Procfile in the root of your project -- this file tells foreman how to run your project.

    In this file, you might want to put a line like this:

    web: node server.js
    

    Or, whatever command is used to 'start' your web service. Then, if you run foreman start from the command line, foreman will parse the Procfile, then run that command for you (node server.js).