Develop Functions Using Sandbox Orgs

You can deploy functions to sandbox orgs for development or testing. Sandbox orgs provide a shared environment for your team to do collaborative Salesforce Functions development and testing.

To create a sandbox org, you can either create it from your DevHub org UI or using the Salesforce CLI.

To create a sandbox using the Salesforce UI, see Create a Sandbox.

When creating a sandbox using the Salesforce CLI, first create a sandbox definition file in your project’s config directory, and then use sf org create sandbox to create the org.

Create a Sandbox Org 

Before you create your sandbox using the Salesforce CLI, create a sandbox definition file in your project’s directory: config/developer-sandbox-def.json. The sandbox definition file is a blueprint for the sandbox.

1{
2  "sandboxName": "sandbox1",
3  "licenseType": "Developer" // put your license type here
4}

From the same directory, use the CLI to create a sandbox org.

1sf org create sandbox --definition-file config/dev-sandbox-def.json --alias MyDevSandbox --target-org MyProductionOrg
  • --definition-file path to sandbox config file
  • --alias set an alias for your sandbox
  • --target-org name of the production org that contains your sandbox licenses

This command starts the sandbox creation process. The process times out after six minutes, but the sandbox org will remain in the creation queue. Make sure the org is fully created in your org’s Setup section before you continue with this guide.

For more information, see Create a Sandbox Definition File and Create, Clone, or Delete a Sandbox.

Connect to Your Sandbox Org 

After creating your sandbox org, you can confirm it’s set up for Salesforce Functions use by logging into your newly created sandbox org and checking the information under Setup > Functions, which should match the Salesforce Functions connection information from your DevHub org.

The Salesforce Functions project you created in the previous step doesn’t automatically create a definition file, so you have to create it yourself.

Note

A sandbox org is a copy of your production org intended for development. Use the Apex Developer Guide: Sandbox Orgs documentation for more setup instructions.

Login and Set an Alias To Your Sandbox Org 

1sf org login web --alias MySandboxOrgAlias --set-default
  • --alias set an alias for the authenticated org
  • --set-default set sandbox as default org

Connect to Salesforce Functions 

Log in to Salesforce Functions using the CLI.

To log in to Salesforce Functions while using sandbox orgs, log in to the associated production org.

Note

1sf login functions

The command sf login functions opens a browser page where you can log in to your Salesforce Functions account. Use the same credentials you used to connect your sandbox’s associated production org.

Create a Compute Environment 

After creating the sandbox org, create a Salesforce compute environment that’s associated with that org. Your functions deploy to this compute environment.

1sf env create compute -o MySandboxOrgAlias -a MyComputeEnv # use your sandbox org alias
  • -o Alias of the org the compute environment is connected to
  • -a Alias for the newly created compute environment

Finish Writing Your Function 

Edit index.js and update your function to match the following example. This function uses the Salesforce Functions SDK for Node.js to insert a new Account record in your scratch or sandbox org. It then queries all Account records with the given fields in the org. The new Account’s name is populated from the name field of the payload.

1export default async function (event, context, logger) {
2  logger.info(`Invoking salesforcesdkjs function with payload ${JSON.stringify(event.data || {})}`);
3
4  // Extract properties from payload
5  const { name, accountNumber, industry, type, website } = event.data;
6
7  // Validate the payload params
8  if (!name) {
9    throw new Error(`Please provide account name`);
10  }
11
12  // Define a record using the RecordForCreate type and providing the Developer Name
13  const account = {
14    type: "Account",
15    fields: {
16      Name: `${name}-${Date.now()}`,
17      AccountNumber: accountNumber,
18      Industry: industry,
19      Type: type,
20      Website: website,
21    },
22  };
23
24  try {
25    // Insert the record using the SalesforceSDK DataApi and get the new Record Id from the result
26    const { id: recordId } = await context.org.dataApi.create(account);
27
28    // Query Accounts using the SalesforceSDK DataApi to verify that your new Account was created.
29    const soql = `SELECT Fields(STANDARD) FROM Account WHERE Id = '${recordId}'`;
30    const queryResults = await context.org.dataApi.query(soql);
31    return queryResults;
32  } catch (err) {
33    // Catch any DML errors and pass the throw an error with the message
34    const errorMessage = `Failed to insert record. Root Cause: ${err.message}`;
35    logger.error(errorMessage);
36    throw new Error(errorMessage);
37  }
38}

This code is from Context_SalesforceSDK_JS sample in the functions-recipes GitHub repo.

Tip

Deploy a Function 

Now that you’ve developed and tested your function locally, deploy your project so you can invoke your function from your Salesforce org. The first time a function project is deployed, the upload can be 500 MB or more.

Add Project to git 

Before you deploy, commit your functions code changes to a git repo. The deploy process uses changes tracked in git to know what to deploy. Since you just created this project, add the project to a new repo.

From the root directory of your project, use the following git commands:

1git init
2git add .
3git commit -m "Initial project commit after project creation"

