CORS lets your server control which websites can talk to it. It helps keep your app safe by blocking unwanted access.
CORS configuration in Node.js
import express from 'express'; import cors from 'cors'; const app = express(); app.use(cors({ origin: 'https://example.com', methods: ['GET', 'POST'], allowedHeaders: ['Content-Type', 'Authorization'] }));
The origin option sets which website can access your server.
You can list allowed HTTP methods and headers to be more specific.
app.use(cors());
https://myfrontend.com.app.use(cors({ origin: 'https://myfrontend.com' }));app.use(cors({ origin: ['https://site1.com', 'https://site2.com'] }));app.use(cors({
origin: 'https://example.com',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type']
}));This server only accepts requests from https://myfrontend.com. If you try from another site, the browser will block the request.
import express from 'express'; import cors from 'cors'; const app = express(); // Allow only https://myfrontend.com to access app.use(cors({ origin: 'https://myfrontend.com' })); app.get('/data', (req, res) => { res.json({ message: 'Hello from server!' }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Browsers enforce CORS, so server settings alone don't block direct calls (like curl).
Always test CORS with your frontend to avoid blocked requests.
You can customize CORS more with options like credentials, exposedHeaders, and preflightContinue.
CORS controls which websites can use your server resources.
Use the cors package in Node.js to set rules easily.
Be careful to allow only trusted sites to keep your app safe.
Practice
Solution
Step 1: Understand CORS role
CORS (Cross-Origin Resource Sharing) controls which external websites can request resources from your server.Step 2: Identify main purpose
It is not about speed, encryption, or database management but about access control from different origins.Final Answer:
To control which websites can access server resources -> Option BQuick Check:
CORS controls access = A [OK]
- Confusing CORS with encryption or speed optimization
- Thinking CORS manages databases
- Assuming CORS is a security firewall
cors middleware in an Express app?Solution
Step 1: Identify modern import syntax
Using ES modules, the correct import isimport cors from 'cors';.Step 2: Use middleware correctly
Middleware must be called as a function:app.use(cors());not justcors.Final Answer:
import cors from 'cors'; app.use(cors()); -> Option AQuick Check:
Import + call middleware = D [OK]
- Forgetting parentheses when using middleware
- Mixing require and import syntax
- Using app.use(cors) without parentheses
import express from 'express';
import cors from 'cors';
const app = express();
app.use(cors({ origin: 'https://example.com' }));
app.get('/', (req, res) => res.send('Hello'));
app.listen(3000);Solution
Step 1: Analyze the origin option
Thecorsmiddleware is configured withorigin: 'https://example.com', which restricts access to that origin only.Step 2: Understand effect on requests
Requests from other origins will be blocked by CORS policy, so only https://example.com is allowed.Final Answer:
Only requests from https://example.com will be allowed -> Option AQuick Check:
origin restricts access = C [OK]
- Assuming all origins allowed by default
- Confusing origin with methods or headers
- Thinking localhost is allowed without explicit mention
import express from 'express';
import cors from 'cors';
const app = express();
app.use(cors({ origin: ['https://site1.com', 'https://site2.com'] }));
app.listen(3000);Solution
Step 1: Check origin option type
Theoriginoption incorsaccepts an array directly for multiple static origins; it also supports string, boolean, regex, or function.Step 2: Confirm other parts are correct
Thecors()function is called correctly,app.listen()works without callback, and import syntax is valid.Final Answer:
The origin option can be an array -> Option CQuick Check:
origin array valid = B [OK]
- Thinking origin cannot accept an array
- Forgetting to call cors() as a function
- Thinking app.listen needs a callback always
https://trusted.com and http://localhost:3000. Which is the best way to configure the cors middleware in your Node.js app?Solution
Step 1: Understand multiple origins handling
Thecorspackage accepts an array directly fororiginwith a static list of allowed origins. This is the simplest and best approach here.Step 2: Evaluate options
Use function for dynamic logic (e.g., regex or env-based). '*' allows all (insecure). Manual handling is error-prone and not recommended.Final Answer:
Set origin to an array of allowed origins directly -> Option DQuick Check:
Static multiple origins use array = C [OK]
- Using '*' to allow all origins insecurely
- Using a single string for multiple origins
- Disabling middleware instead of configuring properly
Ready to prove it?
Pass the test and this pattern moves unknown
