Bird
Raised Fist0
Expressframework~20 mins

Configuring allowed origins in Express - Practice Exercises

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
Challenge - 5 Problems
🎖️
CORS Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What is the output when a request from 'http://example.com' is made?

Given this Express server code configuring CORS origins, what will happen when a request comes from 'http://example.com'?

Express
const express = require('express');
const cors = require('cors');
const app = express();

const allowedOrigins = ['http://example.com', 'http://localhost:3000'];

app.use(cors({
  origin: function(origin, callback) {
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  }
}));

app.get('/', (req, res) => {
  res.send('Hello World');
});

app.listen(3000);
AThe request succeeds and the server responds with 'Hello World'.
BThe request fails with a CORS error because 'http://example.com' is not allowed.
CThe server crashes due to a syntax error in the CORS configuration.
DThe request succeeds but the response is blocked by the browser due to missing headers.
Attempts:
2 left
💡 Hint

Check if 'http://example.com' is in the allowedOrigins array.

📝 Syntax
intermediate
2:00remaining
Which option correctly configures CORS to allow only 'http://myapp.com'?

Select the correct CORS middleware configuration to allow requests only from 'http://myapp.com'.

Aapp.use(cors({ origin: function(origin) { return origin === 'http://myapp.com'; } }));
Bapp.use(cors({ origin: ['http://myapp.com'] }));
Capp.use(cors({ origin: 'http://myapp.com' }));
Dapp.use(cors({ origin: true }));
Attempts:
2 left
💡 Hint

Check the type expected for the origin option in the CORS middleware.

🔧 Debug
advanced
2:30remaining
Why does this CORS configuration block all requests?

Analyze the code below. Why does it block all cross-origin requests?

Express
const allowedOrigins = ['http://site1.com', 'http://site2.com'];

app.use(cors({
  origin: function(origin, callback) {
    if (allowedOrigins.indexOf(origin) >= 0) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  }
}));
AThe allowedOrigins array is empty, so no origins are allowed.
BThe condition 'allowedOrigins.indexOf(origin)' returns 0 for the first origin, which is falsy, so it blocks it.
CThe callback is never called, causing the request to hang.
DThe origin parameter is undefined, so the check fails.
Attempts:
2 left
💡 Hint

Remember how JavaScript treats 0 in conditions.

state_output
advanced
2:00remaining
What is the value of 'allowedOrigins' after this code runs?

Consider this code snippet. What is the final value of the 'allowedOrigins' variable?

Express
let allowedOrigins = ['http://a.com', 'http://b.com'];

allowedOrigins.push('http://c.com');
allowedOrigins = allowedOrigins.filter(origin => origin !== 'http://b.com');
A['http://a.com', 'http://c.com']
B['http://b.com', 'http://c.com']
C['http://a.com', 'http://b.com', 'http://c.com']
D['http://a.com']
Attempts:
2 left
💡 Hint

Think about what filter does to the array.

🧠 Conceptual
expert
3:00remaining
Which statement best explains why configuring allowed origins is important in Express apps?

Why do developers configure allowed origins in Express applications using CORS middleware?

ATo improve server performance by limiting the number of incoming requests from certain origins.
BTo automatically authenticate users based on their origin domain.
CTo enable the server to accept requests only from the same origin, blocking all cross-origin requests by default.
DTo restrict which websites can make requests to the server, enhancing security by preventing unauthorized cross-origin access.
Attempts:
2 left
💡 Hint

Think about what CORS controls in web browsers.

Practice

(1/5)
1. What is the main purpose of configuring allowed origins in an Express app using cors middleware?
easy
A. To encrypt data sent between client and server
B. To speed up the server response time
C. To control which websites can access your server resources
D. To log all incoming requests

Solution

  1. Step 1: Understand what allowed origins mean

    Allowed origins specify which websites are permitted to make requests to your server.
  2. Step 2: Identify the role of cors middleware

    The cors middleware in Express helps set these allowed origins to control access.
  3. Final Answer:

    To control which websites can access your server resources -> Option C
  4. Quick Check:

    Allowed origins = control access [OK]
Hint: Allowed origins control access, not speed or encryption [OK]
Common Mistakes:
  • Confusing allowed origins with encryption
  • Thinking it speeds up server
  • Assuming it logs requests
