DEV Community

KISHAN RAMLAKHAN NISHAD
KISHAN RAMLAKHAN NISHAD

Posted on

What is CORS in Node.js?

CORS (Cross-Origin Resource Sharing) is a security feature in web browsers that blocks requests from different origins (domains) unless the server explicitly allows them.

By default, browsers block requests if:

Solution: Use cors Middleware in Express
The cors package helps enable cross-origin requests in Express.

Installation:
npm install cors

Basic Usage in Express:

const express = require('express');
const cors = require('cors');

const app = express();

// Enable CORS for all requests
app.use(cors());

app.get('/data', (req, res) => {
    res.json({ message: 'CORS enabled!' });
});

app.listen(5000, () => console.log('Server running on port 5000'));

Enter fullscreen mode Exit fullscreen mode

Allow Specific Origins Only
If you want to restrict which frontend domains can access your API:

app.use(cors({
    origin: 'http://localhost:3000' // Allow only this frontend
}));

Enter fullscreen mode Exit fullscreen mode

Allow Multiple Origins
For multiple domains:

const allowedOrigins = ['http://localhost:3000', 'https://mywebsite.com'];

app.use(cors({
    origin: function (origin, callback) {
        if (!origin || allowedOrigins.includes(origin)) {
            callback(null, true);
        } else {
            callback(new Error('Not allowed by CORS'));
        }
    }
}));

Enter fullscreen mode Exit fullscreen mode

Enable CORS for Specific Routes Only

app.get('/public', cors(), (req, res) => {
    res.json({ message: 'Public data, CORS enabled' });
});

app.get('/private', (req, res) => {
    res.json({ message: 'Private data, CORS disabled' });
});

Enter fullscreen mode Exit fullscreen mode

Allow Specific Methods & Headers
You can customize allowed HTTP methods and headers:

app.use(cors({
    origin: '*', // Allow all origins
    methods: ['GET', 'POST', 'PUT', 'DELETE'], // Allow only these HTTP methods
    allowedHeaders: ['Content-Type', 'Authorization'] // Allow specific headers
}));

Enter fullscreen mode Exit fullscreen mode

Why Use cors?
✅ Fixes CORS errors when calling APIs from different origins
✅ Allows frontend to talk to backend
✅ Can restrict or allow specific domains
✅ Supports custom headers and methods

Let me know if you need CORS settings for production! 🚀

Top comments (0)