Cross-origin resource sharing (CORS) allows pages on other domains to access the API. To use CORS, you’ll have to specifically allowlist each domain you want to grant access; this ensures that no bad actors are calling your API from sites you don’t control.
Allowlist domains for CORS
Perform the following steps to allowlist a domain and grant it access to the API:
- Access the Dashboard.
- Navigate to Settings > Security.
- Add the domain you want to allowlist to the Trusted Domains list. Just enter the domain without the https:// part.
Make a CORS request
Most JavaScript AJAX clients support CORS transparently so you won't have to do anything once the site has allowlisted your domain.
If you're unsure whether your client is making the request properly, open up your network inspector and make sure the request has the Origin header and that it includes your domain. That is the domain that must be allowlisted in Vanilla.
Avoid pre-flighted requests
CORS leverages the concept of “pre-flighted requests.” This involves the browser making an initial request to see if it has authorization, followed by the actual request if everything checks out. Pre-flighted requests are suboptimal because they essentially double up the requests you have to make.
Fortunately, the API has a workaround to avoid most pre-flighted requests. Here are the steps you need to take:
- Pass the access token in the access_token querystring rather than the authorization header. If you do this, leave out the “Bearer” part of the access token.
- GET requests that contain the access token in the querystring should avoid pre-flight requests.
- When you make a POST request you cannot set the content type to
application/json
or else it will trigger a pre-flight request. If you want to post JSON, you can set your content type to text/plain and the API will assume it’s application/json
. - If you're still noticing pre-flight requests, you may be adding some type of header to your request. Look at MDN’s help on simple requests to see what extraneous header may be triggering the pre-flight.
These workarounds are only necessary if you're making requests within a browser. If you're making requests elsewhere, then you should set the access token in the header and use a content type of application/json
.