Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sailsjs v0.10 express customMiddleware not loading

Can anyone tell me how to load customMiddleware, or any function that gets the express app, in sails v0.10?

In the past you could, inside /config/express.js, have the following:

customMiddleware: yourFunc(app){
  //do stuff including
  // app.use(myMiddleware)
}

This member of express.js is no longer called in v0.10 - at least not by default. You can prove this to yourself by creating a new app with "sails new" and defining a new function in config.express.customMiddleware. It won't fire.

Does anybody know how to enable this? Or is there another place or config option to enable me to get access to the express app at startup?

like image 533
Cort Fritz Avatar asked Feb 16 '14 04:02

Cort Fritz


2 Answers

Handling of the customMiddleware has slightly changed in Sails 0.10. In version 0.10 that method needs to be configured in http hook (not express hook, as in previous version).

It is also very important to remember that your sails.config.http.middleware.order list needs to have '$custom' middleware entry in it as that will trigger custom middleware function to run.

So in order to add any custom initialization, you can add the following change to the /config/http.js file:

module.exports.http = {
    // ...
    customMiddleware: function(app) {
        // do something ...
    }
    // ...
}

Alternatively, if you would like to perform environment dependent customization, say, in production, you can add following changes to the /config/env/production.js

module.exports = {
    // ...
    http: {
        customMiddleware: function(app) {
            // do something in production environment
        }
    }
    // ...
}

I use that approach to enable trust proxy express flag.

Example:

...
   http: {
    customMiddleware: function(app) {
        app.enable('trust proxy');
    }
  }
...

Code handling can be found on Sails Github: /sails/lib/hooks/http/middleware/load.js.

BTW, when using express hook in Sails 0.10, you will get following warning:

warn: sails.config.express is deprecated; use sails.config.http instead.

like image 150
Tom Avatar answered Dec 28 '22 23:12

Tom


You have to specify an additional config for config.express.costumMiddleware to be mounted. By setting config.middleware.custom to true you enable this default behavior of previous Sails versions.

// config/express.js
module.exports.express = {
  middleware: {
    custom: true
  },

 customMiddleware: function(app){
    // express middleware here
 }
};

Related commit

a89a883c22

Related source

sails/lib/hooks/http/load.js

like image 27
marionebl Avatar answered Dec 28 '22 22:12

marionebl