Search code examples
node.jssslexpresssails.jshsts

Modify response header with sails.js for implementing HSTS


I am implementing a nodejs application using sails.js. I want my user to communicate only through https. So for doing that I need to configure my server my way so that with each response it will add a header "Strict-Transport-Security", "max-age=31536000" to tell browser to communicate with HSTS only. Now how I can modify every response header that I am going to send from sails js.I searched the documentation but did not found any help.


Solution

  • Policies are only applied to the controllers that you explicitly assign them to in config/policies.js.

    Instead of using a policy, try adding an express middleware directly in config/express.js, (create the file if it does not already exist). This middleware is applied to ALL controllers. The format is like so:

    // config/express.js
    "use strict";
    exports.express = {
        customMiddleware: function (app) {
            app.use(function hsts(req, res, next) {
                res.setHeader("Strict-Transport-Security", "max-age=31536000");
                next();
            });
        }
    }
    

    If you have multiple express custom middleware that you want to use, my advice is to keep each middleware function in its own file. I will provide an example, using your middleware along with an additional middleware that accepts some options.

    // config/express.js
    "use strict";
    var hsts = require('../lib/middleware/hsts');
    var staticguard = require('../lib/middleware/staticguard');
    exports.express = {
        customMiddleware: function (app) {
            // ordering of middleware matters!
            app.use(hsts);
            app.use(staticguard(/^\/protected\/.*$/));
        }
    }
    
    // lib/middleware/hsts.js
    "use strict";
    module.exports = function hsts(req, res, next) {
        res.setHeader("Strict-Transport-Security", "max-age=31536000");
        next();
    }
    
    // lib/middleware/staticguard.js
    "use strict";
    module.exports = function (regex) {
        return function (req, res, next) {
            if (!regex.test(req.url)) {
                return next();
            }
            res.end('you are not allowed!');
        }
    };
    

    If you try to have multiple files export a function on the 'express.customMiddleware' namespace, I believe only the middleWare of the last file loaded will work. I haven't tried it though.