SkillAgentSearch skills...

Nforce

nforce is a node.js salesforce REST API wrapper for force.com, database.com, and salesforce.com

Install / Use

/learn @kevinohara80/Nforce
About this skill

Quality Score

0/100

Category

Operations

Supported Platforms

Universal

README

THIS REPOSITORY HAS BEEN ARCHIVED

nforce has been archived and is no longer being maintained. Thank you for all of the support and contributions over the years.

It's highly recommended that you migrate to another npm package for Salesforce API integration (like jsforce)


nforce :: node.js salesforce REST API wrapper

Build Status npm version

nforce is node.js a REST API wrapper for force.com, database.com, and salesforce.com.

Features

  • Simple api
  • Intelligent sObjects
  • Helper OAuth methods
  • Simple streaming
  • Multi-user design with single user mode
  • Plugin support

Installation

npm install nforce

Usage

Require nforce in your app and create a client connection to a Salesforce Remote Access Application.

var nforce = require('nforce');

var org = nforce.createConnection({
  clientId: 'SOME_OAUTH_CLIENT_ID',
  clientSecret: 'SOME_OAUTH_CLIENT_SECRET',
  redirectUri: 'http://localhost:3000/oauth/_callback',
  apiVersion: 'v27.0',  // optional, defaults to current salesforce API version
  environment: 'production',  // optional, salesforce 'sandbox' or 'production', production default
  mode: 'multi' // optional, 'single' or 'multi' user mode, multi default
});

Now we just need to authenticate and get our salesforce OAuth credentials. Here is one way to do this in multi-user mode...

// multi user mode
var oauth;
org.authenticate({ username: 'my_test@gmail.com', password: 'mypassword'}, function(err, resp){
  // store the oauth object for this user
  if(!err) oauth = resp;
});

...or in single-user mode...

// single-user mode
org.authenticate({ username: 'my_test@gmail.com', password: 'mypassword'}, function(err, resp){
  // the oauth object was stored in the connection object
  if(!err) console.log('Cached Token: ' + org.oauth.access_token)
});

Now we can go nuts. nforce has an salesforce sObject factory method that creates records for you. Let's use that and insert a record...

var acc = nforce.createSObject('Account');
acc.set('Name', 'Spiffy Cleaners');
acc.set('Phone', '800-555-2345');
acc.set('SLA__c', 'Gold');

org.insert({ sobject: acc, oauth: oauth }, function(err, resp){
  if(!err) console.log('It worked!');
});

If you are in single-user mode, the oauth argument can be ommitted since it's cached as part of your connection object.

org.insert({ sobject: acc }, function(err, resp){
  if(!err) console.log('It worked!');
});

Querying and updating records is super easy. nforce wraps API-queried records in a special object. The object caches field updates that you make to the record and allows you to pass the record directly into the update method without having to scrub out the unchanged fields. In the example below, only the Name and Industry fields will be sent in the update call despite the fact that the query returned other fields such as BillingCity and CreatedDate.

var q = 'SELECT Id, Name, CreatedDate, BillingCity FROM Account WHERE Name = "Spiffy Cleaners" LIMIT 1';

org.query({ query: q }, function(err, resp){

  if(!err && resp.records) {

    var acc = resp.records[0];
    acc.set('Name', 'Really Spiffy Cleaners');
    acc.set('Industry', 'Cleaners');

    org.update({ sobject: acc, oauth: oauth }, function(err, resp){
      if(!err) console.log('It worked!');
    });

  }
});

Using the Example Files

Most of the files in the examples directory can be used by simply setting two environment variables then running the files. The two environment variables are SFUSER and SFPASS which are your Salesforce.com username and passsword, respectively. Example below:

export SFUSER=myusername@salesforce.com
export SFPASS=mypassword
node examples/crud.js

Authentication

nforce supports three Salesforce OAuth 2.0 flows, username/password, Web Server and User-Agent.

Username/Password flow

To request an access token and other oauth information using the username and password flow, use the authenticate() method and pass in your username, password and security token in the options.

Note: A security token can be generated from the Salesforce dashboard under: Account Name > Setup > My Personal Information > Reset My Security Token.

var username      = 'my_test@gmail.com',
    password      = 'mypassword',
    securityToken = 'some_security_token',
    oauth;

