randal
randal

Reputation: 1372

Heroku Error: ENOENT: no such file or directory, open '.env'

I'm trying to push my application to Heroku, but I'm running into some issues:

Error: ENOENT: no such file or directory, open '.env' 2019-04-10T01:38:23.050188+00:00 app[web.1]: 1 at Object.openSync (fs.js:438:3) 2019-04-10T01:38:23.050190+00:00 app[web.1]: 1 at Object.readFileSync (fs.js:343:35) 2019-04-10T01:38:23.050192+00:00 app[web.1]: 1 at Object. (/app/config/database.js:4:39)

It seems that the error is the variable envConfig, but i need it for database to work.

As of now, I'm getting

enter image description here

Here is my config/database.js:

if (!process.env.PG_DB) {
    const fs = require('fs')
    const dotenv = require('dotenv')
    // dotenv, but i need this make the database work
    const envConfig = dotenv.parse(fs.readFileSync('.env'))

    for (var k in envConfig) {
      process.env[k] = envConfig[k]
    }

    console.log('[api][sequelize] Loaded database ENV vars from .env file')
  }

  module.exports = {
    development: {
      username: process.env.POSTGRES_USER,
      password: process.env.POSTGRES_PASSWORD,
      database: process.env.POSTGRES_DB,
      host: process.env.POSTGRES_HOST,
      dialect: 'postgres',
      migrationStorageTableName: 'sequelize_meta'
    },

    production: {
      username: "root",
      password: null,
      database: "*********some postgress url",
      host: "127.0.0.1",
      dialect: "postgres"
    }

And my app.js:

var express = require('express');
var app = express();
var userRoute = require('./routes/users');
var postRoute  = require('./routes/posts');
var bodyParser = require('body-parser');
var logger = require('morgan');
var session = require('express-session');
var cookieParser = require('cookie-parser') ;
var dotenv = require('dotenv');
var env = dotenv.config();
var cors = require('cors');
var models = require('./models/');
const port = process.env.PORT || 8000;
const passport = require('passport');
const path = require('path');
// const allowOrigin = process.env.ALLOW_ORIGIN || '*'
// CORS Middleware
if (!process.env.PORT) {
  require('dotenv').config()
}
if (!process.env.PORT) {
  console.log('[api][port] 8000 set as default')
  console.log('[api][header] Access-Control-Allow-Origin: * set as default')
} else {
  console.log('[api][node] Loaded ENV vars from .env file')
  console.log(`[api][port] ${process.env.PORT}`)
  console.log(`[api][header] Access-Control-Allow-Origin: ${process.env.ALLOW_ORIGIN}`)
}
require('./config/passport-github');
require('./config/passport');
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(session({
  secret : process.env.JWT_SECRET,
  saveUninitialized: false,
  maxAge: 1000 * 60 * 60 * 84,
  resave: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:false})); 
const isAuthenticated = function(req, res, next){
  if(req.isAuthenticated()){
    next();
    console.log('this works');
  }else{
   res.redirect('http://127.0.0.1:8001/signIn');
  }
}
// app.use(function(req, res, next) {
//   res.header('Access-Control-Allow-Origin', '*');
//   // res.header('Access-Control-Allow-Credentials',  true);
//   res.header("preflightContinue", false)
//   // res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
//   res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
//   next();
// });
app.use(cors({
    'allowedHeaders': ['Content-Type'], // headers that React is sending to the API
    'exposedHeaders': ['Content-Type'], // headers that you are sending back to React
    'origin': '*',
    'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
    'preflightContinue': false
}));
app.use('/api/users', userRoute );
app.use('/api/posts', isAuthenticated,  postRoute );
app.use(function(req, res, next) {
  res.locals.user = req.user; // This is the important line
  // req.session.user = user
  console.log(res.locals.user);
  next();
});
models.sequelize.sync().then(() => {
  const server = app.listen(port, () => {
    console.log(`Server is up and running on port ${port}`);
  });
});

Upvotes: 5

Views: 8849

Answers (1)

Chris
Chris

Reputation: 137228

Before you do anything else, if those are your real credentials you should invalidate them immediately. They are forever compromised, and you need to generate new ones. Editing them out of your question is not enough.


You can change

const envConfig = dotenv.parse(fs.readFileSync('.env'))

to

const envConfig = dotenv.config({silent: true})

You don't need to manually read the file here, and skipping it lets you gracefully handle the case when it doesn't exist. There's also no need to manually set values in process.env:

for (var k in envConfig) {
  process.env[k] = envConfig[k]
}

This can be entirely skipped. Dotenv takes care of this itself. Therefore, you don't need envConfig either, reducing all of that to just

dotenv.config({silent: true})

If .env exists, its contents will be added to what's already in process.env. In development, this gives you a convenient way to set your database connection information.

In production, .env shouldn't exist, and your database connection information definitely shouldn't be hard-coded. Instead, your database connection information should come from one or more Heroku config vars (these are environment variables that should already be available via process.env). Your database addon has probably already set the DATABASE_URL variable for you.

For things in your .env that you've set yourself, set a Heroku config var for its production value. You can do that through the Heroku web dashboard or via the Heroku CLI:

heroku config:set SOME_VARIABLE=foo

Upvotes: 6

Related Questions