Configuring allowed origins helps control which websites can talk to your server. It keeps your app safe by blocking unwanted access.
Configuring allowed origins in Express
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Express
const cors = require('cors'); const corsOptions = { origin: 'https://example.com', optionsSuccessStatus: 200 }; app.use(cors(corsOptions));
The origin option sets which website is allowed.
You can use a string for one origin or a function/array for multiple origins.
Examples
https://mywebsite.com to access your server.Express
app.use(cors({ origin: 'https://mywebsite.com' }));Express
const allowedOrigins = ['https://site1.com', 'https://site2.com']; app.use(cors({ origin: function(origin, callback) { if (!origin || allowedOrigins.includes(origin)) { callback(null, true); } else { callback(new Error('Not allowed by CORS')); } } }));
Express
app.use(cors());
Sample Program
This Express server allows requests only from https://trusted.com and https://partner.com. Others get blocked by CORS.
Express
import express from 'express'; import cors from 'cors'; const app = express(); const allowedOrigins = ['https://trusted.com', 'https://partner.com']; const corsOptions = { origin: (origin, callback) => { if (!origin || allowedOrigins.includes(origin)) { callback(null, true); } else { callback(new Error('Not allowed by CORS')); } } }; app.use(cors(corsOptions)); app.get('/', (req, res) => { res.send('Hello from server!'); }); app.listen(3000, () => { console.log('Server running on port 3000'); });
Important Notes
Remember that CORS only affects browsers. Other clients like Postman are not blocked by CORS.
Always test your allowed origins carefully to avoid blocking your own app.
Summary
Configuring allowed origins controls which websites can access your server.
Use the cors middleware with the origin option to set allowed sites.
Test your settings to keep your app safe and working well.
Practice
1. What is the main purpose of configuring allowed origins in an Express app using
cors middleware?easy
Solution
Step 1: Understand what allowed origins mean
Allowed origins specify which websites are permitted to make requests to your server.Step 2: Identify the role of
Thecorsmiddlewarecorsmiddleware in Express helps set these allowed origins to control access.Final Answer:
To control which websites can access your server resources -> Option CQuick 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
Solution
Step 1: Check the correct option name for allowed origins
The correct option isorigin, notorigins.Step 2: Verify the value type for
It accepts a string for a single allowed origin, soorigin'https://example.com'is correct.Final Answer:
app.use(cors({ origin: 'https://example.com' })); -> Option BQuick 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
Solution
Step 1: Understand the origin option accepts an array
Theoriginoption can accept an array of allowed origins to permit multiple sites.Step 2: Check if 'https://allowed.com' is in the array
Since 'https://allowed.com' is listed, requests from it will be allowed.Final Answer:
The request will be allowed because 'https://allowed.com' is in the list -> Option AQuick 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
Solution
Step 1: Check middleware usage order
Callingcors()twice means the second call overrides the first, ignoring origin restrictions.Step 2: Confirm
Themethodsoption is validmethodsoption is valid to restrict HTTP methods, so no error there.Final Answer:
Callingcors()twice causes conflict and overrides settings -> Option AQuick 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
Solution
Step 1: Understand dynamic origin checking
To allow origins ending with '.trusted.com', a function can check the origin string dynamically.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 withendsWithto 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 butcorsdoes not accept regex directly. app.use(cors({ origin: (origin, callback) => { if (origin.includes('.trusted.com')) callback(null, true); else callback(new Error('Not allowed')); } })); usesincludeswhich may allow unwanted matches.Final Answer:
app.use(cors({ origin: (origin, callback) => { if (origin.endsWith('.trusted.com')) callback(null, true); else callback(new Error('Not allowed')); } })); -> Option DQuick 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()
