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?
How to get a Visualforce Domain?
In case you don’t have a package, just pass in an empty string or null.
How to get an Experience Cloud domain?
Keep in mind that this will not return the Custom Domain, if you have one associated with it.
How to get a link to a record in Salesforce Lightning?
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:
You can wrap the above code in a nice utility method and use it anywhere you need.