Sub topic 4
Scratch Orgs and the Dev Hub
A scratch org is a disposable Salesforce org that you create from a configuration file and discard when the work is done. Every scratch org belongs to a parent org called the Dev Hub. This chapter covers how the two relate, how to authorize a Dev Hub, how to create and use a scratch org with the Salesforce CLI, and what usually goes wrong. The next chapters cover the definition file in detail, source tracking, and limits. This chapter uses only a small definition file.
Prerequisites
This chapter assumes you can:
- Tell production from non-production orgs.
- Deploy metadata between orgs.
- Run commands in a terminal.
- Use Git for basic version control.
You also need the Salesforce CLI (sf) installed, plus a Salesforce DX project folder that contains an sfdx-project.json file.
What a scratch org is
A scratch org is a fully functional Salesforce org with these traits:
- It starts nearly empty. It does not copy metadata or data from production. It gets only the features, edition, and settings you request, plus whatever source you deploy into it.
- It is short-lived. It expires automatically after a set number of days. The default is 7 and the maximum is 30.
- It is created on demand. Creation usually takes a few minutes, so you can make one per feature branch, per test run, or per demo.
- It is described by files. Because the configuration lives in version control, anyone on the team can recreate the same org.
A sandbox is the opposite on each point. It is a copy of production, it is long-lived, and it is refreshed instead of recreated. That difference drives the choice between the two, which a later chapter covers.
The Dev Hub
The Dev Hub is the org that owns and tracks your scratch orgs. You don't develop in it. It does three jobs:
- Authorization. The CLI asks the Dev Hub to create a scratch org. Only users the Dev Hub allows can do this.
- Allocation. The Dev Hub's edition and licenses decide how many scratch orgs can exist and be created per day. The limits chapter covers the numbers.
- Record keeping. The Dev Hub stores a record for each scratch org, so an admin can see who created what and when it expires.
You can enable Dev Hub in a production org or in a Developer Edition org. Enabling it in production is common because the team's licenses and limits come from there. It does not expose production data to scratch orgs, because scratch orgs never copy it. A Developer Edition org works for learning or personal projects.
Enabling and authorizing
To enable Dev Hub, an administrator opens Setup, searches for Dev Hub, and turns on the setting. Two points matter:
- You can't turn the setting off once it is on.
- Each user who creates scratch orgs needs permission in the Dev Hub to create and delete them. An admin grants this through a permission set.
Then each developer authorizes the CLI against the Dev Hub once:
sf org login web --set-default-dev-hub --alias devhubThis opens a browser login. After you sign in, the CLI stores the credentials locally under the alias devhub. The --set-default-dev-hub flag makes this org the default for scratch org commands, so you don't pass --target-dev-hub each time.
Creating a scratch org
A scratch org needs a definition file. This minimal one sets a name, an edition, and one setting. Save it as config/project-scratch-def.json:
{
"orgName": "Acme Development",
"edition": "Developer",
"hasSampleData": false,
"settings": {
"lightningExperienceSettings": {
"enableS1DesktopEnabled": true
}
}
}The hasSampleData value controls whether the org includes sample records. It is false here, so the org starts without them. The next chapter covers the other keys.
A DX project also needs an sfdx-project.json at its root. This minimal version is enough:
{
"packageDirectories": [
{ "path": "force-app", "default": true }
],
"sfdcLoginUrl": "https://login.salesforce.com"
}With both files in place, this sequence runs the whole scratch org cycle:
sf org login web --set-default-dev-hub --alias devhub
sf org create scratch --definition-file config/project-scratch-def.json --alias my-scratch --duration-days 7 --set-default
sf project deploy start
sf org open
sf org delete scratch --target-org my-scratch --no-promptEach line does one thing:
- Line 1 authorizes the Dev Hub, as above.
- Line 2 asks the Dev Hub to create a scratch org from the definition file.
--aliasgives it a short name.--duration-days 7sets the expiration.--set-defaultmakes it the default target for later commands. - Line 3 deploys the source in your project's package directories to the default org, which is now the scratch org.
- Line 4 opens the scratch org in a browser, already logged in.
- Line 5 deletes the org when you are finished.
--no-promptskips the confirmation question, which is useful in scripts and risky when typed by hand.
What happens during creation
When you run sf org create scratch, the CLI doesn't build the org. It sends a request to the Dev Hub, which creates the org and returns its login details.
The request is recorded in the Dev Hub as a ScratchOrgInfo record. While the org is alive, an ActiveScratchOrg record also exists. The record has a status such as New, Active, Deleted, or Error. If creation fails, the status and error details are on the record, which helps when the CLI message is vague.
The CLI generates the scratch org's username automatically. It looks like an email address and is unique across Salesforce. The scratch org has no password until you ask for one:
sf org generate password --target-org my-scratch
sf org display --target-org my-scratch --verbosesf org display prints the username, org ID, instance URL, and expiration date. Add --verbose to see the password and the login URL when one has been generated. Treat that output as a secret and don't paste it into tickets or chat.
Working in a scratch org
After creation you do the same things as in any org, with two habits that differ:
- Treat the org as a build output. The source of truth is your Git repository and the definition file, not the org. Anything you build by clicking in Setup disappears at expiration unless you retrieve it into source. Use
sf project retrieve startto pull changes into your project. Source tracking, covered later, makes this easier. - Recreate instead of repair. If a scratch org gets into a strange state, delete it and create a fresh one. That takes minutes and removes drift.
Seeing which scratch orgs you have is a common need:
sf org listThis lists the orgs your CLI knows about, with aliases and status. To see what the Dev Hub itself has recorded, including orgs created by teammates or CI, query it:
sf data query --target-org devhub --query "SELECT Id, SignupUsername, ExpirationDate FROM ActiveScratchOrg"An admin can run the same query to find scratch orgs that still consume allocation.
Scratch org and sandbox compared
The table below summarizes the differences that matter at the Dev Hub level. Later chapters cover the decision in more depth.
| Aspect | Scratch org | Sandbox |
|---|---|---|
| Created from | A definition file, through a Dev Hub | A copy of a source org, usually production |
| Starting metadata | Only what the definition and your deployment provide | Production's metadata |
| Starting data | None, or sample data if requested | Depends on sandbox type |
| Lifespan | Expires after 1 to 30 days | Persists until deleted |
| How you reset it | Delete and recreate | Refresh |
| Typical owner | One developer or one CI run | A team or a stage in a pipeline |
Common errors
Most first-time failures fall into a few groups:
| Symptom | Likely cause | Fix |
|---|---|---|
| The CLI says no default Dev Hub is set | You authorized the Dev Hub without `--set-default-dev-hub`, or on another machine | Re-run the login with the flag, or pass `--target-dev-hub devhub` |
| The create command is rejected for permissions | Your user lacks the permission to create scratch orgs in the Dev Hub | Ask an admin to grant it through a permission set |
| Creation fails because a limit is reached | The Dev Hub has too many active scratch orgs, or too many were created today | Delete unused orgs, or wait for the daily allocation to reset |
| Creation fails with an error about a setting or feature | The definition file has a misspelled key or an unsupported value | Check the `ScratchOrgInfo` record and the definition file |
| Deployment fails on a missing feature | The source needs a feature or license the definition file doesn't enable | Add it to the definition file and recreate the org |
| A command acts on the wrong org | `--set-default` moved the default to a new org | Pass `--target-org` explicitly in scripts |
Summary of the model
- The Dev Hub is the org that creates, allocates, and tracks scratch orgs. You authorize it once with
sf org login web --set-default-dev-hub. - A definition file plus your project source fully describes a scratch org. The org itself is disposable.
- Creation is a request to the Dev Hub, recorded as
ScratchOrgInfo. The CLI stores the resulting credentials locally. - Most problems come from the default org, missing permissions, Dev Hub limits, or a definition file that doesn't match what the source needs.
Exercise
A teammate runs sf org create scratch --definition-file config/project-scratch-def.json --alias feature-42 --set-default, then sf project deploy start, and later says the deploy went to the wrong org. They had a second scratch org, feature-41, open in another terminal. What is the most likely cause, and what two practices prevent it?
Show answer
Each --set-default or equivalent sf setting changes which org is the default target. If the teammate's project-level default pointed at feature-41, or the default was changed by another command, sf project deploy start used that org. Prevent it by passing --target-org feature-42 explicitly in commands and scripts, and by giving orgs descriptive aliases, then checking the current default with sf org list before deploying.
Exercise
You enabled Dev Hub in a Developer Edition org and want to confirm your scratch orgs from the command line, including their expiration dates. Which command do you run, and where does that data come from?
Show answer
Run sf data query --target-org devhub --query "SELECT Id, SignupUsername, ExpirationDate FROM ActiveScratchOrg". The data comes from the ActiveScratchOrg object in the Dev Hub, which the Dev Hub fills in when it creates each scratch org.