Sub topic 13
Namespaces and when to use them
This chapter assumes you can run sf CLI commands, have a Dev Hub, and understand sfdx-project.json package directories from earlier chapters.
What a namespace is
A namespace is a prefix of 1 to 15 alphanumeric characters. Salesforce adds it to the names of a package's components, for example acme__Invoice__c or acme.BillingService. It stops your names from colliding with names in an org that installs the package.
You register a namespace in a Developer Edition org, called the namespace org. You then link that org to your Dev Hub. One namespace can be used by many packages, and each package is tied to exactly one namespace or none.
Namespaced and no-namespace packages
You choose at creation time. The choice cannot be changed afterwards for that package.
| Aspect | No namespace | Namespaced |
|---|---|---|
| Component names | Unchanged | Prefixed with `ns__` |
| Setup | None | Namespace org linked to the Dev Hub |
| Typical use | Internal packages in your own orgs | Packages shared across many orgs or with other teams |
| Existing code | Easy to move in | References may need updating |
Most teams that split their own org into domain packages use no namespace. This keeps existing Apex, formulas and integrations working, because nothing is renamed.
Creating each kind
For a no-namespace package, pass --no-namespace:
sf package create --name Core --package-type Unlocked --path force-app/core --no-namespace --target-dev-hub MyDevHubFor a namespaced package, leave out that flag. The package uses the namespace set in sfdx-project.json:
{
"packageDirectories": [
{ "path": "force-app/core", "package": "Core", "versionNumber": "1.0.0.NEXT", "default": true }
],
"namespace": "acme",
"sfdcLoginUrl": "https://login.salesforce.com",
"sourceApiVersion": "61.0"
}The project-level namespace value applies to all packages in the project. An empty string, as in the earlier example, means no namespace. If you list a namespace here, make sure the namespace org is linked to the Dev Hub. Otherwise sf package create fails.
Choosing
Consider a namespace when:
- Other teams or customers install the package and could have conflicting names.
- You want clear ownership of components in a shared org.
Avoid a namespace when:
- You are migrating existing metadata into packages. Renaming would break references.
- Only your own orgs install the package.
Exercise
Your team is moving existing Apex classes and custom objects from a production org into unlocked packages. Only your own sandboxes and production will install them. Should you use a namespace, and why?
Show answer
No. A namespace adds a prefix to every component name, which would break existing Apex, formulas, flows and integrations that refer to the old names. Without a namespace, names stay the same, and you only need to use --no-namespace when creating each package. The choice is fixed at package creation, so decide before you create it.