What's the proper way to monitor for session timeout and automatically get a new session using node-salesforce?


Building a basic node.js app on heroku. Using the OAuth2 Resource Owner Password Credential flow to login. Eventually the session expires and being a node.js noob, I'm not exactly sure how I should be setting this up to check the session and update it if it's invalid. Doing I just fail the method call and instead get a new token and hope the end result isn't totally weird to the end user or result in data integrity issues? Should I be using a totally different OAuth flow? ( All the Salesforce oauth docs says to avoid the username pass flow, but I don't understand what else you would use for an autonomous server). Should I just ditch OAuth completely and do a login on EVERY call?


Initialize Salesforce Connection

var sf = require('node-salesforce');

var salesforce_username = process.env.SALESFORCE_USERNAME,
    salesforce_password = process.env.SALESFORCE_PASSWORD;

var oauth_options = {
  loginUrl : process.env.SALESFORCE_LOGIN_URL,
  clientId : process.env.SALESFORCE_CONSUMER_KEY,
  clientSecret : process.env.SALESFORCE_CONSUMER_SECRET,
  redirectUri : process.env.SALESFORCE_CALLBACK_URL

var salesforceConnection = new sf.Connection({oauth2 : oauth_options});
salesforceConnection.login(salesforce_username, salesforce_password, function(err, userInfo) {
  if (err) { return console.error(err); }


function getClientSites(callback) { 
  salesforceConnection.sobject('Account').select('*')execute(function(err, results) {
    if (err) console.error(err);  // <-- failing here when the session expires

1 Answer 1


There is no automatic session refresh within node-salesforce when you use the password flow. In connection.js:215 it will refresh the session if the session has expired but only if you using the access_token and refresh_token instead, not password.

If you have to use password, you could catch the error returned by the 401 status code in connection.js:247 and use the login or initialization function to refresh the session.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .