Start tracking your progress
Trailhead Home
Trailhead Home

Connect to Salesforce

In this step, you update the app built in the Trailhead project Build Your First Application with Lightning Web Components Open Source by fetching the sessions and speakers data from Salesforce.

For that, you set up a local Express server to connect to your Trailhead Playground, and serve a single endpoint that provides data for the conference management app.

Install Packages

The first step is to install two Node.js packages that will be used for your local development and for connecting and authenticating your Express server to your Trailhead Playground. The two packages are JSForce and Dotenv.

JSForce

JSforce (formerly known as Node-Salesforce) is an isomorphic JavaScript Library utilizing Salesforce’s APIs. It works both in a browser or with Node.js, and mainly it encapsulates the access to various APIs provided by Salesforce in asynchronous JavaScript function calls.

Dotenv

Environment variables help you maintain configurability of the application without modifying the underlying code. Dotenv loads environment variables from a local .env file to allow an easy local development experience.

To install the packages:

  1. Open a terminal window.
  2. Switch into the directory that contains the conference management app.
  3. Run npm install jsforce@^1.0.0 dotenv.

Create the .env File

Next add a local environment file to the conference management app project. This stores authentication information for connecting the Express server to your Salesforce instance.

  1. Download a text editor of your choice. While Salesforce does not provide extensions for Lightning Web Components Open Source, we still recommend you use Visual Studio Code. We will assume VS Code for our future instructions.
  2. Open Visual Studio Code.
  3. Press File > Open.
  4. Select your conference-app folder and click Open. A view of the Conference App in Visual Studio Code.
  5. Press File > New File.
  6. Copy and paste this text into the file.
  7. SF_LOGIN_URL=https://login.salesforce.com
    SF_USERNAME=YOUR_USERNAME
    SF_PASSWORD=YOUR_PASSWORD
    SF_TOKEN=YOUR_SECURITY_TOKEN
  8. Update the placeholder values with your data
  9. SF_USERNAME: Your Trailhead Playground username.
    SF_PASSWORD: Your Trailhead Playground password.
    SF_TOKEN: Your Trailhead Playground security token.
  10. Press File > Save.
  11. Enter .env (with a leading period) as file name. Ensure that the file is saved in the root folder (conference-app). If you see a message showing that file names with a leading period are reserved for system files you can confirm that.

Authenticate to Salesforce

Salesforce supports different types of authentication mechanisms, but for simplicity and the purpose of this project, you use a username and password based login. Next, add code that sets up your Express server to authenticate to your Salesforce instance.

  1. Expand the src folder, then expand the server folder.
  2. Open api.js.
  3. Paste this code before const app = express();:
    const jsforce = require('jsforce');
    require('dotenv').config();
    const { SF_USERNAME, SF_PASSWORD, SF_TOKEN, SF_LOGIN_URL } = process.env;
    if (!(SF_USERNAME && SF_PASSWORD && SF_TOKEN && SF_LOGIN_URL)) {
        console.error(
            'Cannot start app: missing mandatory configuration. Check your .env file.'
        );
        process.exit(-1);
    }
    const conn = new jsforce.Connection({
        loginUrl: SF_LOGIN_URL
    });
    conn.login(SF_USERNAME, SF_PASSWORD + SF_TOKEN, err => {
        if (err) {
            console.error(err);
            process.exit(-1);
        }
    });

  4. Save the file api.js.

This code reads the environment variables from your .env file, and uses them to create an authenticated connection to your Salesforce instance. Next you add some code to fetch data from Salesforce.

Create Endpoint to Read Data from Salesforce

Now that you’ve authenticated to Salesforce, you can start securely accessing Salesforce resources. As mentioned earlier, you create an endpoint that runs the logic to access data. This endpoint can then be used by client-side components.

For this project, you fetch data from Salesforce by running SOQL Queries. SOQL stands for Salesforce Object Query Language, whose syntax closely resembles SQL. It is a Salesforce-specific query language that’s tailored for accessing data within Salesforce. SOQL is also capable of joins, which allows you to fetch related data in a single query.

  1. Expand the folder src, then expand the folder server.
  2. Open the api.js file.
  3. Replace the existing app.get() function block with this code:
    app.get('/api/sessions', (req, res) => {
        const soql = `SELECT Id, Name, toLabel(Room__c), Description__c, format(Date_and_Time__c) formattedDateTime,
            (SELECT Speaker__r.Id, Speaker__r.Name, Speaker__r.Description, Speaker__r.Email, Speaker__r.Picture_URL__c FROM Session_Speakers__r)
            FROM Session__c ORDER BY Date_and_Time__c LIMIT 100`;
        /* Salesforce connection */
    });


    The soql property contains the SOQL statement for querying the session and speaker data from Salesforce. It uses an inner query using the Session Speakers junction object.
  4. Replace the comment /* Salesforce connection */ with this code:
    conn.query(soql, (err, result) => {
        if (err) {
            res.sendStatus(500);
        } else if (result.records.length === 0) {
            res.status(404).send('Session not found.');
        } else {
            /* Work with result data */
        }
    });

    Using the jsforce query method you use the SOQL statement to run that query using the authenticated connection.
  5. Replace the comment /* Work with result data */ with
    const formattedData = result.records.map(sessionRecord => {
        let speakers = [];
        if(sessionRecord.Session_Speakers__r){
            speakers = sessionRecord.Session_Speakers__r.records.map(
                record => {
                    return {
                        id: record.Speaker__r.Id,
                        name: record.Speaker__r.Name,
                        email: record.Speaker__r.Email,
                        bio: record.Speaker__r.Description,
                        pictureUrl: record.Speaker__r.Picture_URL__c
                    };
                }
            );
        }
        return {
            id: sessionRecord.Id,
            name: sessionRecord.Name,
            dateTime: sessionRecord.formattedDateTime,
            room: sessionRecord.Room__c,
            description: sessionRecord.Description__c,
            speakers
        };
    });
    res.send({ data: formattedData });


    The shape of the returned data needs to be mapped to the shape that the API the Express server is expected to serve to the conference management app.
  6. Save the api.js file.

Great! You set up your Express server to authenticate with Salesforce, query data using a SOQL query, and serve the data using a custom endpoint. The next step is to update the User Interface part of the conference management app to use this new endpoint.

Update Data Service with a New Endpoint

  1. Expand the src/client/modules/data/sessionService folder.
  2. Open sessionService.js.
  3. Update the URL variable in the first line with the server endpoint you just created.
  4. const URL = '/api/sessions';
  5. Save sessionService.js.

Build and Test

Now verify that your application is working.

  1. Open the terminal.
  2. Run npm run watch.
    Terminal window showing the server running successfully on port 3001.
  3. Open the browser on http://localhost:3001. The app should now be showing the list of sessions from your Trailhead Playground.
  4. Optionally, to look at the JSON response from the endpoint you created, open the browser on http://localhost:3001/api/sessions.

Congratulations, you’ve successfully created an Express server that consumes data using the Salesforce APIs using an authenticated connection. Check out the next project in this trail, Convert Lightning Web Components Open Source to Salesforce, where you make a few tweaks, and deploy this application on the Salesforce platform. You don’t need to know Salesforce to perform the steps in the next project—we guide you through it.