When a cross origin request is initiated by a client app, Browsers make a preflight request before executing an actual request.
Example: Assume that example.com makes an authenticated POST request to a server api.service.com. The browser makes an additional OPTIONS request to api.service.com before making the actual request.
The POST request will be processed only if the response to the OPTIONS call has the headers
If these headers are not present, the POST call is aborted.
Preflight requests make CORS (Cross Origin Resource Sharing) secure, but at the same time they introduce noticeable latency to every rest API call.
This article explains how to avoid OPTIONS calls when you are using AWS cloudfront as CDN and AWS API Gateway to manage your APIs.
- AWS account.
- Web Application hosted in AWS Cloudfront.
- APIs managed by AWS API Gateway.
1. Create/Add an Origin in your cloudfront distribution.
a. Navigate to AWS
API Gateway, select your API and click on ‘Stages’ from side menu, select
any stage and copy invoke url excluding stage name.
b. Navigate to AWS Cloudfront, select your
distribution and click on tab ‘Origins and Origin Groups’ then ‘Create
c. Paste invoke url copied from API Gateway in ‘Origin Domain Name’
d. Leave ‘Origin Path’ empty.
e. Change ‘Origin Protocol Policy’ to HTTPS Only.
f. Leave the rest of the fields untouched to their default values and click on ‘Create’.
2. Create/Add a new Behaviour in your cloudfront distribution.
a. Select your cloudfront distribution and click on
“Behaviours” tab and select ‘Create Behaviour’.
b. Fill ‘Path Pattern’ with stage name part of your API Gateway invoke url like below
c. For ‘Origin or Origin Group’ choose Origin which you have created in Step 1.
d. Change ‘Viewer Protocol Policy’ to Redirect HTTP to HTTPS.
e. Change Allowed HTTP Methods to GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE
f. In ‘Cached HTTP Methods’ select OPTIONS
g. In ‘Cache Based on Selected Request Headers’ select ‘Whitelist’
Whitelist all the headers which you are referring in your api business logic
h. In ‘Object Caching’ select Customize
Enter 0 for Minimum TTL
Enter 0 for Maximum TTL
Enter 0 for Default TTL
i. Select ‘All’ for Forward Cookies
j. Select ‘Forward all, cache based on all’ for ‘Query String Forwarding and Caching’
k. Select ‘No’ for ‘Smooth Streaming’
l. Select ‘No’ for ‘Restrict Viewer Access (Use Signed URLs or Signed Cookies)’
m. Select ‘Yes’ for Compress Objects Automatically
n. Click ‘Create Behaviour’
3. Test the Setup
a. Visit your web
application using google chrome
b. Open ‘Network’ tab in inspect mode
c. Make an action which triggers rest api call and verify preflight (Options) requests are not made.