0
0
Expressframework~8 mins

Why CORS matters for APIs in Express - Performance Evidence

Choose your learning style9 modes available
Performance: Why CORS matters for APIs
MEDIUM IMPACT
CORS affects how browsers allow or block API requests from different origins, impacting user experience and page functionality.
Allowing cross-origin API requests safely
Express
const cors = require('cors');
app.use(cors({ origin: 'https://example.com' }));
Restricts API access to trusted origins, reducing unnecessary preflight requests and improving security.
📈 Performance GainReduces failed requests and unnecessary network overhead, improving interaction speed.
Allowing cross-origin API requests safely
Express
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});
Allows all origins without restriction, risking security and unnecessary exposure.
📉 Performance CostCan cause security issues leading to blocked requests or user distrust, indirectly harming INP.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Allow all origins with '*'N/AN/AN/A[X] Bad
Restrict origins with specific domainN/AN/AN/A[OK] Good
Rendering Pipeline
When a browser makes a cross-origin API request, it checks CORS headers before allowing the response to be processed. If headers are missing or incorrect, the browser blocks the response, preventing JavaScript from accessing data.
Network Request
JavaScript Execution
User Interaction
⚠️ BottleneckNetwork Request blocking due to failed CORS checks
Core Web Vital Affected
INP
CORS affects how browsers allow or block API requests from different origins, impacting user experience and page functionality.
Optimization Tips
1Always specify allowed origins explicitly in CORS headers.
2Avoid using wildcard '*' in Access-Control-Allow-Origin for sensitive APIs.
3Check CORS headers in DevTools Network tab to ensure proper setup.
Performance Quiz - 3 Questions
Test your performance knowledge
What happens if an API response lacks proper CORS headers?
AThe browser loads the response normally without restrictions.
BThe browser blocks the response, causing failed API calls.
CThe server automatically retries the request.
DThe browser delays the response but eventually shows it.
DevTools: Network
How to check: Open DevTools, go to Network tab, filter for API requests, check OPTIONS and actual requests for CORS headers and status codes.
What to look for: Look for 200 status on OPTIONS preflight and presence of Access-Control-Allow-Origin header matching your site.