Understanding Namespace Behavior in Salesforce Second Generation Packaging (2GP)
Salesforce Second-Generation Packaging (2GP) automatically injects the package namespace prefix into metadata at build time, even though developers do not manually add these prefixes in source code. This internal rewriting ensures that Apex classes, objects, fields, and components are properly namespaced and isolated without appearing in the Git repository or subscriber org source code. Salesforce manages all internal references automatically, allowing developers to write clean, namespace-agnostic code while benefiting from the security and modularity of namespaces. Understanding this behavior helps Salesforce teams avoid confusion and build better managed packages following best practices.
- Namespaces are automatically applied by Salesforce at packaging time in 2GP.
- Never manually add namespace prefixes in your source code for 2GP managed packages.
- Salesforce rewrites internal references to include namespaces during packaging.
- Namespaced code doesn't appear in subscriber orgs or your Git repo source.
- Keeping source code namespace-agnostic ensures compatibility and best practices.
If you’re transitioning to Salesforce Second-Generation Packaging (2GP), one of the first things you’ll notice is that your metadata looks different after packaging. Objects, fields, Apex classes, and components suddenly appear with a namespace prefix, even though your original source code contains no such prefix. This can be confusing at first but this behavior is completely expected. In this blog, we’ll explain why Salesforce automatically injects namespaces in 2GP, how it rewrites code internally, and why everything works seamlessly even though you never see the transformed code.