Search code examples
node.jspathpublicproductionrestrict

Node.js - Dynamically forbid some public paths on production mode


I'm using node.js with express.js. Here's my public dir structure:

public/
    js/
    css/
    images/
    built/
        main-built.js
        main-built.css
    index.html
    dev.html

Where index.html links to scripts in js/ and css/, while dev.html links to main-built.js and main-built.css. How can I dynamically forbid some paths under public/ (js/*, css/* and dev.html) when the app is launched as production mode?


Solution

  • If you're using Express, you could block them with a small piece of middleware.

    app.configure(function() {
      app.use(function(req, res, next) {
        if(process.env.NODE_ENV === 'production') {
          if( /* check req.url for blocked content */) {
            res.send('Access Denied');
          }
        }
        else {
          // Not in production, proceed to next handler.
          next();
        }
      });
      app.use(express.static(__dirname + '/public'));
    });