0
0
Node.jsframework~8 mins

CORS configuration in Node.js - Performance & Optimization

Choose your learning style9 modes available
Performance: CORS configuration
MEDIUM IMPACT
CORS configuration affects the network request flow and browser security checks, impacting page load speed and interaction responsiveness.
Allowing cross-origin requests for API calls
Node.js
const cors = require('cors');
const corsOptions = {
  origin: 'https://example.com',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type'],
  optionsSuccessStatus: 204
};
app.use(cors(corsOptions));
Specifying exact allowed origins and methods reduces unnecessary preflight requests, speeding up network calls.
📈 Performance GainEliminates many preflight requests, reducing request blocking and improving INP.
Allowing cross-origin requests for API calls
Node.js
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});
Using a wildcard '*' for Access-Control-Allow-Origin causes browsers to send preflight OPTIONS requests for many calls, adding latency.
📉 Performance CostTriggers extra preflight requests, blocking rendering and interaction until responses arrive.
Performance Comparison
PatternNetwork RequestsPreflight RequestsBlocking TimeVerdict
Wildcard '*' originMultiple requestsMany preflightsBlocks rendering and interaction[X] Bad
Specific origin and methodsFewer requestsMinimal preflightsNon-blocking, faster interaction[OK] Good
Rendering Pipeline
CORS configuration affects the network request phase before rendering. Incorrect setup causes browsers to send preflight OPTIONS requests, delaying the main request and blocking rendering and interaction.
Network Request
Rendering Block
Interaction Responsiveness
⚠️ BottleneckNetwork Request due to preflight OPTIONS delays
Core Web Vital Affected
INP
CORS configuration affects the network request flow and browser security checks, impacting page load speed and interaction responsiveness.
Optimization Tips
1Avoid using wildcard '*' for Access-Control-Allow-Origin in production.
2Specify only necessary HTTP methods and headers in CORS settings.
3Monitor preflight OPTIONS requests in DevTools to optimize CORS.
Performance Quiz - 3 Questions
Test your performance knowledge
What causes browsers to send CORS preflight OPTIONS requests?
AUsing wildcard '*' for Access-Control-Allow-Origin
BUsing HTTPS instead of HTTP
CServing static files from the same origin
DUsing GET requests only
DevTools: Network
How to check: Open DevTools, go to Network tab, filter by 'OPTIONS' requests, and observe if preflight requests occur before main API calls.
What to look for: Presence of many OPTIONS requests indicates excessive preflights; fewer or no OPTIONS requests means better CORS setup.