0

do I have to set the process.env.NODE_ENV myself when I am in development? Does node not set the .env to production when I have a build folder, and development when I am in local environment? I was under the impression many libraries use this as a optimization tool

for example in my app.js file the console.log code turns up undefined

console.log(process.env.NODE_ENV)

const express = require('express');
const app = express();
const mongoose = require('mongoose');
const postsRouter = require('./routes/Post_Route');
const path = require("path")


// parse body on every request //
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

//Routes
app.use('/api/posts', postsRouter);



// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === 'production') {
    app.use(express.static(path.join(__dirname, 'client', 'build')));
    }

console.log(process.env.NODE_ENV)

if (process.env.NODE_ENV === 'production') {

    console.log(`Mongoose is in  production === ${process.env.NODE_ENV}  mongo uri is ${process.env.MONGO_URI_PROD}`)
    // connect DB

when I set the NODE.ENV in my .env file I see it as development, am I to set it manually in development then on heroku for example set the NODE_ENV as production?

6 Answers6

1

in package.json

{
  ...
  "scripts": {
    "start": "NODE_ENV=production node ./app"
  }
  ...
}
1

Sadly enough yes. There is no command like "node script.js --production". Instead, just run this on Linux systems export NODE_ENV=production and that will set you. Alternatively, you can change your launch command to NODE_ENV=production node script.js and that'll set you right for production testing.

Abe
  • 421
  • 3
  • 11
1

NODE_ENV=production node script.js should work.

But it does not work on Windows. So I recommend to use a package like cross-env to make it works in all platform.

{
  "scripts: {
    "start": "cross-env NODE_ENV=production node script.js"
  }
}
Zmen Hu
  • 795
  • 3
  • 12
0

you can also set it in your webpack config with DefinePlugin. Works on Windows too

plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': '"production"',
    }),
  ],
-1

You need to define the environment variable in server. if you are using linux, check with printenv . if variable not in list you need to define

Gurinder Sason
  • 130
  • 2
  • 13
-1

In my opinion I would say npm install dotenv

Docs at : https://www.npmjs.com/package/dotenv

then import it within your entry script file import dotenv from "dotenv" and as early as possible envoke dotenv.config() this will load all variables in your .env file.