CORS lets your server control which websites can talk to it. It helps keep your app safe by blocking unwanted access.
0
0
CORS configuration in Node.js
Introduction
When your frontend and backend are on different websites or ports.
When you want to allow only certain websites to use your API.
When you want to prevent other sites from reading your server data.
When building a public API that needs to control who can access it.
When debugging frontend errors related to blocked requests.
Syntax
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.
Examples
Allow all websites to access your server (not secure for private APIs).
Node.js
app.use(cors());
Only allow requests from
https://myfrontend.com.Node.js
app.use(cors({ origin: 'https://myfrontend.com' }));Allow multiple specific websites to access your server.
Node.js
app.use(cors({ origin: ['https://site1.com', 'https://site2.com'] }));Allow only GET and POST requests with Content-Type header from example.com.
Node.js
app.use(cors({
origin: 'https://example.com',
methods: ['GET', 'POST'],
allowedHeaders: ['Content-Type']
}));Sample Program
This server only accepts requests from https://myfrontend.com. If you try from another site, the browser will block the request.
Node.js
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'); });
OutputSuccess
Important Notes
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.
Summary
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.