CORS Error: No Access-Control-Allow-Origin Header - 5 Solutions
Complete guide to fixing CORS errors in your web applications. Learn 5 different approaches from proxy setup to server configuration.
The Error
Access to fetch at 'https://api.example.com' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present.What is CORS?
Cross-Origin Resource Sharing (CORS) is a security feature that restricts web pages from making requests to a different domain than the one serving the page.
5 Solutions
1. Add CORS Headers to Your Backend
Express.js example:
const express = require('express')
const app = express()
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
next()
})
// Or use cors package
const cors = require('cors')
app.use(cors())2. Use Next.js API Routes as Proxy
// app/api/proxy/route.ts
export async function GET(request: Request) {
const { searchParams } = new URL(request.url)
const url = searchParams.get('url')
const response = await fetch(url!)
const data = await response.json()
return Response.json(data)
}
// Client-side
fetch('/api/proxy?url=https://api.example.com/data')3. Configure next.config.js Rewrites
// next.config.js
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'https://api.example.com/:path*',
},
]
},
}4. Development: Use Proxy in package.json (Create React App)
// package.json
{
"proxy": "https://api.example.com"
}5. Use CORS Anywhere (Development Only)
const proxyUrl = 'https://cors-anywhere.herokuapp.com/'
const apiUrl = 'https://api.example.com/data'
fetch(proxyUrl + apiUrl)
.then(response => response.json())Best Practice
The best solution is always to configure CORS properly on your backend server. Proxy solutions should be used as workarounds during development or when you don't control the backend.
Frustration Level Before Finding This Fix
How frustrated were you? Vote and see what others experienced!
Related Articles
Hydration Error in Next.js 13/14 - Complete Fix
Fix "Hydration failed because the initial UI does not match what was rendered on the server" error in Next.js with 5 proven solutions.
Module Not Found: Can't Resolve '@/...' in Next.js - Fixed
Solve the "Module not found: Can't resolve '@/components'" error in Next.js. Step-by-step fix for path aliases and TypeScript configuration.
Too Many Re-renders in React - Why & How to Fix
Understanding and fixing "Too many re-renders. React limits the number of renders" error. Learn about common causes and solutions.