I want to build a Single Page Application (SPA) and noticed the following issue during separation of backend API (REST) and frontend assets (static vue.js code):
When serving the index.html from another domain than the API backend, most of the POST/PUT requests trigger a CORS preflight request.
I did some research and found out that blog posts [1][2] discuss this issue - without giving a practical solution. Some headers (e.g. Authorization header and the Content-Type header with the application/json value) are not allowed as cors-safelisted-request-header. Thus POST/PUT requests trigger a CORS preflight request. This is not acceptable since it adds a considerable amount of latency.
Question
Is it possible to avoid these preflight requests if both domains are owned by the same entity?
Research
I did some research on how to avoid CORS requests between frontend and backend. The solution requires the index.html file being served from the same domain as the REST API backend (see Example below). I wonder if not using separate domains is the only solution to avoid CORS requests for SPAs.
Scenario (Example)
- Single Page Application (SPA); frontend and backend layer
- hosted in the AWS cloud
- Layer 1: CloudFront CDN with an S3 bucket origin - serve static assets (Vue.js frontend) on static.example.com
- Layer 2: Load-Balancer with ECS integration which is running node.js containers to host the (REST) backend on example.com
- The communication between layer 1 and layer 2 uses the HTTPS protocol and the REST paradigm.
- The index.html is served by layer 2 and customers open the webapp using example.com.
- The index.html references the API by pointing to the same domain (example.com). It references the static vue assets by pointing to the CDN (static.example.com).
- The SPA consists of two parts: a) the public assets (.js files, .css files etc.) and b) the index.html file. The latter one is served by the same fleet of backend containers which also host the REST API.
References
[1] https://www.freecodecamp.org/news/the-terrible-performance-cost-of-cors-api-on-the-single-page-application-spa-6fcf71e50147/
[2] https://developer.akamai.com/blog/2015/08/17/solving-options-performance-issue-spas