Salesforce developers know that working with domains is not easy. Links generation always takes time to get the right domain, parameters, etc. Hopefully, from Spring’22, Salesforce provides a new Apex class DomainCreator. It helps to return a specific hostname specific to the org. The class will work with or without Enhanced Domains. Let’s see a few examples of using this class.
MyDomain Hostname
String myDomain = DomainCreator.getOrgMyDomainHostname();
Lightning Hostname
If you want to build a full record URL in Lightning, use the method getLightningHostname(). See the example for a Lead record below:
Lead leadRecord = [SELECT Id FROM Lead LIMIT 1];
String lightningHostname = DomainCreator.getLightningHostname();
String recordURL = 'https://' + lightningHostname + '/lightning/r/Account/' + leadRecord.Id + '/view';
See more details in the official Salesforce documentation.