Discover how a simple setting can protect your server from sneaky unauthorized requests!
Configuring allowed origins in Express - Why You Should Know This
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a web server that should only accept requests from your own website, but you try to manually check the origin of every request by writing custom code for each route.
Manually checking origins is slow, repetitive, and easy to forget. It can lead to security holes if you miss a route or make a typo. Also, handling errors and headers correctly is tricky and error-prone.
Configuring allowed origins using middleware like CORS in Express automatically handles origin checks, sets the right headers, and blocks unwanted requests, making your server secure and your code clean.
app.use((req, res, next) => {
if (req.headers.origin === 'https://mywebsite.com') {
next();
} else {
res.status(403).send('Forbidden');
}
});const cors = require('cors'); app.use(cors({ origin: 'https://mywebsite.com' }));
This lets your server safely share resources only with trusted websites without extra code for each request.
A company website uses this to allow its frontend app to fetch data securely from the backend API, while blocking requests from unknown sites trying to steal data.
Manual origin checks are repetitive and risky.
Middleware like CORS automates and secures origin configuration.
Proper origin setup protects your server and simplifies code.
Practice
cors middleware?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]
- Confusing allowed origins with encryption
- Thinking it speeds up server
- Assuming it logs requests
cors middleware in Express?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]
- Using 'origins' instead of 'origin'
- Passing array for single origin string
- Calling cors without options
const cors = require('cors');
app.use(cors({ origin: ['https://allowed.com', 'https://other.com'] }));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]
- Thinking origin must be string only
- Assuming method affects origin check
- Believing array format causes error
app.use(cors({ origin: 'https://site.com', methods: ['GET', 'POST'] }));
app.use(cors());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]
- Calling cors middleware multiple times
- Thinking origin must be array always
- Ignoring middleware order effects
cors configuration correctly implements this?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]
- Using wildcard strings in origin array
- Passing regex directly as origin
- Using includes() instead of endsWith()
