You can connect to Salesforce from Node.js using Devart ODBC Driver for Salesforce.
Run the following command to install the odbc
package.
npm install odbc
An ODBC connection requires a connection string, which can either use a predefined DSN or be specified through connection string parameters (a DSN-less connection).
For information about available parameters, see Connection string parameters.
You can use a connection string with a predefined DSN.
const connectionString = 'DSN=your_dsn';
If you need credentials other than those used in the DSN, specify them in the connection string to override the DSN values.
const connectionString = 'DSN=your_dsn;User ID=your_username;Password=your_password';
For information on configuring a DSN on specific operating systems, see instructions for Windows, macOS, or Linux.
You can establish a connection without a DSN by specifying all necessary parameters directly in the connection string.
The following example uses OAuth 2.0 authentication.
const connectionString = 'DRIVER=Devart ODBC Driver for Salesforce;Authentication=OAuth;Refresh Token=your_refresh_token';
For more information, see DSN-less connections.
The following Node.js code demonstrates how to connect to Salesforce and fetch data using the ODBC driver.
const odbc = require('odbc');
// Define an async function to connect to a data source and execute an SQL query
async function connectToSalesforceAndQuery() {
// Declare a variable to hold the ODBC connection
var connection;
try {
// Define an ODBC connection string
const connectionString = 'your_connection_string';
// Create an object that represents a connection to a data source
connection = await odbc.connect(connectionString);
// Execute an SQL query to retrieve data from the data source
const result = await connection.query('SELECT Id, Name FROM Account LIMIT 10');
// Print the query results
console.log('Salesforce Data:', result);
// You can integrate this data into your app logic here
// Example: Save the result to your application's database or display it on the UI
} catch (error) {
// Handle any errors
console.error('Error connecting to Salesforce via ODBC:', error);
} finally {
// Ensure the connection is closed to free resources
if (connection) {
await connection.close();
}
}
}
// Call the function as part of your application's workflow
connectToSalesforceAndQuery();