search
Tutorials

Fix: CORS preflight response is invalid error

Quick fix for 'CORS preflight response is invalid' error. Learn how to properly configure CORS headers for preflight requests.

person By Gautam Sharma
calendar_today January 8, 2026
schedule 2 min read
CORS HTTP Headers API Error Fix Web Development

The ‘CORS preflight response is invalid’ error occurs when the OPTIONS preflight request doesn’t return the required CORS headers or returns invalid values.


How the Error Happens

❌ Error Scenario:

// ❌ This causes preflight errors
app.options('/api/data', (req, res) => {
  res.header('Access-Control-Allow-Origin', '*'); // ❌ Too permissive for credentials
  res.header('Access-Control-Allow-Methods', 'GET'); // ❌ Missing POST, PUT, DELETE
  res.header('Access-Control-Allow-Headers', 'Content-Type'); // ❌ Missing custom headers
  res.sendStatus(200);
});

✅ Quick Fix - Proper Preflight Configuration

Solution 1: Express.js with CORS

// ✅ Proper CORS configuration
const cors = require('cors');

// ✅ Configure CORS with specific options
const corsOptions = {
  origin: ['http://localhost:3000', 'https://yourdomain.com'], // ✅ Specific origins
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], // ✅ All required methods
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'], // ✅ Required headers
  credentials: true, // ✅ If using credentials
  optionsSuccessStatus: 200 // ✅ Some legacy browsers
};

app.use('/api/', cors(corsOptions));

// ✅ Your API routes
app.post('/api/data', (req, res) => {
  res.json({ message: 'Success' });
});

Solution 2: Manual CORS Headers

// ✅ Manual CORS preflight handling
app.use('/api/', (req, res, next) => {
  // ✅ Handle preflight requests
  if (req.method === 'OPTIONS') {
    res.header('Access-Control-Allow-Origin', 'https://yourdomain.com'); // ✅ Specific origin
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); // ✅ All methods
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With'); // ✅ All headers
    res.header('Access-Control-Max-Age', '86400'); // ✅ Cache preflight for 24 hours
    res.sendStatus(200);
    return;
  }
  
  // ✅ Set headers for actual requests
  res.header('Access-Control-Allow-Origin', 'https://yourdomain.com');
  res.header('Access-Control-Allow-Credentials', 'true');
  
  next();
});

Solution 3: Custom CORS Middleware

// ✅ Custom CORS middleware
const corsMiddleware = (req, res, next) => {
  // ✅ Set CORS headers
  res.header('Access-Control-Allow-Origin', req.headers.origin || 'https://yourdomain.com');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Max-Age', '86400');
  
  // ✅ Handle preflight requests
  if (req.method === 'OPTIONS') {
    res.sendStatus(200);
    return;
  }
  
  next();
};

app.use('/api/', corsMiddleware);

Solution 4: Framework-Specific Solutions

// ✅ For Fastify
const fastify = require('fastify')({ logger: true });

fastify.register(require('@fastify/cors'), {
  origin: ['http://localhost:3000', 'https://yourdomain.com'],
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
});

// ✅ For Next.js API routes
// pages/api/data.js
export default function handler(req, res) {
  // ✅ Set CORS headers
  res.setHeader('Access-Control-Allow-Origin', 'https://yourdomain.com');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  
  if (req.method === 'OPTIONS') {
    res.status(200).end();
    return;
  }
  
  // ✅ Your API logic
  res.status(200).json({ message: 'Success' });
}
Gautam Sharma

About Gautam Sharma

Full-stack developer and tech blogger sharing coding tutorials and best practices

Related Articles

Tutorials

Fix: 429 Too Many Requests error

Quick fix for '429 Too Many Requests' error. Learn how to implement rate limiting and handle API rate limits effectively.

January 8, 2026
Tutorials

How to Fix: 403 Forbidden Error - Complete Tutorial

Complete guide to fix 403 Forbidden errors. Learn how to resolve permission issues with practical solutions, authorization management, and best practices for secure API communication.

January 8, 2026
Tutorials

Fix: 401 Unauthorized Error - Complete Guide to Authentication Issues

Complete guide to fix 401 Unauthorized errors. Learn how to resolve authentication issues with practical solutions, token management, and best practices for secure API communication.

January 8, 2026