No articles found
Try different keywords or browse our categories
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.
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' });
} Related Articles
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.
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.
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.