function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Get URL to current environment in Apex code.

I want to compose an email body in Apex code and include a link in it.  The link can be "/" plus the ID of the object but the URL needs to be construction relative to the current instance.  I can't code "" as it might not work.  Also, it should work with the proper URL for each sandbox.


Anyone know a way in Apex to get the root URL for the current environment?


I don't think VF email templates will work in my case.

Cory CowgillCory Cowgill

Have you tried this:

Cory CowgillCory Cowgill

Forgot to mention that will only work in a Visualforce Page.


If you need to do this in a Trigger or Batch Apex, I would suggest you create a Custom Setting and populate it with the Server URL in your browser address bar.Then in your Apex code you pull the Custom Setting and pull the Server URL from  the field you populated.


That should allow your code to be independent of the environment. Yeah, you'll have to do a manual config of the Server URL each time you build out a new environment, but its literally just a few clicks of your mouse.


If you're able to use merge codes, you can use the .Link extesion. IE: {!Opportunity.Link} which will auto create the entire URL for you.


If that doesn't work (since you mentioned the thing about email templates), have you tried simply making it relative? IE: /apex/PageName?id=XXX


Given that everything runs off the root ( that may work. Another option, albeit ugly, could be to pull the full current URL (if you're doing this for VF) and parse out everything after the .com.


Edit: If you're trying to do this strictly from Apex, this post may be of assistance:


I'm running in the context of a trigger so anything having to do with VF won't work.


The custom setting idea will work except if our org is ever bounced to a different node, we'll have to edit it.  Thatts a hack but I think it is the only suggestion that will work so far.

Cory CowgillCory Cowgill

Yeah, theres already an idea on the idea exchange to give access to this at the API level and not have to do any workarounds since 2008, and its still not delivered. So we have to work with what we've got. :)

Nadim ShaikhNadim Shaikh
I did this in Apex

URL.getSalesforceBaseUrl().toExternalForm() +'/'