Handle CORS in Express.js

What is CORS?

CORS is a security feature implemented by browsers that prevents frontend JavaScript code from making requests to a different domain or port than the one from which it was loaded. It protects users from malicious websites trying to access sensitive data.

Why is CORS Important?

CORS is necessary when your frontend and backend are hosted on different domains or ports. For example, if your React app is hosted on vercel.app and your backend is hosted on railway.app, CORS must be enabled on the backend to allow the frontend to communicate with it.

How to Enable CORS in Express

First, install the cors middleware:

npm install cors

Then, use it in your Express app:

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

const app = express();
app.use(cors()); // Enables CORS for all routes

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

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

You can also customize CORS settings to allow only certain domains:

app.use(cors({
  origin: 'https://your-frontend.vercel.app'
}));

When Should You Use It?

Use CORS when:

Helpful Resources