---
schema_version: "1"
id: 17601b57a2c5ffe67f70ce26997d1dc9903c88fbe137fedd9999accde4c0cba0
title: Use Pre-Chat API to Pass Customer Information to the Service Rep in an Experience Site
collection: admin
version: current
locale: en-us
portal_url: https://docs.salesforce.com/admin/current/en-us/service/264-0-0/miaw_pre_chat_api_3.md
canonical_url: https://help.salesforce.com/s/articleView?id=service.miaw_pre_chat_api_3.htm&release=264.0.0&type=5
source_site: help.salesforce.com
content_type: documentation
content_hash: dcdf1dc362c0588db9cefc104384340d5905d5ff9f3a99e31a932a112df04202
description: To provide service reps with customer information that helps move an interaction forward, send end-user data to the service console via the pre-chat API.
products:
  - Service Cloud
  - Digital Engagement
release: "264"
---
# Use Pre-Chat API to Pass Customer Information to the Service Rep in an Experience Site

To provide service reps with customer information that helps move an interaction forward, send end-user data to the service console via the pre-chat API.

### Required Editions

<table class="slds-table slds-table_bordered slds-max-medium-table_stacked slds-m-bottom_small edition">
        <colgroup>
          <col style="width:50%">
          <col style="width:50%">
        </colgroup>
        <tbody>
          <tr class="">
            <td class="slds-cell-wrap" colspan="2" style="vertical-align:top;"><a href="https://help.salesforce.com/s/articleView?id=service.messaging_editions.htm&amp;type=5&amp;language=en_US" target="_blank">View supported editions.</a></td>

          </tr>
          <tr class="">
            <td class="slds-cell-wrap" style="vertical-align:top;">
              <a name="miaw_pre_chat_api_3__d1061e1065"><!-- --></a><span style="vertical-align:text-bottom;display:inline-block;"><img style="margin-bottom:0;" id="miaw_pre_chat_api_3__d1061e1065" src="https://sf-zdocs-cdn-prod.zoominsoftware.com/tdta-service-support_channels-264-0-0-production-enus/f3c4b3d2-ff86-4f7c-9fe2-3d8b23d35109/resources-global/_corporate/images/checkmark.png" alt="Checkmark"></span>
              <strong>This article applies to:</strong>
            </td>

            <td class="slds-cell-wrap" style="vertical-align:top;">Enhanced Web Chat channels</td>

          </tr>
          <tr class="">
            <td class="slds-cell-wrap" style="vertical-align:top;">
              <span style="vertical-align:text-bottom;display:inline-block;"><img style="margin-bottom:0;" src="https://sf-zdocs-cdn-prod.zoominsoftware.com/tdta-service-support_channels-264-0-0-production-enus/f3c4b3d2-ff86-4f7c-9fe2-3d8b23d35109/resources-global/_corporate/images/crossmark.png" alt="X icon"></span>
              <strong>This article doesn’t apply to:</strong>
            </td>

            <td class="slds-cell-wrap" style="vertical-align:top;">Enhanced In-App Chat, Enhanced WhatsApp, Enhanced Facebook Messenger, Standard
              and Enhanced SMS, Enhanced Apple Messages for Business, Enhanced LINE, and Bring Your
              Own Channel</td>

          </tr>
        </tbody>
      </table>

