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.
{
"sandboxName": "sandbox1",
"licenseType": "Developer" // put your license type here
}
From the same directory, use the CLI to create a sandbox org.
sf org create sandbox --definition-file config/dev-sandbox-def.json --alias MyDevSandbox --target-org MyProductionOrg
--definition-filepath to sandbox config file--aliasset an alias for your sandbox--target-orgname 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.
note: The Salesforce Functions project you created in the previous step doesn't automatically create a definition file, so you have to create it yourself.
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
sf org login web --alias MySandboxOrgAlias --set-default
--aliasset an alias for the authenticated org--set-defaultset sandbox as default org
Connect to Salesforce Functions
Log in to Salesforce Functions using the CLI.
note: To log in to Salesforce Functions while using sandbox orgs, log in to the associated production org.
sf 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.
sf env create compute -o MySandboxOrgAlias -a MyComputeEnv # use your sandbox org alias
-oAlias of the org the compute environment is connected to-aAlias 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.
export default async function (event, context, logger) {
logger.info(`Invoking salesforcesdkjs function with payload ${JSON.stringify(event.data || {})}`);
// Extract properties from payload
const { name, accountNumber, industry, type, website } = event.data;
// Validate the payload params
if (!name) {
throw new Error(`Please provide account name`);
}
// Define a record using the RecordForCreate type and providing the Developer Name
const account = {
type: "Account",
fields: {
Name: `${name}-${Date.now()}`,
AccountNumber: accountNumber,
Industry: industry,
Type: type,
Website: website,
},
};
try {
// Insert the record using the SalesforceSDK DataApi and get the new Record Id from the result
const { id: recordId } = await context.org.dataApi.create(account);
// Query Accounts using the SalesforceSDK DataApi to verify that your new Account was created.
const soql = `SELECT Fields(STANDARD) FROM Account WHERE Id = '${recordId}'`;
const queryResults = await context.org.dataApi.query(soql);
return queryResults;
} catch (err) {
// Catch any DML errors and pass the throw an error with the message
const errorMessage = `Failed to insert record. Root Cause: ${err.message}`;
logger.error(errorMessage);
throw new Error(errorMessage);
}
}
tip: This code is from Context_SalesforceSDK_JS sample in the functions-recipes GitHub repo.
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:
git init
git add .
git 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.
sf deploy functions -o MySandboxOrgAlias
The deploy process can take several minutes.
To check the status of your deployed project, use sf env list.
sf env list
Outputs:
Salesforce Orgs
============================================================================================================================================
| Aliases Username Org ID Instance Url Auth Method Config
| ─────── ──────────────────────────────────────────────── ────────────────── ─────────────────────────────────── ─────────── ──────────────
| rodriguez.s@salesforce-developers.com 00D3h000000Gr9mEAC https://na111.salesforce.com web
| DevHub rodriguez.s@salesforce.com 00D5e000002URZtEAO https://seb-scr-org.my.salesforce.… web
| d16673… sbudhiraja@d16673dc-20210803-functions-trial.com 00D5e000003TQoSEAW https://d16673dc-20210803-function… web target-dev-hub
| Bob_De… bob@ding.dong 00DB0000000KfREMA0 https://fc2bfda2-20210913-function… web
| Prod_O… alan@ding.dong 00DB0000000KfREMA0 https://fc2bfda2-20210913-function… web
Scratch Orgs
==========================================================================================================================================
| Aliases Username Org ID Instance Url Auth Method Config
| ─────── ───────────────────────────── ────────────────── ──────────────────────────────────────────────────────────── ─────────── ──────
| test-15zzduduspjn@example.com 00D3D000000BJJLUA4 https://mycompany.scratch.my.salesforce.com web
Compute Environments
============================================================================================================
| Alias Project Name Connected Org Alias Connected Org Id Compute Environment Name
| ───────────── ─────────────────────── ─────────────────── ────────────────── ─────────────────────────────
| 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:
<?xml version="1.0" encoding="UTF-8"?>
<PermissionSet xmlns="http://soap.sforce.com/2006/04/metadata">
<hasActivationRequired>true</hasActivationRequired>
<label>Functions</label>
<objectPermissions>
<allowCreate>true</allowCreate>
<allowDelete>false</allowDelete>
<allowEdit>true</allowEdit>
<allowRead>true</allowRead>
<modifyAllRecords>false</modifyAllRecords>
<object>Account</object>
<viewAllRecords>false</viewAllRecords>
</objectPermissions>
</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:
sf project deploy start --ignore-conflicts --target-org MyOrgAlias
Outputs:
Deploying v59.0 metadata to test-1234dbzjb@example.com using the v60.0 SOAP API.
Deploy ID: 0Af6t00000jWn
Status: Succeeded | ████████████████████████████████████████ | 1/1 Components | Tracking: 1/1
Deployed Source
========================================================================================================
| State Name Type Path
| ─────── ───────── ───────────── ──────────────────────────────────────────────────────────────────────
| Created Functions PermissionSet force-app/main/default/permissionsets/Functions.permissionset-meta.xml
note: For more information on syncing project and sandbox org changes, see Develop Against Any Org.
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.