Rule for sending sign-up and log-in analytics events

Hello,

I need to send events to Segment and I used this article as guidance Export Log Events with Rules

However, I encountered a few issues and need experts help.

This is my rule

function(user, context, callback) {
  var Analytics = require('analytics-node');
  var analytics = new Analytics(configuration.SEGMENT_WRITE_KEY, { flushAt: 1 });

  // Note: Set { flushAt: 1 } and use analytics.flush to ensure
  // the data is sent to Segment before the rule/Webtask terminates

  // Identify your user
  analytics.identify({
      userId: user.user_id,
      traits: {
      //email: user.email,
      signed_up: user.created_at,
      login_count: context.stats.loginsCount
    },
    "context": {
      "userAgent": context.request.UserAgent,
      "ip": context.request.ip
    }
  });
  
  var event = (context.stats.loginsCount > 1) ? 'Log In' : 'Sign Up';

  analytics.track({
    userId: user.user_id,
    event: event,
    properties: {
      clientName: context.clientName,
      clientID: context.clientID,
      connection: context.connection
    },
    "context": {
      "userAgent": context.request.UserAgent,
      "ip": context.request.ip
    }
  });
  analytics.flush(function(err, batch){
    callback(null, user, context);
  });
}

The first problem is that in documentation I found two ways of getting user logins count: context.stats.loginsCount and user.logins_count. What’s the difference? Why the user one does not work?

The second problem is that on each login/signup several events are sent. Seems that even logout sends events.

Appreciate your help.
Thanks.

Hey there!

Sorry for such huge delay in response! We’re doing our best in providing you with best developer support experience out there, but sometimes our bandwidth is not enough comparing to the number of incoming questions.

Wanted to reach out to know if you still require further assistance?

No, I decided not to use rules as it too complicated.

Just to answer this question, the context one should be used, the user one might still incorrectly be in the docs, but it’s deprecated. They used to hold the same value though, but it was decided it makes more sense to have it in the context object.