Sub topic 9
Create a scratch org
This chapter shows you how to create a scratch org from a definition file, how it relates to the Dev Hub, and how to work with it afterward. It assumes you can log in to an org with sf org login web, set a default target org, and work inside a Salesforce DX project (the earlier chapters cover these). You also need a Dev Hub org, which the next section explains.
What a scratch org is
A scratch org is a temporary Salesforce org that you create from a configuration file. It starts empty, apart from the features and settings you request. You deploy your project source into it, test your changes, and delete it when you finish.
Scratch orgs differ from sandboxes in several ways:
- They are built from source and a definition file, so you can recreate the same org at any time.
- They are short-lived. The duration can be 1 to 30 days, and the default is 7 days. When the org expires, Salesforce deletes it.
- They contain no production data unless you load it yourself.
- Each one is created by a Dev Hub org, which tracks it and applies limits.
Because they are disposable, scratch orgs suit feature development, automated testing, and continuous integration (CI) jobs. Each run can start from a known, clean state.
The Dev Hub
A Dev Hub is a Salesforce org that has the Dev Hub feature enabled. It creates scratch orgs and keeps a record of them. You do not create scratch orgs in the org you are developing against. You ask the Dev Hub to create them.
To use a Dev Hub:
- Enable Dev Hub in the org. In Setup, search for Dev Hub and turn it on. Developer Edition orgs and production orgs can be Dev Hubs. Once enabled, the setting cannot be turned off.
- Authorize the Dev Hub from the CLI with the
--set-default-dev-hubflag.
sf org login web --alias devhub --set-default-dev-hubThis works like the login in the authorization chapter, with one difference. The CLI saves this org as your default Dev Hub. It is stored in the target-dev-hub configuration variable. This is separate from target-org, which holds your default working org.
You can also set it afterward:
sf config set target-dev-hub devhubKeeping the two defaults separate lets you point commands at a scratch org while the Dev Hub stays available for creating more.
The definition file
A scratch org definition file is a JSON file that describes the org you want. By convention it lives in config/project-scratch-def.json inside your project. The sf project generate command normally creates this file for you.
A minimal file looks like this:
{
"orgName": "Demo scratch org",
"edition": "Developer"
}The two keys have these roles:
orgNameis the company name shown in the org.editionis the Salesforce edition to create, for exampleDeveloper,Enterprise,Group, orProfessional.
Definition files support more keys. You will meet these often:
| Key | Purpose |
|---|---|
| `features` | A list of features to enable, such as `EnableSetPasswordInApi` or `Communities`. |
| `settings` | Org settings, written in the same shape as the Metadata API settings types. |
| `country` | The default country for the org. |
| `language` | The default language. |
| `description` | Free text that helps you remember the purpose of the org. |
A definition file that enables a feature and a setting could look like this:
{
"orgName": "Demo scratch org",
"edition": "Developer",
"features": ["EnableSetPasswordInApi"],
"settings": {
"lightningExperienceSettings": {
"enableS1DesktopEnabled": true
}
}
}Feature names and setting names must match what Salesforce supports. A misspelled feature name causes the creation command to fail, so copy names from the Salesforce documentation instead of typing them from memory.
Create the scratch org
From your project directory, run the creation command:
sf org create scratch --definition-file config/project-scratch-def.json --alias myscratch --duration-days 7 --set-defaultThe flags do the following:
| Flag | Meaning |
|---|---|
| `--definition-file` | The path to the JSON definition file. |
| `--alias` | A short name you can use in later commands instead of the generated username. |
| `--duration-days` | How many days the org lives before it is deleted. |
| `--set-default` | Saves the new org as your default target org (`target-org`). |
The command sends a request to the Dev Hub, waits while Salesforce builds the org, then authorizes it locally. Creation commonly takes a minute or more. When it finishes, the CLI prints the org ID and the generated username.
You do not need to log in separately. The Dev Hub hands the CLI the credentials it needs, and the CLI stores them like any other authorized org.
The creation command also accepts --wait to set how many minutes the CLI waits before giving up. If the wait ends first, the org may still finish building. In that case you can check its status with sf org list.
How the pieces fit together
The sequence below shows who talks to whom when you create a scratch org.
Use the new org
Because you passed --set-default, commands without a target now run against the scratch org. Confirm it:
sf org display
sf org listsf org display shows the username, org ID, instance URL, and alias of the default org. sf org list shows all orgs the CLI knows about. The scratch org appears with its expiration date, and the Dev Hub is marked as such.
Next, deploy your project source into it. This is the typical first step after creation:
sf project deploy start --source-dir force-appYou can open the org in a browser without a password:
sf org openTo target the scratch org explicitly, instead of relying on the default, use the --target-org flag with the alias:
sf data query --query "SELECT Id, Name FROM Account LIMIT 5" --target-org myscratchLink the definition file to the project
Your sfdx-project.json file does not store the definition file path. The scratch org definition file is supplied on the command line each time. Teams usually keep it in version control with the rest of the project and always use the same path. Doing so means everyone who creates a scratch org gets the same shape.
Some teams also write a script that creates the org, deploys source, assigns permission sets, and loads sample data. Since each step is a CLI command, the script can be run again whenever you need a fresh org.
Delete a scratch org
Scratch orgs delete themselves when their duration ends. You can also remove one sooner to free capacity:
sf org delete scratch --target-org myscratch --no-promptWithout --no-prompt, the CLI asks you to confirm. Deleting a scratch org removes its data and any changes you made that you did not retrieve. Retrieve or commit anything you want to keep first.
Limits and common errors
The Dev Hub enforces limits on how many scratch orgs you can create. Two limits matter in practice:
- A daily limit on how many scratch orgs can be created in 24 hours.
- An active limit on how many can exist at the same time.
You can check your remaining allocation with:
sf limits api display --target-org devhubThe output includes DailyScratchOrgs and ActiveScratchOrgs, each with a maximum and a remaining count. The actual numbers depend on the Dev Hub's edition.
Errors you are likely to see:
| Symptom | Likely cause | Fix |
|---|---|---|
| No default Dev Hub found | `target-dev-hub` is not set. | Run `sf config set target-dev-hub devhub`, or pass `--target-dev-hub`. |
| Invalid feature or setting | A name in the definition file is misspelled or unsupported. | Check the name against the Salesforce documentation. |
| Limit exceeded | The daily or active scratch org limit is used up. | Delete unused scratch orgs, or wait for the 24-hour window to pass. |
| Definition file not found | The path is wrong relative to your current directory. | Run the command from the project root, or use a full path. |
| Command not enabled | The org you authorized is not a Dev Hub. | Enable Dev Hub in Setup, then authorize again. |
Scratch org alternatives
Scratch orgs are not the only way to get a development org. Here is how they compare.
| Option | Strength | Limitation |
|---|---|---|
| Scratch org | Reproducible, disposable, source-driven. | Needs a Dev Hub, has limits, and expires. |
| Developer sandbox | Copies metadata from production. | Slower to refresh, and does not start from source. |
| Developer Edition org | Free and permanent. | Hard to reset to a known state. |
Choose a scratch org when you want a repeatable setup for each feature or CI run. Choose a sandbox when you need to work against an existing production configuration.
Exercise
You run sf org create scratch --definition-file config/project-scratch-def.json --alias feature1 and the CLI reports that it cannot find a default Dev Hub. Name two ways to fix this, and say which configuration variable differs from the one that holds your working org.
Show answer
Either authorize the Dev Hub with sf org login web --alias devhub --set-default-dev-hub, or set it with sf config set target-dev-hub devhub. You can also pass --target-dev-hub devhub on the creation command. The variable is target-dev-hub. The working org is stored in target-org.
Exercise
A teammate says a scratch org they created last week is gone, and the changes they made in it are lost. What most likely happened, and what should they have done?
Show answer
The org passed its duration (7 days by default) and Salesforce deleted it. Before it expired, they should have retrieved their changes with sf project retrieve start and committed the source to version control.