org.authenticate({ username: username, password: password, securityToken: securityToken }, function(err, resp){
  if(!err) {
    console.log('Access Token: ' + resp.access_token);
    oauth = resp;
  } else {
    console.log('Error: ' + err.message);
  }
});

The Salesforce website suggests appending the security token to the password in order to authenticate. This works, but using the securityToken parameter as shown above is cleaner. Here's why the security token is necessary, from the Salesforce Website:

The security token is an automatically generated key that must be added to the end of the password in order to log in to Salesforce from an untrusted network. You must concatenate their password and token when passing the request for authentication.

Web Server Code Flow

To perform an authorization code flow, first redirect users to the Authorization URI at Salesforce. nforce provides a helper function to build this url for you.

org.getAuthUri();

An example of using this function in a typical node route would be:

app.get('/auth/sfdc', function(req,res){
  res.redirect(org.getAuthUri());
});

Once you get a callback at the Redirect URI that you specify, you need to request your access token and other important oauth information by calling authenticate() and passing in the "code" that you received.

var oauth;

org.authenticate({ code: 'SOMEOAUTHAUTHORIZATIONCODE' }, function(err, resp){
  if(!err) {
    console.log('Access Token: ' + resp.access_token);
    oauth = resp;
  } else {
    console.log('Error: ' + err.message);
  }
});

An example of using this function in a typical node route and populating the code from the request would be:

app.get('/auth/sfdc/callback', function(req, res) {
  org.authenticate({code: req.query.code}, function(err, resp){
    if(!err) {
      console.log('Access Token: ' + resp.access_token);
    } else {
      console.log('Error: ' + err.message);
    }
  });
});

User-Agent Flow

The user-agent flow simply redirects to your redirectUri after the user authenticates and logs in. The getAuthUri() method can be used similar to the Web Server flow but a responseType property must be set to token.

org.getAuthUri({ responseType: 'token' });

OAuth Object

At the end of a successful authorization, you are returned an OAuth object for the user. This object contains your salesforce access token, endpoint, id, and other information. If you have mode set to multi, cache this object for the user as it will be used for subsequent requests. If you are in single user mode, the OAuth object is stored as a property on your salesforce connection object.

OAuth Object De-Coupling (Multi-user mode)

nforce decouples the oauth credentials from the connection object when mode is set to multi so that in a multi-user situation, a separate connection object doesn't need to be created for each user. This makes the module more efficient. Essentially, you only need one connection object for multiple users and pass the OAuth object in with the request. In this scenario, it makes the most sense to store the OAuth credentials in the users session or in some other data store. If you are using express, nforce can take care of storing this for you (see Express Middleware).

Integrated OAuth Object (Single-user mode)

If you specified single as your mode when creating the connection, calling authenticate will store the OAuth object within the connection object. Then, in subsequent API requests, you can simply omit the OAuth object from the request like so.

// look ma, no oauth argument!
org.query({ query: 'SELECT Id FROM Lead LIMIT 1' }, function(err, res) {
  if(err) return console.error(err);
  else return console.log(res.records[0]);
});

Access Token Auto-Refreshes

nforce provides an optional, built-in function for auto-refreshing access tokens when able it's able to. This requires you are using the web-server flow and you've requested the right scope that returns you a refresh_token. The username/password flow is also supported if using single-user mode.

To enable auto-refreshes, you just need to set the autoRefresh argument when creating your connection...

var nforce = require('nforce');

var org = nforce.createConnection({
  clientId: 'SOME_OAUTH_CLIENT_ID',
  clientSecret: 'SOME_OAUTH_CLIENT_SECRET',
  redirectUri: 'http://localhost:3000/oauth/_callback',
  apiVersion: 'v44.0',
  environment: 'production',
  mode: 'multi',
  autoRefresh: true // <--- set this to true
});

Now when you make requests and your access token is expired, nforce will automatically refresh your access token from Salesforce and re-try your original request...

console.log('old token: ' + oauth.access_token);
org.query({ query: 'SELECT Id FROM Account LIMIT 1', oauth: oauth }, function(err, records){
  if(err) throw err;
  else {
    console.log('query completed with token: ' + oauth.access_token); // <--- if refreshed, this should be different
    res.send(body);
  }
});

NOTE: If you're using express and storing your oauth in the session, if you pa

Related Skills

View on GitHub
GitHub Stars471
CategoryOperations
Updated18d ago
Forks162

Languages

JavaScript

Security Score

100/100

Audited on Mar 8, 2026

No findings