Skip to content

Backend CORS Security — Configuring CORS for API Security

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Backend Cors Security. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

CORS configuration controls which origins can access your API, preventing unauthorized cross-origin requests.

const cors = require('cors');

// Explicit allowed origins (NO wildcards with credentials)
const allowedOrigins = [
  'https://app.example.com',
  'https://admin.example.com',
  'https://dashboard.example.com'
];

const corsOptions = {
  origin: (origin, callback) => {
    // Allow requests with no origin (server-to-server, mobile apps)
    if (!origin) return callback(null, true);

    if (allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      logger.warn('CORS blocked origin', { origin });
      callback(new Error('Origin not allowed by CORS'));
    }
  },
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
  allowedHeaders: [
    'Content-Type',
    'Authorization',
    'X-CSRF-Token',
    'X-Requested-With',
    'X-Correlation-ID'
  ],
  exposedHeaders: [
    'X-Request-Id',
    'X-RateLimit-Remaining',
    'X-RateLimit-Reset'
  ],
  credentials: true,  // Allow cookies/auth headers
  maxAge: 86400,       // Cache preflight for 24 hours
  preflightContinue: false,
  optionsSuccessStatus: 204
};

app.use(cors(corsOptions));

// Dynamic CORS based on environment
function dynamicCors(req, res, next) {
  const origin = req.headers.origin;

  if (process.env.NODE_ENV === 'development') {
    res.setHeader('Access-Control-Allow-Origin', origin || '*');
  } else {
    const allowed = process.env.ALLOWED_ORIGINS?.split(',') || [];
    if (allowed.includes(origin)) {
      res.setHeader('Access-Control-Allow-Origin', origin);
    } else {
      return res.status(403).json({ error: 'CORS policy does not allow this origin' });
    }
  }

  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-CSRF-Token');
  res.setHeader('Access-Control-Allow-Credentials', 'true');
  res.setHeader('Access-Control-Max-Age', '86400');

  if (req.method === 'OPTIONS') return res.status(204).end();
  next();
}

Restrictive CORS policies prevent unauthorized web applications from making cross-origin requests to your API.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro