Cort Fritz
Cort Fritz

Reputation: 143

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?

Upvotes: 11

Views: 2947

Answers (2)

Tom
Tom

Reputation: 26819

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.

Upvotes: 6

marionebl
marionebl

Reputation: 3382

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

Upvotes: 5

Related Questions