At this point you can optionally push your changes to github.com, but it isn’t required for deploying functions.

Your project is now ready to deploy. If you make additional changes to your function code, use git add and git commit to commit those changes to the repo before deploying again.

For more details on adding your repo to github.com, see Create a repo.

Deploy Function to Compute Environment 

To deploy your project’s function, use the following command with sandbox org alias we created earlier.

1sf deploy functions -o MySandboxOrgAlias

The deploy process can take several minutes.

To check the status of your deployed project, use sf env list.

1sf env list

Outputs:

1Salesforce Orgs
2============================================================================================================================================
3| Aliases Username                                         Org ID             Instance Url                        Auth Method Config
4| ─────── ──────────────────────────────────────────────── ────────────────── ─────────────────────────────────── ─────────── ──────────────
5|         rodriguez.s@salesforce-developers.com            00D3h000000Gr9mEAC https://na111.salesforce.com        web
6| DevHub  rodriguez.s@salesforce.com                       00D5e000002URZtEAO https://seb-scr-org.my.salesforce.… web
7| d16673… sbudhiraja@d16673dc-20210803-functions-trial.com 00D5e000003TQoSEAW https://d16673dc-20210803-function… web         target-dev-hub
8| Bob_De… bob@ding.dong                                    00DB0000000KfREMA0 https://fc2bfda2-20210913-function… web
9| Prod_O… alan@ding.dong                                   00DB0000000KfREMA0 https://fc2bfda2-20210913-function… web
10
11Scratch Orgs
12==========================================================================================================================================
13| Aliases Username                      Org ID             Instance Url                                                 Auth Method Config
14| ─────── ───────────────────────────── ────────────────── ──────────────────────────────────────────────────────────── ─────────── ──────
15|         test-15zzduduspjn@example.com 00D3D000000BJJLUA4 https://mycompany.scratch.my.salesforce.com                  web
16
17Compute Environments
18============================================================================================================
19| Alias         Project Name            Connected Org Alias Connected Org Id   Compute Environment Name
20| ───────────── ─────────────────────── ─────────────────── ────────────────── ─────────────────────────────
21| Prod_Env_Alan GA_Bug_Bash_Prod_Manual Prod_Org_Alan       00DB0000000KfREMA0 ga-bug-00db0000000kfrema0-203

For more details on deploying projects, see the Salesforce Functions Developer Guide.

Update and Deploy Permissions 

Update a permission set to ensure that the function we create can access data in our Salesforce org. A permission set is a collection of settings and permissions that give users and apps access to various tools and data in Salesforce.

Update the Functions Permission Set 

When you connect your org to Salesforce Functions via the Functions Setup page, Salesforce creates a Functions permission set with minimal permissions. Update that permission set to give your function access to the Account object.

To update the functions permission set, add the file force-app/main/default/permissionsets/Functions.permissionset-meta.xml, with contents:

1<?xml version="1.0" encoding="UTF-8"?>
2<PermissionSet xmlns="http://soap.sforce.com/2006/04/metadata">
3    <hasActivationRequired>true</hasActivationRequired>
4    <label>Functions</label>
5    <objectPermissions>
6        <allowCreate>true</allowCreate>
7        <allowDelete>false</allowDelete>
8        <allowEdit>true</allowEdit>
9        <allowRead>true</allowRead>
10        <modifyAllRecords>false</modifyAllRecords>
11        <object>Account</object>
12        <viewAllRecords>false</viewAllRecords>
13    </objectPermissions>
14</PermissionSet>

These permissions allow a running function in a compute environment connected to your org to access the Account object.

Deploy the Functions Permission Set 

Use project deploy start with the --ignore-conflicts flag to deploy your changes to the functions permission set to your scratch org:

1sf project deploy start --ignore-conflicts --target-org MyOrgAlias

Outputs:

1Deploying v59.0 metadata to test-1234dbzjb@example.com using the v60.0 SOAP API.
2Deploy ID: 0Af6t00000jWn
3Status: Succeeded | ████████████████████████████████████████ | 1/1 Components | Tracking: 1/1
4
5Deployed Source
6========================================================================================================
7| State   Name      Type          Path
8| ─────── ───────── ───────────── ──────────────────────────────────────────────────────────────────────
9| Created Functions PermissionSet force-app/main/default/permissionsets/Functions.permissionset-meta.xml

For more information on syncing project and sandbox org changes, see Develop Against Any Org.

Note

Enable Source Tracking for Sandboxes 

When developing functions with multiple contributors, sync your team’s changes by using Enable Source Tracking in Developer and Developer Pro Sandboxes. See Enable Source Tracking in Sandboxes for more details.

Follow Invoke Functions with Apex for next steps on invoking your function.

Product Retirement Announcement

Salesforce Functions is no longer available for purchase or renewal. To preserve the capabilities that Salesforce Functions provided to your org, deploy an alternative solution before your existing order term ends. See Salesforce Functions Retirement for more information on migrating your functions. Contact your Salesforce Account Executive for more information on Heroku.