Skip to content

Connect to Salesforce with Node.js

Last updated on November 21, 2022

In this post, we gonna make a connection to Salesforce with Node.js and we will update the Salesforce Objects.

We will use node-salesforce npm module to authenticate with Salesforce. So let’s install it.

Let’s initialize the project npm init --yes and install node-salesforce it as shown below.

$ mkdir salesforceDemo
$ cd salesforceDemo
$ npm init --yes
$ npm install node-salesforce

Once you install the dependency, let’s create a file called index.js (The file name can be anything).

const salesForceLoginUrl = 'https://test.salesforce.com'
const salesForceLoginUser = "login user"
const salesForceAccountPassword = "account password"
const salesForceSecurityToken = "security token"
const sf = require('node-salesforce')

const connect = async () => {
    return new Promise((resolve, reject) => {
        const conn = new sf.Connection({
            loginUrl: salesForceLoginUrl
        })
        conn.login(salesForceLoginUser, `${salesForceAccountPassword}${salesForceSecurityToken}`, function (err, result) {
            if (err) { return reject(err) }
            return resolve(result)
        })
    });
}

(async() => {
   const salesForceConnct = await connect();
   console.log(salesForceConnct)
})()

update the connection settings with your salesforce details. After updating the details you can test your connection by calling node index.js and upon success, you should get a response object with organizationId, id, and URL.

Fetch data from salesforce

const getObject = async(conn, objectName, where) => {
  return new Promise((resolve, reject) => {
    conn.sobject(objectName)
      .find(where)
      .execute(function(err, records) {
        if (err) { return reject(err) }
        return resolve(records)
      });
  });
}
//usage
(async() => {
  try {
   const salesForceConnct = await connect();
   const results = await getObject(salesForceConnct,'ObjectName',{'Id' : '1123455'});
   console.log(results);
  } catch(error) {
    console.log(error.toString());
  }
})()

Update salesforce data

const updateObject = async (conn, objectName, data) => {
  return new Promise((resolve, reject) => {
    conn.sobject(objectName).update(data, function (err, rets) {
      if (err) { return reject(err); }
      return resolve(rets);
    })
  });
}
//usage
(async() => {
  try {
   const salesForceConnct = await connect();
   const results = await updateObject (salesForceConnct,'ObjectName',{'Id' : '1123455', 'Name' :'Arjun'}); // it will update name where ID = 1123455
   console.log(results);
  } catch(error) {
    console.log(error.toString());
  }
})()

To update multiple rows, just send data in the array of objects format.

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments