Salesforce is one of the best CRMs out there but like other systems, it too has its fair share of limitations. But oftentimes, many workarounds can be applied to get our desired results. For example, starting a Process Builder after one minute even though by default we have to wait at least an hour or fetching attachments from just external URLs in Apex. Fixing the CORS issue in Apex can also become challenging sometimes, as it is not just a Salesforce-related issue but a general one. In this guide, we will help you solve CORS blocking issue but before that let’s talk about what CORS is.
For security reasons, web protocols have a same-origin resource-sharing policy, meaning that the source and destination URLs of callouts should be the same. Otherwise, it would be referred to as cross-origin resource sharing (CORS) and will be blocked. For example, a request made to “link2.com” by “link1.com” will be blocked. As “link1.com” will only be allowed to request resources from its own domain.
In order to allow CORS, the server-side needs to acknowledge that the request which is coming from a different origin is allowed to communicate with the server. For that, ‘Access-Control-Allow-Origin’ headers need to be added to the APIs. Then through a preflight request, it is first ensured that the request is approved and then no blocking occurs.
Fixing the CORS issue in Apex
In Salesforce, we can solve CORS blocking issue by the following steps.
Whitelisting the Domain
First of all, you need to add the external domain – that will be making requests to the Salesforce – in the CORS whitelist in the Salesforce setup.
- Go to Setup
- Enter CORS and click New
- In the URL pattern field, type the external URL
- Click Save
Adding Headers in Webservice
In order to make the endpoint enable cross-origin resource sharing, we have to add some specific headers in our APIs.
Add the following headers inside your Apex REST API code:
RestResponse res = RestContext.response;
.
.
res.addHeader('Access-Control-Max-Age', '86400');
res.addHeader('Access-Control-Allow-Credentials', 'Server,range,hdntl,hdnts');
res.addHeader('Access-Control-Expose-Headers', 'Server,range,hdntl,hdnts');
res.addHeader('Access-Control-Allow-Headers', 'origin,range,hdntl,hdnts');
res.addHeader('Access-Control-Allow-Origin', '*');
res.addHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
.
.
This should get your client-side requests approved.
Verify client-side request
If the above two steps didn’t work, make sure that your client-side request is correct. Sometimes, calling a request of a different method (GET, POST, etc) with a different method can cause CORS blocking issues. So, make sure that
- The method (GET, POST etc) are correct
- Content-Type header is correct
- The destination url is correct
I hope this guide will help in fixing the CORS issue in Apex. If the problem persists, let us know in the comments below. For more programming guides, keep following Retrology.