Bird
Raised Fist0
Expressframework~10 mins

Why CORS matters for APIs in Express - Visual Breakdown

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
Concept Flow - Why CORS matters for APIs
Browser sends API request
Server receives request
Server checks Origin header
Origin allowed?
NoReject request with CORS error
Server sends response with CORS headers
Browser accepts response if CORS headers valid
API data accessible in browser
The browser sends a request with an origin. The server checks if the origin is allowed. If yes, it sends back CORS headers allowing access. Otherwise, the browser blocks the response.
Execution Sample
Express
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'https://example.com');
  next();
});
This code adds a header to allow requests only from https://example.com.
Execution Table
StepActionRequest OriginServer CORS CheckResponse Header SentBrowser Behavior
1Browser sends API requesthttps://example.comCheck if origin allowedAccess-Control-Allow-Origin: https://example.comBrowser accepts response
2Browser sends API requesthttps://malicious.comCheck if origin allowedNo CORS header or different originBrowser blocks response (CORS error)
3Browser sends API requestnull (local file)Check if origin allowedDepends on server configBrowser blocks or accepts based on header
4Request without Origin header (e.g. curl)No OriginNo CORS check neededNo CORS header neededResponse received normally
5End of flow---Browser enforces CORS policy based on headers
💡 Browser blocks API response if CORS headers do not allow the request origin.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
Request Originundefinedhttps://example.comhttps://malicious.comnullNo Originvaries per request
Server CORS Headernone'https://example.com'none or differentdependsnonevaries per request
Browser Accepts Responsefalsetruefalsedependstruedepends on CORS headers
Key Moments - 3 Insights
Why does the browser block the response from https://malicious.com?
Because the server did not send an Access-Control-Allow-Origin header matching https://malicious.com, so the browser enforces CORS and blocks access (see execution_table step 2).
Why do requests without an Origin header (like curl) not get blocked?
CORS is a browser security feature. Requests without Origin header are usually from non-browser clients and are not blocked (see execution_table step 4).
What happens if the server allows all origins with '*'?
The server sends Access-Control-Allow-Origin: * header, so browsers accept responses from any origin, allowing cross-origin access.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the browser behavior when the request origin is https://example.com?
ABrowser ignores the response
BBrowser blocks the response due to CORS error
CBrowser accepts the response
DBrowser retries the request
💡 Hint
Check execution_table row 1 under 'Browser Behavior'
At which step does the browser block the response due to missing or wrong CORS headers?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at execution_table row 2 for browser blocking
If the server sets Access-Control-Allow-Origin to '*', how would the browser behave for https://malicious.com origin?
ABrowser blocks the response
BBrowser accepts the response
CBrowser sends a new request
DBrowser ignores the origin
💡 Hint
Recall that '*' allows all origins, so browser accepts (see key_moments answer 3)
Concept Snapshot
Why CORS matters for APIs:
- Browsers enforce CORS to protect users from unauthorized cross-origin requests.
- Server must send Access-Control-Allow-Origin header matching the request origin.
- Without correct CORS headers, browser blocks API responses.
- Non-browser clients (curl) are not affected by CORS.
- Setting '*' allows any origin to access the API.
Full Transcript
When a browser sends a request to an API, it includes the origin of the page making the request. The server checks this origin and decides if it is allowed to access the API. If allowed, the server sends back a special header called Access-Control-Allow-Origin with the allowed origin. The browser then lets the page access the API response. If the origin is not allowed or the header is missing, the browser blocks the response to protect the user. This is called CORS, or Cross-Origin Resource Sharing. It is important because it stops malicious websites from reading data from APIs they shouldn't access. Non-browser tools like curl do not have this restriction. Developers must configure their API servers to send the right CORS headers to allow trusted websites to use their APIs safely.

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