Performance: Configuring allowed origins
This affects how the server handles cross-origin requests, impacting network latency and browser security checks.
Jump into concepts and practice - no test required
const allowedOrigins = ['https://example.com', 'https://app.example.com']; app.use(cors({ origin: (origin, callback) => { if (!origin || allowedOrigins.includes(origin)) { callback(null, true); } else { callback(new Error('Not allowed by CORS')); } }}));
app.use(cors({ origin: '*' }));| Pattern | Network Requests | Preflight Requests | Security Risk | Verdict |
|---|---|---|---|---|
| Allow all origins (*) | High - all requests allowed | High - many preflights | High - security risk | [X] Bad |
| Allow specific origins | Low - only trusted domains | Low - fewer preflights | Low - secure | [OK] Good |
cors middleware?cors middlewarecors middleware in Express helps set these allowed origins to control access.cors middleware in Express?origin, not origins.origin'https://example.com' is correct.const cors = require('cors');
app.use(cors({ origin: ['https://allowed.com', 'https://other.com'] }));origin option can accept an array of allowed origins to permit multiple sites.app.use(cors({ origin: 'https://site.com', methods: ['GET', 'POST'] }));
app.use(cors());cors() twice means the second call overrides the first, ignoring origin restrictions.methods option is validmethods option is valid to restrict HTTP methods, so no error there.cors() twice causes conflict and overrides settings -> Option Acors configuration correctly implements this?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.