Fix: Failed to fetch (CORS) in Vercel Serverless Functions
The Symptom
You deployed a serverless function to Vercel. Your frontend attempts an API fetch, but the browser strictly blocks the response. The network tab shows a failed OPTIONS request, and your terminal throws this policy violation:
Access to fetch at 'https://api.yourdomain.com/data' from origin 'https://frontend.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The Cure
The browser is waiting for a preflight approval. Drop this pure vanilla HTTP intercept pattern at the very top of your serverless handler before executing your main processing logic.
Immediate Resolution:
javascript
export default async function handler(req, res) {
// 1. Inject strict CORS headers into the response
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Access-Control-Allow-Origin', '*'); // Or specify 'https://yourfrontend.com'
res.setHeader('Access-Control-Allow-Methods', 'GET,OPTIONS,PATCH,DELETE,POST,PUT');
res.setHeader(
'Access-Control-Allow-Headers',
'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'
);
// 2. Intercept the OPTIONS preflight request
if (req.method === 'OPTIONS') {
res.status(200).end();
return;
}
// 3. Main Logic
res.status(200).json({ message: "API connected successfully." });
}
Loading logs...