How to Load Production Files with Express?

So I am running into a problem when deploying express to indicate whether I am in production or development.

I am using Node/Express/Handlebars per this guide: [Tutorial] An Introduction to Node.js Servers (and Express.js) - #45 by PaulH

Now the problem is that I have deployed the app, but things are still loading as if they are in development.

Reading on the web, it seems like I need to configure a dev build script and a production build script. When I do, I put a variable in there to indicated which type of production it is. Is that the best practice?

Something like this:

 "start": "NODE_ENV=production node index.js",
    "dev": "NODE_ENV=development nodemon index.js",

This site suggests creating some kind of configuration function?

app.configure('development', () => {
  //...
})
app.configure('production', () => {
  //...
})
app.configure('production', 'staging', () => {
  //...
})

What is the best way to move forward with flagging production? Is there a good guide?

I am also using this MDN guide: Express Tutorial Part 7: Deploying to production - Learn web development | MDN

Are you using pm2? It would be different with pm2.

Try this in the terminal on the remote server:

$ echo 'export NODE_ENV=production' >> ~/.bashrc
$ source ~/.bashrc

Then restart the app.

1 Like

I think what I found right now is this script I can put in the server.js (sometimes app.js)


if(process.env.NODE_ENV === 'production') {
    // We are running in production mode
    var cache = require('express-redis-cache')({ expire: 604800 });
    
} else {
   // We are running in development mode
   console.log("development");

   var cache = require('express-redis-cache')({ expire: 1 });
}

I am going to use it to have the redis cache last for a week in production, and for 1 second in dev mode.

I think I will then have pm2 always start the npm start server script which has the production variable…

Your code there will read whether it’s in development or production mode. To set it as production mode, try my snippet.

(Find me on Slack if you want to screenshare.)

1 Like

I will try this, and report back. Thanks!

1 Like

I ran the code, but I am not sure if it working… I suppose so?

There’s another line under that one.

$ source ~/.bashrc

If this command shows output, then it’s working:

$ echo $NODE_ENV
1 Like