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
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.
Create/Add an Origin in your cloudfront distribution.
- Navigate to AWS API Gateway, select your API and click on
‘Stages’ from side menu, select any stage and copy invoke url excluding stage
- Navigate to AWS Cloudfront, select your distribution and click on tab ‘Origins and Origin Groups’ then ‘Create Origin’
- Paste invoke url copied from API Gateway in ‘Origin Domain Name’
- Leave ‘Origin Path’ empty
- Change ‘Origin Protocol Policy’ to HTTPS Only.
- Leave the rest of the fields untouched to their default values and click on ‘Create’.
Create/Add a new Behaviour in your cloudfront distribution.
- Select your cloudfront distribution and click on “Behaviours” tab and select ‘Create Behaviour’.
- Fill ‘Path Pattern’ with stage name part of
your API Gateway invoke url like below
- For ‘Origin or Origin Group’ choose Origin which you have created in Step 1.
- Change ‘Viewer Protocol Policy’ to Redirect HTTP to HTTPS.
- Change Allowed HTTP Methods to GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE
- In ‘Cached HTTP Methods’ select OPTIONS
- In ‘Cache Based on Selected Request
Headers’ select ‘Whitelist’
Whitelist all the headers which you are referring in your api business logic
- In ‘Object Caching’ select Customize
- Enter 0 for Minimum TTL
- Enter 0 for Maximum TTL
- Enter 0 for Default TTL
- Select ‘All’ for Forward Cookies
- Select ‘Forward all, cache based on all’ for ‘Query String Forwarding and Caching’
- Select ‘No’ for ‘Smooth Streaming’
- Select ‘No’ for ‘Restrict Viewer Access (Use Signed URLs or Signed Cookies)’
- Select ‘Yes’ for Compress Objects Automatically
- Click ‘Create Behaviour’
Test the Setup
- Visit your web application using google chrome
- Open ‘Network’ tab in inspect mode
- Make an action which triggers rest api call and verify preflight (Options) requests are not made.
Click here to find out how Techpearl can build performant sites for you.