Bird
Raised Fist0
Expressframework~8 mins

Why CORS matters for APIs in Express - Performance Evidence

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
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.

Practice

(1/5)
1. What is the main reason CORS is important for APIs in Express?
easy
A. It encrypts the data sent by the API.
B. It speeds up the API response time.
C. It automatically logs all API requests.
D. It controls which websites can access your API to protect it.

Solution

  1. Step 1: Understand CORS purpose

    CORS stands for Cross-Origin Resource Sharing and it controls which websites can call your API.
  2. Step 2: Identify protection role

    By controlling access, CORS protects your API from unwanted or malicious websites.
  3. Final Answer:

    It controls which websites can access your API to protect it. -> Option D
  4. Quick Check:

    CORS controls access = D [OK]
Hint: Remember: CORS controls access, not speed or encryption [OK]
Common Mistakes:
  • Thinking CORS speeds up API
  • Confusing CORS with logging
  • Believing CORS encrypts data
2. Which Express middleware is commonly used to enable CORS?
easy
A. cors
B. express-session
C. body-parser
D. morgan

Solution

  1. Step 1: Recall Express middleware for CORS

    The npm package named 'cors' is the standard middleware to enable CORS in Express.
  2. Step 2: Identify other middleware roles

    express-session manages sessions, body-parser parses request bodies, morgan logs requests, none handle CORS.
  3. Final Answer:

    cors -> Option A
  4. Quick Check:

    Enable CORS with 'cors' middleware = B [OK]
Hint: Use 'cors' package to enable CORS in Express apps [OK]
Common Mistakes:
  • Choosing body-parser for CORS
  • Confusing logging middleware with CORS
  • Using session middleware for CORS
3. What will happen if an API does NOT set CORS headers and a browser tries to call it from another website?
medium
A. The browser will block the request due to CORS policy.
B. The API will respond faster without CORS headers.
C. The API will automatically allow all websites.
D. The browser will ignore CORS and allow the request.

Solution

  1. Step 1: Understand browser CORS enforcement

    Browsers enforce CORS by blocking cross-origin requests if the server does not send proper CORS headers.
  2. Step 2: Identify consequences of missing CORS headers

    Without CORS headers, the browser blocks the request; the API itself may respond but browser denies access.
  3. Final Answer:

    The browser will block the request due to CORS policy. -> Option A
  4. Quick Check:

    Missing CORS headers = browser blocks request = A [OK]
Hint: No CORS headers means browser blocks cross-site calls [OK]
Common Mistakes:
  • Thinking API blocks request instead of browser
  • Assuming API allows all without CORS
  • Believing browser ignores CORS
4. Consider this Express code snippet:
const express = require('express');
const app = express();

app.get('/data', (req, res) => {
  res.json({ message: 'Hello' });
});

app.listen(3000);
What is missing to allow cross-origin requests safely?
medium
A. Adding a body-parser middleware.
B. Changing app.get to app.post.
C. Adding CORS middleware to set proper headers.
D. Using HTTPS instead of HTTP.

Solution

  1. Step 1: Identify missing CORS headers

    The code does not include any middleware to set CORS headers, so cross-origin requests will be blocked by browsers.
  2. Step 2: Recognize correct fix

    Adding CORS middleware (like 'cors' package) will add headers to allow safe cross-origin requests.
  3. Final Answer:

    Adding CORS middleware to set proper headers. -> Option C
  4. Quick Check:

    Add CORS middleware to allow cross-origin = A [OK]
Hint: Add 'cors' middleware to fix cross-origin blocking [OK]
Common Mistakes:
  • Thinking HTTP method change fixes CORS
  • Confusing body parsing with CORS
  • Believing HTTPS alone solves CORS
5. You want your Express API to allow only requests from https://example.com but block others. Which CORS configuration achieves this?
hard
A. app.use(cors());
B. app.use(cors({ origin: 'https://example.com' }));
C. app.use(cors({ origin: '*' }));
D. app.use(cors({ methods: ['GET', 'POST'] }));

Solution

  1. Step 1: Understand origin option in CORS

    The 'origin' option in the cors middleware specifies which website origins are allowed to access the API.
  2. Step 2: Match requirement to configuration

    Setting origin to 'https://example.com' allows only that site; '*' allows all, no origin restricts, methods restrict HTTP verbs only.
  3. Final Answer:

    app.use(cors({ origin: 'https://example.com' })); -> Option B
  4. Quick Check:

    Restrict origin to example.com = C [OK]
Hint: Set origin to specific URL to restrict access [OK]
Common Mistakes:
  • Using '*' allows all origins, not restricted
  • Omitting origin allows all by default
  • Confusing methods with origin restriction