Identify Production / Sandbox Salesforce Org in Apex

Author: Bruce Tollefson Published: May 14, 2022; Modified: May 14, 2022

In order to write reusable code and not hardcode in Apex there are times you will need to know if you are working in a Sandbox or Production org. Most of the time it would be to change variables such as knowing when to use a dev named credential vs a production named credential (hopefully there are other measures to prevent this such as the server checking the hostname). However identifying in Apex whether the Salesforce org is production or a sandbox either required a SOQL query or some base url string manipulations with risks. Now with the Spring ’22 release and the added Domain classes we now longer need to use either methods. Let’s first go through the old ways of Identify a production or sandbox salesforce org.

Using a SOQL Query

You could have used a SOQL query looking at the organization object and checking the IsSandbox field:

Boolean isSandbox = [SELECT IsSandbox, Id FROM Organization].IsSandbox;

Then you can use the isSandbox boolean however you needed. This commonly was in a utility method that had potential to be called multiple times in a transaction. Each time called you would use a SOQL query. This could be mitigated by putting it in a singleton pattern as outlined and reference the singleton. But that wasn’t very common to see.

Base URL String Manipulation

The next potential way to identify a production or sandbox org in Salesforce was to use the URL.getOrgDomainUrl() and split it see if there is a sandbox name:

Boolean isSandbox = false; List urlSplit = URL.getOrgDomainUrl().toExternalForm().split('--'); //domain sandbox format is Domain name + '--' + sandbox name if(urlSplit.size() > 1){ isSandbox = true; // }

Assuming that the sandbox naming format continues as Domain name + ‘–‘ + sandbox name.

Using the Spring ’22 Domain Classes

With the Spring ’22 release 3 new class were added Domain Class, DomainCreator Class, and DomainParser Class allowing us to use these classes to determine if the Salesforce org is production or a sandbox, without using a SOQL query or any type of string manipulation:

String sandboxName = DomainParser.parse(DomainCreator.getOrgMyDomainHostname()).getSandboxName(); boolean isSandbox = false; if(!String.isEmpty(sandboxName)){ isSandbox = true; }

Leave a Reply

Your email address will not be published. Required fields are marked *