0
0
Expressframework~8 mins

Configuring allowed origins in Express - Performance Optimization Steps

Choose your learning style9 modes available
Performance: Configuring allowed origins
MEDIUM IMPACT
This affects how the server handles cross-origin requests, impacting network latency and browser security checks.
Allowing cross-origin requests securely and efficiently
Express
const allowedOrigins = ['https://example.com', 'https://app.example.com'];
app.use(cors({ origin: (origin, callback) => {
  if (!origin || allowedOrigins.includes(origin)) {
    callback(null, true);
  } else {
    callback(new Error('Not allowed by CORS'));
  }
}}));
Restricts origins to trusted domains, reducing unnecessary preflight requests and improving security.
📈 Performance GainReduces preflight requests and network delays, improving interaction responsiveness
Allowing cross-origin requests securely and efficiently
Express
app.use(cors({ origin: '*' }));
Allowing all origins causes browsers to send preflight OPTIONS requests more often and can expose security risks.
📉 Performance CostTriggers frequent preflight requests, increasing network latency and blocking rendering until response
Performance Comparison
PatternNetwork RequestsPreflight RequestsSecurity RiskVerdict
Allow all origins (*)High - all requests allowedHigh - many preflightsHigh - security risk[X] Bad
Allow specific originsLow - only trusted domainsLow - fewer preflightsLow - secure[OK] Good
Rendering Pipeline
When a browser makes a cross-origin request, it may send a preflight OPTIONS request to check permissions. The server's allowed origins configuration determines if the request proceeds. Proper configuration reduces network round-trips and delays before rendering or interaction.
Network Request
Browser Preflight
Server Response
Interaction Readiness
⚠️ BottleneckNetwork latency caused by unnecessary preflight OPTIONS requests
Core Web Vital Affected
INP
This affects how the server handles cross-origin requests, impacting network latency and browser security checks.
Optimization Tips
1Avoid using wildcard '*' for allowed origins in production.
2Specify only trusted domains in allowed origins to reduce preflight requests.
3Use CORS middleware with origin as a function to dynamically validate origins.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a performance downside of allowing all origins with CORS in Express?
ABlocks all cross-origin requests
BReduces network requests and speeds up loading
CTriggers many preflight OPTIONS requests increasing latency
DImproves browser caching automatically
DevTools: Network
How to check: Open DevTools, go to Network tab, filter by OPTIONS requests, and observe preflight requests when making cross-origin calls.
What to look for: Fewer OPTIONS preflight requests indicate better CORS configuration and improved performance.