ViteCORSError Fix2026 Updated

Vite CORS Error: Access to Fetch Blocked— Fixed [Complete Guide 2026]

Also covers: No Access-Control-Allow-Origin · credentials · proxy setup · production CORS

January 20267 min readVite · React · Node.js · Express

⚡ The Error

Error
Access to fetch at 'http://localhost:3000/api/users'
from origin 'http://localhost:5173' has been blocked
by CORS policy: No 'Access-Control-Allow-Origin'
header is present on the requested resource.

✅ Fastest Fix — Vite Proxy

vite.config.ts
export default defineConfig({
  server: {
    proxy: {
      "/api": "http://localhost:3000",  // browser never sees the cross-origin request
    },
  },
})

Why CORS Errors Happen in Vite Projects

CORS (Cross-Origin Resource Sharing) is a browser security policy, not a Vite limitation. When your Vite app at localhost:5173 fetches data from a backend at localhost:3000 — even on the same machine — the browser treats them as different origins and blocks the request unless the backend explicitly allows it.

The two ways to fix this are: (1) make the request appear same-origin using Vite's dev server proxy, or (2) configure your backend to send the correct Access-Control-Allow-Origin response headers. The proxy approach is simpler for development and requires no backend changes.

1

Use Vite's Dev Server Proxy

Best fix for development — no backend changes needed
3 min

Vite's server.proxy forwards matching requests from the Vite dev server — not the browser — to your backend. Since the request originates from a server (not a browser), CORS restrictions don't apply.

vite.config.ts
import { defineConfig } from "vite"
import react from "@vitejs/plugin-react"

export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      // Requests to /api/* are forwarded to localhost:3000/api/*
      "/api": {
        target: "http://localhost:3000",
        changeOrigin: true,
        // Optional: rewrite the path prefix
        // rewrite: (path) => path.replace(/^/api/, ""),
      },
    },
  },
})
In your React code — use relative paths
// Before (cross-origin — triggers CORS error)
fetch("http://localhost:3000/api/users")

// After (relative path — goes through Vite proxy)
fetch("/api/users")

// With multiple backends:
// proxy: { "/api": "http://localhost:3000", "/auth": "http://localhost:4000" }

After changing vite.config.ts, restart the dev server for the proxy to take effect. Hot Module Replacement does not reload vite.config.ts changes.

2

Add CORS Headers to Your Backend

Required for production — fix on the server side
4 min

For production (where the Vite proxy doesn't exist), your backend must send the correct CORS headers. Here's how to configure CORS in the most common Node.js frameworks:

Express.js — using the cors package
npm install cors
npm install --save-dev @types/cors
server.ts (Express)
import express from "express"
import cors from "cors"

const app = express()

app.use(cors({
  origin: [
    "http://localhost:5173",         // Vite dev
    "https://yourapp.vercel.app",    // Production frontend
  ],
  methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
  allowedHeaders: ["Content-Type", "Authorization"],
  credentials: true,                 // needed for cookies
}))

app.get("/api/users", (req, res) => {
  res.json({ users: [] })
})

app.listen(3000)
Fastify
import Fastify from "fastify"
import cors from "@fastify/cors"

const app = Fastify()

await app.register(cors, {
  origin: ["http://localhost:5173", "https://yourapp.com"],
  credentials: true,
})
3

Fix CORS With Credentials (Cookies / Auth Headers)

CORS works but fails with credentials: include
4 min

If you use credentials: 'include' in your fetch calls (needed for cookies and session-based auth), both the client and server need additional configuration. Using a wildcard * for the origin is not allowed when credentials are enabled.

Frontend — fetch with credentials
// Must use credentials: "include" for cookies to be sent
fetch("/api/profile", {
  credentials: "include",
  headers: {
    "Content-Type": "application/json",
  },
})
Vite proxy — forward credentials
// vite.config.ts
server: {
  proxy: {
    "/api": {
      target: "http://localhost:3000",
      changeOrigin: true,
      secure: false,
      configure: (proxy) => {
        proxy.on("proxyReq", (proxyReq) => {
          // Forward cookies through the proxy
          proxyReq.setHeader("origin", "http://localhost:3000")
        })
      },
    },
  },
}
Backend — must specify exact origin, not wildcard
app.use(cors({
  // ❌ Wrong — wildcard forbidden with credentials
  // origin: "*",

  // ✅ Correct — explicit origin required
  origin: "http://localhost:5173",
  credentials: true,  // Access-Control-Allow-Credentials: true
}))

Never use origin: '*' with credentials: true. The browser will block the request — this is not a bug in Vite or your backend. Always specify an explicit origin when using credentials.

4

Fix CORS in Production

Vite proxy only works in development
4 min

The Vite dev server proxy does not run in production (npm run build produces static files). In production, use a reverse proxy to route API calls through the same origin as your frontend, or configure your backend with the correct CORS headers for your production domain.

Vercel — vercel.json rewrites
{
  "rewrites": [
    {
      "source": "/api/:path*",
      "destination": "https://your-backend.com/api/:path*"
    }
  ]
}
Netlify — netlify.toml redirects
[[redirects]]
  from = "/api/*"
  to = "https://your-backend.com/api/:splat"
  status = 200
  force = true
Nginx — reverse proxy config
server {
  listen 80;
  server_name yourapp.com;

  # Serve Vite static files
  location / {
    root /var/www/dist;
    try_files $uri $uri/ /index.html;
  }

  # Proxy /api to backend — same origin, no CORS needed
  location /api/ {
    proxy_pass http://localhost:3000/api/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
  }
}
5

Fix Wildcard CORS Misconfiguration

Preflight OPTIONS requests failing
2 min

If you set Access-Control-Allow-Origin: * and still see CORS errors, the issue is often a missing response to the browser's OPTIONS preflight request. Your backend must handle OPTIONS explicitly.

Express — handle OPTIONS preflight
// Option A: cors() middleware handles OPTIONS automatically
app.use(cors({ origin: "https://yourapp.com" }))

// Option B: manual preflight handler
app.options("*", (req, res) => {
  res.setHeader("Access-Control-Allow-Origin", "https://yourapp.com")
  res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS")
  res.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization")
  res.status(204).send()
})

Prevention

Frequently Asked Questions

Why am I getting a CORS error in my Vite app?+
CORS errors happen when your Vite dev server (localhost:5173) makes a request to a backend on a different origin — for example, localhost:3000 or an external API. The browser blocks cross-origin requests unless the server explicitly allows them via CORS headers. This is a browser security policy, not a Vite bug.
How do I fix CORS in Vite development?+
The cleanest development fix is to configure Vite's built-in proxy in vite.config.ts. The proxy makes requests from Vite's server (not the browser), so CORS restrictions don't apply. Set server.proxy to forward /api requests to your backend.
Does Vite have a built-in CORS fix?+
Yes. Vite's server.proxy option proxies API requests through the Vite dev server itself, bypassing browser CORS restrictions entirely. This is the recommended solution for development. For production, you need proper CORS headers on your backend or a reverse proxy.
Why does my CORS error say 'No Access-Control-Allow-Origin header'?+
Your backend is not sending the Access-Control-Allow-Origin header. You need to configure your backend server (Express, Fastify, Django, etc.) to include this header. For development, the Vite proxy avoids needing this entirely.
CORS works without credentials but fails with cookies — why?+
When you send cookies or use credentials: 'include' in fetch, the server must respond with Access-Control-Allow-Credentials: true AND specify an exact origin (not wildcard *) in Access-Control-Allow-Origin. Using * with credentials is forbidden by the browser.
How do I fix CORS in Vite production build?+
In production, the Vite proxy does not exist. You need either: 1) Configure CORS headers on your backend to allow your production domain, or 2) Set up a reverse proxy (Nginx, Vercel rewrites, Netlify redirects) to route API calls through the same origin as your frontend.

Need Expert Help?

We Build & Deploy Vite + React Applications

Softplix engineers build production-ready Vite applications with proper API architecture. Struggling with CORS, deployment, or backend integration? Let us help.

Talk to an Engineer