# Rules not executing in order

**URL:** <https://community.auth0.com/t/rules-not-executing-in-order/39672>\
**Category:** Get Help\
**Tags:** rules\
**Created:** [March 19, 2020, 9:47pm UTC](https://community.auth0.com/t/rules-not-executing-in-order/39672 "2020-03-19T21:47:50Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![andre.hermanto93](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/andre.hermanto93/32/13514_2.png) [@andre.hermanto93](https://community.auth0.com/u/andre.hermanto93)\
**Post date:** [March 19, 2020, 9:47pm UTC](https://community.auth0.com/t/rules-not-executing-in-order/39672/1 "2020-03-19T21:47:50Z")

</div>

Hi Auth0 Community,

I suddenly have a problem where rules script not executing is not executing in correct order(they run asynchronously). These were fine and tested before, until I got some complaint from the users a month ago. Upon checking it was the rules that is not executing in proper order.

The 1st rules is meant to call auth0-authorization api to give roles to a user  
The 2nd rules is meant to write metadata based on roles given on the 1st rules

On a side note, this was working fine for a year or so, then I start getting complaint about 2 months ago.

---

<div class="post-metadata">

**Author:** ![markd](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/markd/32/38919_2.png) [@markd](https://community.auth0.com/u/markd)\
**Post date:** [March 20, 2020, 2:24am UTC](https://community.auth0.com/t/rules-not-executing-in-order/39672/2 "2020-03-20T02:24:34Z")

</div>

Hi @andre.hermanto93,

Can you do some testing / logging to demonstrate the behaviour? You can use the [Realtime Webtask Logs](https://auth0.com/docs/extensions/realtime-webtask-logs) extension to help. Anything you `console.log()` in a rule will show up in the realtime webtask logs interface.

---

<div class="post-metadata">

**Author:** ![andre.hermanto93](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/andre.hermanto93/32/13514_2.png) [@andre.hermanto93](https://community.auth0.com/u/andre.hermanto93)\
**Post date:** [March 20, 2020, 3:05am UTC](https://community.auth0.com/t/rules-not-executing-in-order/39672/3 "2020-03-20T03:05:34Z")

</div>

Hi @markd

 ![Screen Shot 2020-03-20 at 1.52.00 pm](https://global.discourse-cdn.com/auth0/original/3X/5/e/5e81334737b21d87e6c5970f5cf0435feeaf3b11.png)

So above are my 2 rules that doesn’t execute in order.

Assign role to selected users script is:

```
function (user, context, callback) {
  var acuteCare = '9da80d63-c29e-48bd-8cbb-a725f662df05';
  
  var emailsListAcuteCare = [
                             'test@test.com'
                          	];
  
  var accessGiven = [];

  if(emailsListAcuteCare.includes(user.email.toLowerCase())){
    accessGiven.push(acuteCare);
  }

  if(accessGiven.length > 0){
    var request = require("request");
    var options = { method: 'POST',
    url: 'https://URL/oauth/token',
    headers: { 'content-type': 'application/json' },
    body: '{"client_id":"ID","client_secret":"SECRET","audience":"urn:auth0-authz-api","grant_type":"client_credentials"}' };

    request(options, function (error, response, body) {
      if (error) throw new Error(error);
      var opt = { method: 'PATCH',
        url: `https://URL.au8.webtask.io/adf6e2f2b84784b57522e3b19dfc9201/api/users/${user.user_id}/roles`,
        headers: { 'content-type': 'application/json', 
              'authorization': `Bearer ${JSON.parse(body).access_token}` },
        body: JSON.stringify(accessGiven)
    };

    request(opt, function (er, response, body2) {
      console.log("This should come 1st");
      if (er) throw new Error(er);
     });
   });
  }
  
  callback(null, user, context);
}

```

Then my auth0-authorization-extension script is:

```
function (user, context, callback) {
  var _ = require('lodash');
  var EXTENSION_URL = "";

  var audience = '';
  audience = audience || (context.request && context.request.query && context.request.query.audience);
  if (audience === 'urn:auth0-authz-api') {
    return callback(new UnauthorizedError('no_end_users'));
  }

  audience = audience || (context.request && context.request.body && context.request.body.audience);
  if (audience === 'urn:auth0-authz-api') {
    return callback(new UnauthorizedError('no_end_users'));
  }

  getPolicy(user, context, function(err, res, data) {
    if (err) {
      console.log('Error from Authorization Extension:', err);
      return callback(new UnauthorizedError('Authorization Extension: ' + err.message));
    }

    if (res.statusCode !== 200) {
      console.log('Error from Authorization Extension:', res.body || res.statusCode);
      return callback(
        new UnauthorizedError('Authorization Extension: ' + ((res.body && (res.body.message || res.body) || res.statusCode)))
      );
    }

    // Update the user object.
    user.permissions = data.permissions;

    // Store this in the user profile (app_metadata).
    saveToMetadata(user, data.groups, data.roles, data.permissions, function(err) {
      console.log("This should come 2nd");
      return callback(err, user, context);
    });
  });

  // Get the policy for the user.
  function getPolicy(user, context, cb) {
    request.post({
      url: EXTENSION_URL + "/api/users/" + user.user_id + "/policy/" + context.clientID,
      headers: {
        "x-api-key": "API KEY"
      },
      json: {
        connectionName: context.connection || user.identities[0].connection,
        groups: user.groups
      },
      timeout: 5000
    }, cb);
  }

  // Store authorization data in the user profile so we can query it later.
  function saveToMetadata(user, groups, roles, permissions, cb) {
    user.app_metadata = user.app_metadata || {};
    user.app_metadata.authorization = {
      permissions: permissions
    };

    auth0.users.updateAppMetadata(user.user_id, user.app_metadata)
    .then(function() {
      cb();
    })
    .catch(function(err){
      cb(err);
    });
  }
}

```

Then upon execution the 2nd always executed first. Here’s the screenshot of the logs

 ![Screen Shot 2020-03-20 at 1.56.44 pm](https://global.discourse-cdn.com/auth0/original/3X/c/5/c5517f6386f7135f0e22dd2054af75e7de07e2ee.png)

---

<div class="post-metadata">

**Author:** ![andre.hermanto93](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/andre.hermanto93/32/13514_2.png) [@andre.hermanto93](https://community.auth0.com/u/andre.hermanto93)\
**Post date:** [March 23, 2020, 12:33pm UTC](https://community.auth0.com/t/rules-not-executing-in-order/39672/4 "2020-03-23T12:33:01Z")

</div>

Hi @markd,

Is there any update on this?

Cheers

---

<div class="post-metadata">

**Author:** ![mathiasconradt](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/mathiasconradt/32/12758_2.png) [@mathiasconradt](https://community.auth0.com/u/mathiasconradt)\
**Post date:** [March 23, 2020, 1:16pm UTC](https://community.auth0.com/t/rules-not-executing-in-order/39672/5 "2020-03-23T13:16:50Z")

</div>

The callback of the first rule

> callback(null, user, context);

is outside of the `request {...}` , so that calling is executed without waiting for the request() to finish, as the request runs async.  
It should be inside that request, like this:

```
request(opt, function (er, response, body2) {
  console.log("This should come 1st");
  if (er) {
    throw new Error(er) 
  } else {
    callback(null, user, context);
  }
 });

```

But also note, since you actually have 2 request in your first rule: these requests also don’t wait for each other, so you never know which of the two requests will finish first. Might make sense to call this in a nested as well.

---

<div class="post-metadata">

**Author:** ![konrad.sopala](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/konrad.sopala/32/13516_2.png) [@konrad.sopala](https://community.auth0.com/u/konrad.sopala)\
**Post date:** [January 8, 2024, 8:06am UTC](https://community.auth0.com/t/rules-not-executing-in-order/39672/6 "2024-01-08T08:06:05Z")

</div>

Hey there!

As this topic is related to Rules - Hooks - Actions, I’m excited to let you know about our next [Ask me Anything session in the Forum on Thursday, January 18 with the Rules, Hooks and Actions team](https://community.auth0.com/t/auth0-community-ask-me-anything-rules-hooks-and-why-actions-matter/124043) on Rules & Hooks and why Actions matter! Submit your questions in the thread above and our esteemed product experts will provide written answers on January 18. Find out more about Rules & Hooks and why Actions matter! Can’t wait to see you there!

[Learn more here!](https://community.auth0.com/t/auth0-community-ask-me-anything-rules-hooks-and-why-actions-matter/124043)

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/auth0/original/3X/b/5/b560f266932fcce5d57f09a6595bd50518cae3f3.jpeg) [@system](https://community.auth0.com/u/system)\
**Post date:** [January 22, 2024, 8:06am UTC](https://community.auth0.com/t/rules-not-executing-in-order/39672/7 "2024-01-22T08:06:43Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
