---
schema_version: "1"
id: 1074c2fafb876f1c7391d931254b4dc38efc3aff2d90deb790736da39fc2d585
title: Develop Functions Using Sandbox Orgs
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/salesforce-functions/functions/guide/dev-guide/sandbox-orgs.md
canonical_url: https://developer.salesforce.com/docs/platform/functions/guide/sandbox-orgs.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: 58a1df6628effbfc7526670f5f29377a09e9b5d47c3cf06c8d5e7cf65e6e1506
products:
  - Salesforce Functions
---
# 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](https://help.salesforce.com/s/articleView?id=platform.data_sandbox_create.htm&type=5).

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.

```js
{
  "sandboxName": "sandbox1",
  "licenseType": "Developer" // put your license type here
}
```

From the same directory, use the CLI to create a sandbox org.

```sh
sf 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](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_sandbox_definition.htm) and [Create, Clone, or Delete a Sandbox](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_create_clone_sandboxes.htm).

## 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](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_intro_get_dev_account.htm) documentation for more setup instructions.

### Login and Set an Alias To Your Sandbox Org

```sh
sf 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.

**note:** To log in to Salesforce Functions while using sandbox orgs, log in to the associated production org.

```sh
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.

```sh
sf 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](https://developer.salesforce.com/docs/platform/functions/nodesdk/NODE_README.md) 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.

```javascript
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](https://github.com/trailheadapps/functions-recipes/tree/main/functions/03_Context_SalesforceSDK_JS) in the [functions-recipes GitHub repo](https://github.com/trailheadapps/functions-recipes/).

## 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:

```sh
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](https://docs.github.com/en/get-started/quickstart/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.

```sh
sf deploy functions -o MySandboxOrgAlias
```

The deploy process can take several minutes.

To check the status of your deployed project, use `sf env list`.

```sh
sf env list
```

Outputs:

```sh
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](https://developer.salesforce.com/docs/platform/functions/dev-guide/deploy.md).

## 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
<?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:

```sh
sf project deploy start --ignore-conflicts --target-org MyOrgAlias
```

Outputs:

```sh
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](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_dev_develop_any_org.htm).

## 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](https://developer.salesforce.com/docs/atlas.en-us.sfdx_dev.meta/sfdx_dev/sfdx_setup_enable_source_tracking_sandboxes.htm) for more details.

Follow [Invoke Functions with Apex](https://developer.salesforce.com/docs/platform/functions/guide/invoke-apex.md) for next steps on invoking your function.
