DEV Community

Tanmay Gupta
Tanmay Gupta

Posted on

Handling CORS in Express

When building APIs with Express, you may run into a common browser security issue called CORS. This post explains what CORS is, why it matters, and how to handle it properly in your Express applications.


What is CORS?

CORS (Cross-Origin Resource Sharing) is a browser security feature that restricts requests from one origin (domain, protocol, port) to another.

For example, if your frontend is hosted on http://localhost:3000 and it tries to access an API at http://localhost:5000, the browser treats this as a cross-origin request. By default, the browser blocks such requests unless the server explicitly allows them.


When Do You See CORS Errors?

You’ll typically see an error like this in your browser console:

Access to fetch at 'http://localhost:5000/api' from origin 'http://localhost:3000' has been blocked by CORS policy.
Enter fullscreen mode Exit fullscreen mode

This means the backend didn’t allow your frontend’s origin to make the request.


Solution: Use the cors Package in Express

Express doesn’t handle CORS by default, but the fix is simple. Just use the cors middleware.

Step 1: Install CORS

npm install cors
Enter fullscreen mode Exit fullscreen mode

Step 2: Enable CORS in Your Express App

import cors from 'cors';
import express from 'express';

const app = express();

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

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

app.listen(5000, () => {
  console.log('Server running on port 5000');
});
Enter fullscreen mode Exit fullscreen mode

Customizing CORS

Want to allow only certain origins? Use options:

const corsOptions = {
  origin: 'http://localhost:3000', // Only allow this origin
  methods: ['GET', 'POST'],        // Allowed methods
  credentials: true                // Allow cookies, auth headers
};

app.use(cors(corsOptions));
Enter fullscreen mode Exit fullscreen mode

You can also provide a dynamic function to control allowed origins:

const corsOptions = {
  origin: function (origin, callback) {
    const allowedOrigins = ['http://localhost:3000', 'https://myapp.com'];
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  }
};

app.use(cors(corsOptions));
Enter fullscreen mode Exit fullscreen mode

CORS and Preflight Requests

When making PUT, DELETE, or requests with custom headers, the browser sends a preflight OPTIONS request to ask the server if it allows the actual request.

Make sure your server handles it:

app.options('*', cors());
Enter fullscreen mode Exit fullscreen mode

Summary

Concept Example
Allow all origins app.use(cors())
Allow one origin origin: 'http://localhost:3000'
Allow multiple Use a function inside origin
Handle preflight app.options('*', cors())

Final Thoughts

CORS can be frustrating, especially during frontend-backend development. But using the cors middleware makes it easy to:

  • Enable cross-origin requests
  • Protect your API from unwanted domains
  • Support cookies and custom headers

Top comments (0)