I have very intensive single-page application that is using API. Let's say application is located at application.com
. Now if I place API in api.application.com
it will enable CORS thus all browsers will do OPTIONS
request before the actual request.
Does this makes my application 2x slower?
This pre-flight request is made by some browsers as a safety measure to ensure that the request being done is trusted by the server. Meaning the server understands that the method, origin and headers being sent on the request are safe to act upon.
Another way to avoid Preflight requests is to use simple requests. Preflight requests are not mandatory for simple requests, and according to w3c CORS specification, we can label HTTP requests as simple requests if they meet the following conditions. Request method should be GET , POST , or HEAD .
A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers. It is an OPTIONS request, using three HTTP request headers: Access-Control-Request-Method , Access-Control-Request-Headers , and the Origin header.
Prevent sending the post data, if it wont be processed This is the only reason what is valid. Using options request will prevent sending the post data to the server unnecessarily.
It probably won't make your entire application 2x slower. It will sometimes issue 2 http requests when you might expect one. But your app is probably more than just HTTP requests, so you'd have to measure the performance of your app as a whole.
The conditions for the browser issuing a preflight are:
GET
, HEAD
, POST
), orAccept
, Accept-Language
, Content-Language
or Content-Type
(but only if the Content-Type
value is not application/x-www-form-urlencoded
, multipart/form-data
, or text/plain
)If your HTTP request doesn't meet those criteria, it will not issue a preflight. The preflight is a small OPTIONS request without a body, so it should be fast (depending on your connection speed). And once you issue a preflight, its results are cached for a period of time (the cache time varies by browser. Chrome/Safari do 5 minutes, FF does 24 hours).
If you are interested in tips for reducing preflights, see this answer: How to apply CORS preflight cache to an entire domain
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With