Getting Started

Start app development using JSforce

Overview

JSforce (f.k.a. Node-Salesforce) is a isomorphic JavaScript Library utilizing Salesforce's API: It works both in browser and with Node.js.

It capsulates the access to various APIs provided by Salesforce in asynchronous JavaScript function calls.

Unlike other Salesforce API libraries, it is intended to give integrated interface both server-side and client-side apps, so you don't have to rewrite similar logics with different libraries only for running in different environment.

Additionally, it has useful command line interface (CLI) which gives interactive console (REPL), so you can learn the usage without hassle.

Supported APIs

Setup

Node.js

If you want to use JSforce as an API library in your Node.js project, install it via npm.

$ npm install jsforce

NOTE: the jsforce npm package includes the browser bundles + minified builds, TS source code and other deps that will not be used in a Node.js environment. For these cases we provide a slim, node-only package that strips these artifacts and deps.

$ npm install @jsforce/jsforce-node

Aside from being smaller, there's no API differences between jsforce and jsforce-node.

When you installed JSforce, you can import using require('jsforce') in your Node.js application code.

const jsforce = require('jsforce');
const conn = new jsforce.Connection();

Details for establishing API connection are written in the document and options are in API reference.

Web Browser

If you want to use JSforce in web browser JavaScript, download JSforce JS library and put it on any path in your website, and include in <script> tag:

<script src="/path/to/jsforce.js"></script>

Or you can use public CDN to include script directly to your web site.

<script src="https://cdn.jsdelivr.net/npm/jsforce@3.2.2/dist/jsforce.min.js"></script>

When the script is loaded, jsforce object will be defined in global root.

As the jsforce.js file is all-in-one library, it includes all objects for each Salesforce APIs. You might prefer to use only core module and some specific API module to reduce total footprint size to load. You can use jsforce-core.js file which includes core function only, and include each API scripts to use in your app.

<script src="/path/to/jsforce-core.min.js"></script>
<script src="/path/to/jsforce-api-bulk.min.js"></script>
<script src="/path/to/jsforce-api-chatter.min.js"></script>

If your app is located outside of Salesforce domain (that is, non-Visualforce app), you need to register your app as "Connected App" in Salesforce.

Web app pages which use JSforce should be initialized with the application information. In following initizalization code, you can see it is passing OAuth2 client ID information, so first you have to register your app as an OAuth2 client to get client ID. You must provide callback URL information (used as OAuth2 redirect URI) in registration, which must be in the same origin of your web app.

<script src="/path/to/jsforce.js"></script>
<script>
jsforce.browser.init({
  clientId: '[your OAuth2 client ID]',
  redirectUri: '[your OAuth2 redirect URI]'
});

// ...

</script>

Note that the page in callback URL also have to include JSforce initialization code. The content of callback page can be empty, because it will not be used except for API authorization.

Additionally, you may need jsforce-ajax-proxy if the app resides outside of Salesforce (that is, non-Visualforce environment).

jsforce.browser.init({
  clientId: '<your OAuth2 client ID>',
  redirectUri: '<your OAuth2 redirect URI>',
  proxyUrl: 'https://your-jsforce-proxy-server.herokuapp.com/proxy/'
});

To enforce users to login, you can call jsforce.browser.login() to start OAuth2 authorization flow by popping up window. Afterward you can get authorized API connection by listening connect event on jsforce.browser object.

jsforce.browser.on('connect', function(conn) {
  const res = await conn.query('SELECT Id, Name FROM Account')
  console.log(res);
});

Visualforce

If you are writing HTML5 apps on Visualforce, API access token is automatically obtained as session ID. You can just pass it to Connection constructor to initialize. Also you can use static resources to upload JSforce JavaScript file to include.

<apex:page docType="html-5.0" showHeader="false">
  <apex:includeScript value="{!URLFOR($Resource.JSforce)}" />
  <script>
const conn = new jsforce.Connection({ accessToken: '{!$API.Session_Id}' });
const res = await conn.query('SELECT Id, Name FROM Account');
console.log(res);
// ...

  </script>

</apex:page>

Salesforce Canvas

You can also use JSforce in Salesforce Canvas app. In order to create authorized API connection, pass signed request JSON value to Connection constructor

Note that the signed request value must be validated in server-side before passing to JSforce. Also you have to load canvas JS SDK officially provided from Salesforce.

<!DOCTYPE html>
<html>
<head>
  <meta id="sf-canvas-signed-request" content="<%= verifiedSignedRequestJSON %>" />
  <script src="https://login.salesforce.com/canvas/sdk/js/42.0/canvas-all.js"></script>
  <script src="/js/jsforce.js"></script>
  <script>
let sr = document.getElementById('sf-canvas-signed-request').content;
const conn = new jsforce.Connection({ signedRequest: sr });
const res = await conn.query('SELECT Id, Name FROM Account');
console.log(res);

//...

  </script>
</head>
<body></body>
</html>

Basic Usage

When you established the connection, you can call APIs defined in connection object.

By JavaScript's nature, all API calls are done asynchronously.

Command Line Interface

There is a Command Line Interface (CLI) which works on tty. To use JSforce CLI, install npm package globally.

$ npm install jsforce -g

After the install, jsforce command will be available in your path.

$ jsforce --help

  Usage: jsforce [options]

  Options:

    -h, --help                     output usage information
    -u, --username [username]      Salesforce username
    -p, --password [password]      Salesforce password (and security token, if available)
    -c, --connection [connection]  Connection name stored in connection registry
    -e, --evalScript [evalScript]  Script to evaluate
    --coffee                       Using CoffeeScript

When you just type jsforce, it enters into REPL mode. In the REPL environment, default connection object in the context is exposed, so you don't need to instantiate connection object.

$ jsforce
> login('user@example.org', 'password123');
{ id: '00550000000vwsFAAQ',
  organizationId: '00D500000006xKGEAY',
  url: 'https://login.salesforce.com/id/00D500000006xKGEAY/00550000000vwsFAAQ' }
>

To login to Salesforce, type .connect with username.

> .connect user@example.org
Password: ********
Logged in as : username@example.org
>

The established session information is stored in ~/.jsforce/config.json file, so you can connect without password while the session is valid.

$ jsforce -c user@example.org
Logged in as : user@example.org
>

By passing a script in -e option, it automatically evaluate the script and returns result in JSON.

$ jsforce -c user@example.org -e "query('SELECT Id, Name FROM Account LIMIT 1')"
{"totalSize":1,"done":true,"records":[{"attributes":{"type":"Account","url":"/services/data/v29.0/sobjects/Account/0015000000KBQ5GAAX"},"Id":"0015000000KBQ5GAAX","Name":"United Oil"}]}

In order to authorize the connection via OAuth2 authorization flow, type .authorize in REPL mode. It will popup browser and start flow for API access authorization.

> .authorize

Note that you need to register your OAuth2 client information before start OAuth2 authorization. The .register command will navigate the registration. In order to accomplish authorization flow successfully, the redirect URL of registering client must be http://localhost:<port>.

> .register
Input client ID (consumer key) : <your client id>
Input client secret (consumer secret) : <your client secret>
Input redirect URI : <your client redirect uri>
Input login URL (default is https://login.salesforce.com) :
Client registered successfully.

If you are connecting to sandbox instance or other environment with different login servers (e.g. pre-release environment), you can specify login server by -l <loginServerUrl>.

$ jsforce -l https://test.salesforce.com

If you are connecting to sandbox, you can also use following :

$ jsforce -l sandbox

or

$ jsforce --sandbox