{ sailsit }

Sails Js Tutorials for Beginners and Forum

Have a Question?

If you have any question you can ask below or enter what you are looking for!

Sails – Working with Policies

1. Creating SailsJs Project

Follow the below tutorial for setting up SailsJs
Setting up sails project

2. Creating Controller

Generate a controller using the below command

sails generate controller User

copy the below code and paste in api/controllers/UserController.js

module.exports = {

    policiesValidation: function (req, res) {
            success: true,
            message: "policy validation passed"


3. Creating Policies

Create a new file sourceValidation.js in api/policies directory
Paste the below code in your sourceValidation.js file

module.exports = function(req, res, next) {

     * If Request Body contains source as sailsit then
     * policy will go to the respective controller
     * otherwise it will directly return bad request response
    if(req.param("source") && req.param("source") === "sailsit") {
    } else {
            success: false,
            message: "policy validation failed"


In this code we are verifying source of the request, if request does not contain source param as sailsit then we reject the request
or if it contains source as sailsit in request body then its redirected to respective controller function using next() function

4. Configuring Policies

Go to config/policies.js file
Paste the below code in it

module.exports.policies = {
    UserController: {

         * Use this for applying sourceValidation policy to all functions of UserController
        //'*': sourceValidation,

         * Use this for applying policy to specific function
        policiesValidation	: 'sourceValidation'

         * To use multiple policies for one function you can use this method
        // policiesValidation: ['policy1', 'policy2']

This will configure sourceValidation policy for policiesValidation function

5. Checking Validation

Now to check the whether policy is working or not
Start sails using below command

sails lift

Start any RestClient (POSTMAN), and check the below route

  • Without Source Param


    This will return below mentioned error as it does not contain source in request

        "success": false,
        "message": "policy validation failed"


  • With Source Param


    This will return success response as it contains the source param as sailsit

        "success": true,
        "message": "policy validation passed"


You can find the source code for the tutorial at below URL
SailsPolicies Source Code