2. Which of the following is the correct way to allow only 'https://example.com' as an origin using the cors middleware in Express?
easy
A. app.use(cors({ origin: [https://example.com] }));
B. app.use(cors({ origin: 'https://example.com' }));
C. app.use(cors({ origins: 'https://example.com' }));
D. app.use(cors(https://example.com));

Solution

  1. Step 1: Check the correct option name for allowed origins

    The correct option is origin, not origins.
  2. Step 2: Verify the value type for origin

    It accepts a string for a single allowed origin, so 'https://example.com' is correct.
  3. Final Answer:

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

    Option name is origin, value is string [OK]
Hint: Use 'origin' option with string for single allowed site [OK]
Common Mistakes:
  • Using 'origins' instead of 'origin'
  • Passing array for single origin string
  • Calling cors without options
3. Given this Express code snippet, what will be the result when a request comes from 'https://allowed.com'?
const cors = require('cors');
app.use(cors({ origin: ['https://allowed.com', 'https://other.com'] }));
medium
A. The request will be allowed because 'https://allowed.com' is in the list
B. The request will be blocked due to invalid origin format
C. The request will be allowed only if it uses POST method
D. The request will be blocked because origin must be a string

Solution

  1. Step 1: Understand the origin option accepts an array

    The origin option can accept an array of allowed origins to permit multiple sites.
  2. Step 2: Check if 'https://allowed.com' is in the array

    Since 'https://allowed.com' is listed, requests from it will be allowed.
  3. Final Answer:

    The request will be allowed because 'https://allowed.com' is in the list -> Option A
  4. Quick Check:

    Array of origins allows listed sites [OK]
Hint: Array of origins lets listed sites access [OK]
Common Mistakes:
  • Thinking origin must be string only
  • Assuming method affects origin check
  • Believing array format causes error
4. Identify the error in this Express CORS setup that aims to allow only 'https://site.com':
app.use(cors({ origin: 'https://site.com', methods: ['GET', 'POST'] }));
app.use(cors());
medium
A. Calling cors() twice causes conflict and overrides settings
B. The methods option is invalid in cors middleware
C. The origin value should be an array, not a string
D. Missing next() call in middleware

Solution

  1. Step 1: Check middleware usage order

    Calling cors() twice means the second call overrides the first, ignoring origin restrictions.
  2. Step 2: Confirm methods option is valid

    The methods option is valid to restrict HTTP methods, so no error there.
  3. Final Answer:

    Calling cors() twice causes conflict and overrides settings -> Option A
  4. Quick Check:

    Multiple cors calls override previous config [OK]
Hint: Only call cors once with all options [OK]
Common Mistakes:
  • Calling cors middleware multiple times
  • Thinking origin must be array always
  • Ignoring middleware order effects
5. You want to allow requests only from origins that end with '.trusted.com' dynamically in Express. Which cors configuration correctly implements this?
hard
A. app.use(cors({ origin: ['*.trusted.com'] }));
B. app.use(cors({ origin: (origin, callback) => { if (origin.includes('.trusted.com')) callback(null, true); else callback(new Error('Not allowed')); } }));
C. app.use(cors({ origin: '/^https:\/\/.*\.trusted\.com$/' }));
D. app.use(cors({ origin: (origin, callback) => { if (origin.endsWith('.trusted.com')) callback(null, true); else callback(new Error('Not allowed')); } }));

Solution

  1. Step 1: Understand dynamic origin checking

    To allow origins ending with '.trusted.com', a function can check the origin string dynamically.
  2. Step 2: Evaluate each option's approach

    app.use(cors({ origin: (origin, callback) => { if (origin.endsWith('.trusted.com')) callback(null, true); else callback(new Error('Not allowed')); } })); uses a function with endsWith to precisely match the domain ending, which is correct. app.use(cors({ origin: ['*.trusted.com'] })); uses wildcard string which is not supported. app.use(cors({ origin: '/^https:\/\/.*\.trusted\.com$/' })); uses regex but cors does not accept regex directly. app.use(cors({ origin: (origin, callback) => { if (origin.includes('.trusted.com')) callback(null, true); else callback(new Error('Not allowed')); } })); uses includes which may allow unwanted matches.
  3. Final Answer:

    app.use(cors({ origin: (origin, callback) => { if (origin.endsWith('.trusted.com')) callback(null, true); else callback(new Error('Not allowed')); } })); -> Option D
  4. Quick Check:

    Use function with endsWith for dynamic origin [OK]
Hint: Use function with endsWith() to allow domain patterns [OK]
Common Mistakes:
  • Using wildcard strings in origin array
  • Passing regex directly as origin
  • Using includes() instead of endsWith()