JAVASCRIPT

Configure Secure CORS in an Express.js API

Secure your API by configuring Cross-Origin Resource Sharing (CORS) in an Express.js application, controlling which origins can access your resources to prevent unauthorized requests.

const express = require('express');
const cors = require('cors'); // npm install cors

const app = express();

// Option 1: Basic CORS - Allow all origins (NOT recommended for production APIs)
// app.use(cors());

// Option 2: Recommended - Allow specific origins for production
const allowedOrigins = ['https://your-frontend-domain.com', 'https://another-trusted-domain.com'];
app.use(cors({
  origin: function (origin, callback) {
    // allow requests with no origin (like mobile apps or curl requests)
    if (!origin) return callback(null, true);
    if (allowedOrigins.indexOf(origin) === -1) {
      const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
      return callback(new Error(msg), false);
    }
    return callback(null, true);
  },
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', // Allowed HTTP methods
  credentials: true, // Allow cookies to be sent with cross-origin requests
  optionsSuccessStatus: 204 // Some legacy browsers (IE11, various SmartTVs) choke on 200
}));

// Example route
app.get('/api/data', (req, res) => {
  res.json({ message: 'This is secure data!' });
});

app.post('/api/submit', (req, res) => {
  res.json({ message: 'Data received securely!' });
});

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
  console.log(`CORS-enabled web server listening on port ${PORT}`);
  console.log(`Try accessing http://localhost:${PORT}/api/data from 'https://your-frontend-domain.com'`);
});
How it works: This snippet demonstrates how to securely configure Cross-Origin Resource Sharing (CORS) in an Express.js application using the `cors` middleware. CORS is a browser security feature that prevents web pages from making requests to a different domain than the one that served the web page, unless explicitly allowed. The example shows how to restrict access to a specific list of `allowedOrigins`, preventing unauthorized domains from accessing your API. It also configures allowed HTTP `methods` and enables `credentials` for securely handling cookies in cross-origin requests.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs