Backend

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.

5 min read
CORSAPIBackendSecurity

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!

Share this article

Share:
K

Kushagra Kukreti

Full-Stack Developer specializing in React, Next.js, and TypeScript. Sharing short, crisp solutions to common development issues.