DEV Community

Sabir Sheikh
Sabir Sheikh

Posted on

πŸ”— Salesforce Integration with JavaScript: Get Access Token & Perform CRUD

Salesforce provides powerful REST APIs that allow developers to interact with Salesforce data from external applications. In this blog, we’ll learn how to:

βœ… Get an Access Token from Salesforce using JavaScript
βœ… Perform CRUD operations (Create, Read, Update, Delete) on Salesforce records
βœ… Test everything in a simple HTML + JS file without extra tools

πŸ› οΈ Prerequisites

Before we start, you’ll need:

  • A Salesforce Developer Org (free: signup here)
  • A Connected App created in Salesforce with OAuth enabled
  • Your Client ID, Client Secret, Username, Password, and Security Token

πŸ”‘ Step 1: Create a Connected App in Salesforce

  1. Go to Setup β†’ App Manager β†’ New Connected App
  2. Enter the following:

OAuth Scopes:
-Full access (full)
-Access and manage your data (api)
-Perform requests on your behalf
(refresh_token, offline_access)

  1. Save β†’ Copy the Client ID and Client Secret

πŸ”‘ Step 2: Get Access Token via JavaScript

Salesforce uses OAuth 2.0 for authentication. In testing, we can use the Password Grant Flow.

Here’s how we request an access token with plain JavaScript:

function getAccessToken() {
  const body = new URLSearchParams({
    grant_type: "password",
    client_id: "YOUR_CLIENT_ID",
    client_secret: "YOUR_CLIENT_SECRET",
    username: "YOUR_SALESFORCE_USERNAME",
    password: "YOUR_PASSWORD_WITH_SECURITY_TOKEN"
  });

  return fetch("https://login.salesforce.com/services/oauth2/token", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: body
  })
  .then(res => res.json())
  .then(data => {
    console.log("Access Token:", data.access_token);
    return data;
  });
}

Enter fullscreen mode Exit fullscreen mode

πŸ”¨ Step 3: Perform CRUD Operations

Once you have the access_token and instance_url, you can interact with Salesforce objects.

Here’s a full HTML + JavaScript example:

<!DOCTYPE html>
<html>
<head>
  <title>Salesforce CRUD Example</title>
</head>
<body>
  <h2>Salesforce CRUD via JavaScript</h2>
  <script>
    const clientId = "YOUR_CLIENT_ID";
    const clientSecret = "YOUR_CLIENT_SECRET";
    const username = "YOUR_SALESFORCE_USERNAME";
    const password = "YOUR_PASSWORD_WITH_SECURITY_TOKEN";
    const loginUrl = "https://login.salesforce.com"; 
    const apiVersion = "v59.0";

    let accessToken = "";
    let instanceUrl = "";

    // 1️⃣ Get Access Token
    function getAccessToken() {
      const body = new URLSearchParams({
        grant_type: "password",
        client_id: clientId,
        client_secret: clientSecret,
        username: username,
        password: password
      });

      return fetch(`${loginUrl}/services/oauth2/token`, {
        method: "POST",
        headers: { "Content-Type": "application/x-www-form-urlencoded" },
        body: body
      })
      .then(res => res.json())
      .then(data => {
        console.log("πŸ”‘ Access Token:", data);
        accessToken = data.access_token;
        instanceUrl = data.instance_url;
        return data;
      });
    }

    // 2️⃣ CREATE
    function createAccount() {
      fetch(`${instanceUrl}/services/data/${apiVersion}/sobjects/Account/`, {
        method: "POST",
        headers: {
          "Authorization": "Bearer " + accessToken,
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          Name: "JS Test Account",
          Phone: "1234567890"
        })
      })
      .then(res => res.json())
      .then(data => {
        console.log("βœ… Account Created:", data);
        getAccount(data.id);
      });
    }

    // 3️⃣ READ
    function getAccount(accountId) {
      fetch(`${instanceUrl}/services/data/${apiVersion}/sobjects/Account/${accountId}`, {
        method: "GET",
        headers: { "Authorization": "Bearer " + accessToken }
      })
      .then(res => res.json())
      .then(data => {
        console.log("πŸ“– Account Data:", data);
        updateAccount(accountId);
      });
    }

    // 4️⃣ UPDATE
    function updateAccount(accountId) {
      fetch(`${instanceUrl}/services/data/${apiVersion}/sobjects/Account/${accountId}`, {
        method: "PATCH",
        headers: {
          "Authorization": "Bearer " + accessToken,
          "Content-Type": "application/json"
        },
        body: JSON.stringify({ Phone: "9876543210" })
      })
      .then(res => {
        if (res.status === 204) {
          console.log("✏️ Account Updated!");
          deleteAccount(accountId);
        } else {
          console.log("❌ Update Failed");
        }
      });
    }

    // 5️⃣ DELETE
    function deleteAccount(accountId) {
      fetch(`${instanceUrl}/services/data/${apiVersion}/sobjects/Account/${accountId}`, {
        method: "DELETE",
        headers: { "Authorization": "Bearer " + accessToken }
      })
      .then(res => {
        if (res.status === 204) {
          console.log("πŸ—‘οΈ Account Deleted!");
        } else {
          console.log("❌ Delete Failed");
        }
      });
    }

    // πŸš€ Run: Login then CRUD
    getAccessToken().then(() => createAccount());
  </script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

πŸ”’ Security Considerations

  • The Password Grant Flow exposes your Salesforce password β†’ only use for testing.
  • For production apps, always use the OAuth Web Server Flow (authorization code).
  • Never commit your Client Secret or Access Token to GitHub.

*🎯 Conclusion
*

  • With just a few lines of JavaScript, you can:
  • Authenticate with Salesforce
  • Create, Read, Update, and Delete records
  • Test your API integration in the browser
  • This approach is perfect for learning, prototyping, or small automation tasks.
  • For production, switch to secure OAuth flows and use server-side code (Node.js, Java, .NET, etc.).

Top comments (0)