How to get a specific Salesforce domain?

With the recent Salesforce transition to Enhanced Domains the question of how to reliably get a specific Salesforce domain (e.g. for Lightning or Visualforce) is getting raised more often than before. In this post I will shortly present a very helpful class that was released in Spring ‘22 that will be the go-to answer to this question in the future.

DomainCreator

In Spring ‘22 Salesforce has released a new class called DomainCreator. Below is the official Salesforce description of when to use this class:

Use the DomainCreator class to return a hostname specific to the org. For example, get the org’s Visualforce hostname. Values are returned as a hostname, such as MyDomainName.lightning.force.com.

It is important to note that this class will work with or without Enhanced Domains being enabled, so you can safely use it during the transition period when some of your orgs have it enabled and some still don’t.

The official Salesforce documentation is probably the best place to learn more about this class and how to use it, and I will only mention some examples uses of it:

How to get the Salesforce org’s MyDomain?

// Get the My Domain login hostname
String myDomainHostname = DomainCreator.getOrgMyDomainHostname();

How to get a Visualforce Domain?

// Get the Visualforce hostname for 'uat' package
String vfHostname = DomainCreator.getVisualforceHostname('uat');

In case you don’t have a package, just pass in an empty string or null.

How to get an Experience Cloud domain?

// Get the Experience Cloud hostname if Digital Experiences are enabled
String xcHostname = DomainCreator.getExperienceCloudSitesHostname();

Keep in mind that this will not return the Custom Domain, if you have one associated with it.

Below is an example on how to get a link to a record in Salesforce Lightning - adjust the objectName and recordId to fit your needs:

String hostname = DomainCreator.getLightningHostname();
String objectName = 'Account';
Id recordId = '0011w00001E7PzWAAV';
 
String fullRecordUrl = String.format(
    'https://{0}/lightning/r/{1}/{2}/view', 
    new List<String>{ hostname, objectName, recordId});

You can wrap the above code in a nice utility method and use it anywhere you need.

Written on June 21, 2022