0
0
Flaskframework~8 mins

CORS configuration with Flask-CORS - Performance & Optimization

Choose your learning style9 modes available
Performance: CORS configuration with Flask-CORS
MEDIUM IMPACT
This affects how browsers handle cross-origin requests, impacting page load speed and interaction responsiveness when fetching resources from different domains.
Allowing cross-origin requests in a Flask API
Flask
from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r"/data": {"origins": ["https://example.com"]}})

@app.route('/data')
def data():
    return {'key': 'value'}
Restricting origins reduces preflight requests and allows browsers to skip OPTIONS calls, improving response time.
📈 Performance GainEliminates unnecessary preflights, reducing latency by 100-200ms per request
Allowing cross-origin requests in a Flask API
Flask
from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}})

@app.route('/data')
def data():
    return {'key': 'value'}
Allowing all origins with '*' causes browsers to send preflight OPTIONS requests for many calls, increasing latency and blocking rendering.
📉 Performance CostTriggers extra preflight requests, adding 100-200ms delay per cross-origin call
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Allow all origins with '*'No direct DOM impactNo reflowsNo paint cost[!] OK but causes network delays
Restrict origins to specific domainsNo direct DOM impactNo reflowsNo paint cost[OK] Best for network performance
Rendering Pipeline
CORS configuration affects the network request phase before rendering. Improper setup causes browsers to send preflight OPTIONS requests, delaying the main resource fetch and blocking rendering and interaction.
Network Request
Rendering Blocking
Interaction Responsiveness
⚠️ BottleneckNetwork Request due to preflight OPTIONS calls
Core Web Vital Affected
INP
This affects how browsers handle cross-origin requests, impacting page load speed and interaction responsiveness when fetching resources from different domains.
Optimization Tips
1Avoid using '*' for allowed origins to reduce preflight requests.
2Specify only necessary HTTP methods and headers in CORS config.
3Use browser DevTools Network tab to monitor preflight OPTIONS calls.
Performance Quiz - 3 Questions
Test your performance knowledge
What causes browsers to send a preflight OPTIONS request when using CORS?
ARequesting simple GET requests only
BUsing wildcard '*' for allowed origins
CUsing same-origin requests
DServing static files
DevTools: Network
How to check: Open DevTools > Network tab, filter by OPTIONS requests, and observe if preflight requests occur before your API calls.
What to look for: Presence of OPTIONS requests indicates preflight; fewer or no OPTIONS requests means better CORS setup and faster response