\`

This recipe combines common use cases as examples of data that you can send to service reps using the pre-chat API. First, pass the end user’s login ID to the rep so that verification is done. Then, to prevent loss on large orders, we pass the customer’s shopping cart value to the service rep. To accomplish these goals, create custom hidden pre-chat fields that route the data to Salesforce custom fields via a flow. Then edit the code snippet, telling it to auto-populate the hidden pre-chat fields.

Before building this recipe, consider these caveats.

- You can reference fields from the Messaging Session object or the Messaging User object (because it's linked to Messaging Session) in an auto-response formula template for Start Conversation, End Conversation, and Inactive Conversation. You can’t reference fields from the Messaging Session or Messaging User objects in Conversation
- Salesforce custom object fields are different from pre-chat custom fields. This recipe references both types of fields. [Learn more about the relationship and differences between these two types of fields](https://trailhead.salesforce.com/content/learn/modules/messaging-optimization-for-in-app-and-web/collect-information-to-help-end-users).

1. [Create custom fields on Salesforce objects](https://help.salesforce.com/s/articleView?language=en_US&id=sf.customize_customfields.htm&type=5). In this example, create a Customer ID field and a Shopping Cart Value field on the messaging session or messaging user objects.
2. If your Service Console doesn’t show the object where you stored the fields, [edit the layout](https://help.salesforce.com/s/articleView?language=en_US&id=sf.console_lex_create_custom.htm&type=5) to give service reps easy access. In this example, we edit the Service Console to give easy access to the Messaging Session and Messaging User objects.
3. To capture the data that gets sent to the Salesforce custom fields from step 1, [create hidden pre-chat fields](https://help.salesforce.com/s/articleView?id=service.miaw_custom_prechat_3.htm&language=en_US). In this example, create custom parameters called Customer ID and Shopping Cart Value in Messaging Settings for the channel, and then select them as hidden pre-chat fields in Embedded Services Pre-Chat Form settings.
4. [Map your custom pre-chat fields to your Salesforce custom fields, and then populate the Salesforce fields using a flow](https://help.salesforce.com/s/articleView?id=service.miaw_map_messaging_2.htm&type=5&language=en_US). In this example, we map the pre-chat field called Customer ID to the Salesforce field called Customer ID. Then we map the pre-chat field called Shopping Cart Value to the Salesforce field called Shopping Cart Value. With the flexibility of flows, you can combine or slice data or populate any other objects, such as Case or Contact, as needed.
5. [Create and deploy a custom LWC component](https://trailhead.salesforce.com/content/learn/modules/lightning-web-components-basics/push-lightning-web-component-files) that fetches the user information.
    1. In the newly created custom LWC component folder, here is a template of the custom component.
    2. The .js-meta.xml file.
        
        ```
        <?xml version="1.0" encoding="UTF-8"?>
        <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
           <apiVersion>55.0</apiVersion>
           <isExposed>true</isExposed>
           <masterLabel>[give a component name here]</masterLabel>
           <description>Set logged in User details for Embedded Messaging component</description>
           <targets>
               <target>lightningCommunity__Page</target>
               <target>lightningCommunity__Default</target>
           </targets>
        </LightningComponentBundle>
        ```
    3. The .js file.
        
        ```
        import { LightningElement, wire } from 'lwc';
        import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
        import Id from '@salesforce/user/Id';
        import First_Name from '@salesforce/schema/User.FirstName';
        import Last_Name from '@salesforce/schema/User.LastName';
        import Email from '@salesforce/schema/User.Email';
        
        
        const fields = [First_Name, Last_Name, Email];
        
        
        export default class EmbeddedMessagingSetRecordUser extends LightningElement {
           userId = Id;
           user;
        
        
           @wire(getRecord, { recordId: '$userId', fields })
           wiredRecord({ error, data }) {
               if (error) {
                   let message = "Unknown error";
                   if (Array.isArray(error.body)) {
                       message = error.body.map((e) => e.message).join(", ");
                   } else if (typeof error.body.message === "string") {
                       message = error.body.message;
                   }
                   console.error("Error loading user record:" + message);
               } else if (data) {
                   this.user = data;
                   console.log('before custom event');
                   var selectedEvent = new CustomEvent('userInfo',
                           {
                               detail: {
                                   fname: getFieldValue(this.user, First_Name),
                                   lname : getFieldValue(this.user, Last_Name),
                                   email: getFieldValue(this.user, Email)
                               },
                               bubbles: true,
                               composed: true
                           });
        
        
                   // Dispatches the event.
                   window.dispatchEvent(selectedEvent);
               }
           }
        }
        ```
    4. The .html file.
        
        ```
        <template></template>
        ```
6. In the Experience Site Builder, drag your custom LWC component into the template footer.
7. Go to **Settings → Advanced → Edit Head Markup**, paste the following sample script into the head markup.
    
    ```
    <script>
        var fname, lname, email;
        window.addEventListener('userInfo', function(e){
            console.log("userInfo received");
            fname = e.detail.fname;
            lname = e.detail.lname;
            email = e.detail.email;
        });
        window.addEventListener("onEmbeddedMessagingReady", e => {
            embeddedservice_bootstrap.prechatAPI.setVisiblePrechatFields({
                "_firstName": {
                    "value": fname,
                    "isEditableByEndUser": true
                },
                "_lastName": {
                    "value": lname,
                    "isEditableByEndUser": true
                },
                "_email": {
                    "value": email,
                    "isEditableByEndUser": true
                }
            });
        });
    </script>
    ```
8. [Update your embedded messaging code snippet, instructing it to auto-populate the pre-chat fields that you created in step 2](https://developer.salesforce.com/docs/service/messaging-web/guide/populate-prechat-fields.html). The code in this example uses the Pre-Chat API to send Customer ID and Shopping Cart Value to your pre-chat fields automatically. Before adding to your code snippet, consider these caveats.
    1. The first section of the code contains an example of the standard code snippet for your Embedded Service deployment. Yours looks slightly different due to your unique deployment ID and name.
    2. To complete the recipe, add the code that starts with the comment line `Passing Web Context to Prechat - BEGIN`.
    3. The first section assigns static values to these variables, but you can change them to reflect how you get these values. The next section populates the visible pre-chat fields. The final section populates hidden pre-chat fields.
    4. We use different code settings in assigning the values. For example, the first and last names are locked and not editable by users.
    5. Your page or site template must have the Embedded Messaging component.
    6. An Experience site doesn’t allow you to directly paste in a code snippet. Include Prechat API in the header markup. Add your code at **Experience Builder → Settings → Advanced → Edit Head Markup**.
    7. In the Experience site code sample, we don’t include a baseline code snippet, such as the `initEmbeddedMessaging()` function. That’s because such baseline code is already included in the Embedded Messaging LWC component.
    8. This example includes an event listener on userInfo. This sends a logged-in customer’s information directly to the prechat form without asking the customer to enter it again. The example makes the fields editable by customers. You can also change the isEditableByEndUser configuration to lock it down.