Using Intercom with Express/Passport/NodeJS

Intercom is a really useful tool for chatting with your users, among other things. Part of this means sending some basic user info to Intercom so they know who's talking to you. They give instructions on how to set this up, but only for Rails, Django, and PHP. I'm currently working on a project that uses Express, Node, and Angular, and the below worked for me.

Note that you might want to deal with this in your templating engine (Jade, etc.), but for the sake of having a universal example, and because I find this approach cleaner, this simply returns the desired JS on a request to "yourdomain.tld/intercomJS". I'm already handling templating in Angular, and generally find combining server and client-side templating to be more hassle than it's worth.

Assuming your logged-in user's email is stored as req.user.email (a common PassportJS construct) just pop your app secret and app id from Intercom in to the below:

//you'll need to import crypto, and we assume "app" is your express app
//var crypto = require('crypto');
//var app = express();

app.get('/intercomJS',  
  function(req, res){
    if(req.user){
      // better to use const instead of var in newest versions of nodejs
      var hmac = crypto.createHmac('sha256', 'secret_from_intercom!');
      hmac.update(req.user.email);
      var hmacDigest = hmac.digest('hex');
      var jsString = 'window.intercomSettings = {app_id: "app_id_from_intercom", email: "' + req.user.email + '",  user_hash: "' + hmacDigest + '"  };';
      res.send(jsString);
    } else {
      res.send("Not Logged In, or some JSON that your app uses accordingly");
    }
  });

Then, in your html you'll need to include /intercomJS along with your default Intercom code:

<script>(function(){var w=window.... blah blah blah default intercom widget stuff....lse{w.addEventListener('load',l,false);}}})()</script>  
<script src="/intercomJS"></script>  

On the whole I'm not really crazy about concatenating strings and returning them for your JS - but sometimes it's an effective way to get things done.