# Async rule writing to a database on login, directly call callback?

**URL:** <https://community.auth0.com/t/async-rule-writing-to-a-database-on-login-directly-call-callback/42541>\
**Category:** Get Help\
**Tags:** rules, auth0\
**Created:** [May 7, 2020, 6:39am UTC](https://community.auth0.com/t/async-rule-writing-to-a-database-on-login-directly-call-callback/42541 "2020-05-07T06:39:58Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![alexab](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/alexab/32/13403_2.png) [@alexab](https://community.auth0.com/u/alexab)\
**Post date:** [May 7, 2020, 6:39am UTC](https://community.auth0.com/t/async-rule-writing-to-a-database-on-login-directly-call-callback/42541/1 "2020-05-07T06:39:59Z")

</div>

Hi Auth0. When we have an async rule, can it run in the background?

My objective is track when users log-in, and therefore write to our Mongo database. The rule currently looks something like this, and waits for the mongodb write operation to complete:

```auto
function (user, context, callback) {
    user.app_metadata = user.app_metadata || {};
    const { MongoClient } = require("mongodb@3.1.4");
    const uri = `mongodb+srv://${dbUser}:${dbPwd}@${dbHost}/admin?retryWrites=true`;
    const client = new MongoClient(uri, { useNewUrlParser: true });

    client.connect(err => {
        if (err) return callback(err);
        const collection = client.db(dbName).collection(colName);
        collection.insert({ // some data })
        .then(() => {
    	    client.close();
			callback(null);      
        })
        .catch((err) => callback(err));
  });
}

```

To improve performance, can we write the rule so we don’t await the write?  
Would something like this work ok - or do I miss something here?

```auto
function (user, context, callback) {
    user.app_metadata = user.app_metadata || {};
    const { MongoClient } = require("mongodb@3.1.4");
    const uri = `mongodb+srv://${dbUser}:${dbPwd}@${dbHost}/admin?retryWrites=true`;
    const client = new MongoClient(uri, { useNewUrlParser: true });

    client.connect(err => {
        if (err) {
            // Log error somewhere - maybe to Auth0 logs?
        };
        const collection = client.db(dbName).collection(colName);
        collection.insert({ // some data })
        .then(() => {
    	    client.close();
        })
        .catch((err) => {
            // Log error somewhere - maybe to Auth0 logs?
        });
    });

    // Callback before connect and write operation is done. Is this ok?
    callback(null, user, context);
}

```

Thanks for your help.

**Update**  
After some googling, I found this sample rule from Auth0 “[Record or update an Intercom User](https://auth0.com/rules/intercom-user)”. And this rule specifically does not wait for the operation to complete, but calls the callback straight away - so that answers part of the question 😀

---

<div class="post-metadata">

**Author:** ![dan.woda](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/dan.woda/32/18340_2.png) [@dan.woda](https://community.auth0.com/u/dan.woda)\
**Post date:** [May 8, 2020, 10:22pm UTC](https://community.auth0.com/t/async-rule-writing-to-a-database-on-login-directly-call-callback/42541/3 "2020-05-08T22:22:26Z")

</div>

Hi @alexab,

As you have discovered, rules do not run async. At this time, there is no hook (async action) for completing this type of request.

You can send the request and move on, like you have mentioned, or you could use a feature like log streaming to build this out manually via logs.

> **[Log Streams](https://auth0.com/docs/customize/log-streams)**
>
> Describes how to export your log events in near real-time using log streaming.

Hope this helps to clarify!

---

<div class="post-metadata">

**Author:** ![alexab](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/alexab/32/13403_2.png) [@alexab](https://community.auth0.com/u/alexab)\
**Post date:** [May 10, 2020, 12:48pm UTC](https://community.auth0.com/t/async-rule-writing-to-a-database-on-login-directly-call-callback/42541/4 "2020-05-10T12:48:16Z")

</div>

Hi Dan.

I am not sure I understand your answer?

If I configure this code to run:

```auto
function (user, context, callback) {
  var moment = require('moment-timezone');

  var data = { // Some data};
  var accessToken = 'YOUR INTERCOM ACCESS TOKEN';

  request.post({
    url: 'https://api.intercom.io/users',
    headers: {
      'Authorization': 'Bearer ' + accessToken,
      'Accept': 'application/json'
    },
    json: data
  }).catch(err => request.post({ // Will this code execute!? })
  callback(null, user, context);
}

```

I’m unsure if the above code in the catch(err) block will execute?

The log streaming sounds like the solution to this specific problem, but we are also working on other rules at the moment 🤓

Now that I have you attention, would you happen to know the answer for [this some-what related question](http://community.auth0.com/t/if-a-rule-in-auth0-calls-the-callback-with-error-will-the-next-continue/42546)?

---

<div class="post-metadata">

**Author:** ![dan.woda](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/dan.woda/32/18340_2.png) [@dan.woda](https://community.auth0.com/u/dan.woda)\
**Post date:** [May 11, 2020, 9:37pm UTC](https://community.auth0.com/t/async-rule-writing-to-a-database-on-login-directly-call-callback/42541/5 "2020-05-11T21:37:48Z")

</div>

Yes, the err function will execute, but the user will have to wait to be logged in until the callback function completes. This can eventually slow things down, since your application will not receive a token until after the rules are finished.

---

<div class="post-metadata">

**Author:** ![dan.woda](https://sea1.discourse-cdn.com/auth0/user_avatar/community.auth0.com/dan.woda/32/18340_2.png) [@dan.woda](https://community.auth0.com/u/dan.woda)\
**Post date:** [May 11, 2020, 9:38pm UTC](https://community.auth0.com/t/async-rule-writing-to-a-database-on-login-directly-call-callback/42541/6 "2020-05-11T21:38:02Z")

</div>

> [@alexab](#):
>
> Now that I have you attention, would you happen to know the answer for [this some-what related question](http://community.auth0.com/t/if-a-rule-in-auth0-calls-the-callback-with-error-will-the-next-continue/42546)?

Sure let me take a look.

---

<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:** [May 26, 2020, 9:44pm UTC](https://community.auth0.com/t/async-rule-writing-to-a-database-on-login-directly-call-callback/42541/7 "2020-05-26T21:44:22Z")

</div>

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