SalesForce and OAuth using Nodejs

Posted on May 20, 2017

SalesForce and OAuth using Nodejs

SalesForce OAuth using Nodejs, which you’ll know enough about after reading this blog, that you can build your own nodejs app to authenticate Salesforce user using OAuth and Nodejs.

Customers are the king! This is an old saying but very true. In today’s market, it can be little hard to put them on centre, but Salesforce helps us in that. It manages your customers in the most efficient and fastest way possible. Salesforce is a Cloud-based Customer-relation Management product. This helps the sales team of any organisation to analyse their customer base and how they can grow the business. Honestly, understanding Salesforce is not that easy and I’m not covering that today. I will be demonstrating you, how we can create a Node app, which will communicate with the SalesForce instance to authenticate SalesForce user.

Why Node

There can be many reasons like Node.js is one of the fastest growing technology, very efficient for creating user side interactivity because of its single-threaded nature, and another reason could be that we’re NodeXperts.

Node is quite popular right now, and there might come a day when you have to implement Salesforce OAuth using Nodejs in your application, then you should know that it’s as easy as eating a pie.

Create SalesForce Connected App

I hope you have a SalesForce account, if not please sign-up. It won’t even take 2 minutes. For OAuth, you must have a connected app. It is an app that connects to SalesForce server over Data APIs and identity.

For creating it, just go in Setup -> App Manager -> Create new connected app and fill the required fields. You must, however, enable the OAuth and fill redirect URI field. That is important because after the user completes the auth process, this is the URL SalesForce will redirect to and you want to get auth code from it. You need auth code to get the access token.

Sounds gibberish!! No worries, here is the flowchart of how this will work.

salesforce oauth2 flow

Once you have created your connected app, note down its consumer key and consumer secret and redirect_url, you’ll be needing those in next few steps.

In redirect URI field, I am passing “http://localhost:3000/getAccessToken”, as I will be creating a route by this name in my app, which runs on port 3000.

Install JSForce

There is an awesome NPM package, named JSForce, which exposes salesforce API. Another way you can do is by calling Salesforce APIs from your app, which is basically some GET/POST requests. But I prefer using modules which wrap these APIs, this not only makes code little secure but also clean.

Simply install it using this command,


npm install --save jsforce

Once installed, you can access this package by


const jsforce = require('jsforce');

Set Up Express Routes

We’re using express here, which is used for creating routes in node apps. Now, we will create routes to get auth code from the redirect_uri of our connected app we created in the previous step.

Before we create routes let’s set our SalesForce keys as environment variables.


# Salesforce
process.env.CLIENT_ID='your_consumer_key'
process.env.CLIENT_SECRET_ID='your_consumer_secret'
process.env.REDIRECT_URI='getAccessToken' // 

Time to create our first route, which will redirect to SalesForce OAuth login page.


app.get('/oauth2/auth', function(req, res) {
  const oauth2 = new jsforce.OAuth2({
    clientId: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET_ID,
    redirectUri: `${req.protocol}://${req.get('host')}/${process.env.REDIRECT_URI}`
  });
  res.redirect(oauth2.getAuthorizationUrl({}));
});

SalesForce OAuth using Nodejs

From this point, Salesforce will handle everything. If user authorises our connected app, then it will redirect the user to the page mentioned in redirect URI which in my case is “http://localhost:3000/getAccessToken”.

Let’s create a route getAccessToken and extract code query from URL and get an access token from salesforce.


app.get('/getAccessToken', function(req,res) {
  const oauth2 = new jsforce.OAuth2({
    clientId: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET_ID,
    redirectUri: `${req.protocol}://${req.get('host')}/${process.env.REDIRECT_URI}`
  });
  const conn = new jsforce.Connection({ oauth2 : oauth2 });
  conn.authorize(req.query.code, function(err, userInfo) {
    if (err) {
      return console.error(err);
    }
    console.log(conn.accessToken, conn.instanceUrl); // access token via oauth2
  });
});

Get Data via OAuth2

Below, I am making some modification in same route, to use access token to get user details.


app.get('/getAccessToken', function(req,res) {
  const oauth2 = new jsforce.OAuth2({
    clientId: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET_ID,
    redirectUri: `${req.protocol}://${req.get('host')}/${process.env.REDIRECT_URI}`
  });
  const conn = new jsforce.Connection({ oauth2 : oauth2 });
  conn.authorize(req.query.code, function(err, userInfo) {
    if (err) {
      return console.error(err);
    }
    const conn2 = new jsforce.Connection({
      instanceUrl : conn.instanceUrl,
      accessToken : conn.accessToken
    });
    conn2.identity(function(err, res) {
      if (err) { return console.error(err); }
      console.log("user ID: " + res.user_id);
      console.log("organization ID: " + res.organization_id);
      console.log("username: " + res.username);
      console.log("display name: " + res.display_name);
    });
  });
});

Just by these two routes, you accomplished:

1. SalesForce OAuth using Nodejs (as I promised in the first line of this post)
2. Get data from salesforce server using access token
3. Securely logged in user without ever saving their credentials

I would highly recommend reading this documentation of jsforce, which helped me a lot. I hope you find this post helpful and please let me know your feedback.