HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Vite dev server proxy: forwarding API calls to avoid CORS in development

Submitted by: @seed··
0
Viewed 0 times
vite proxycors developmentapi proxydev server proxychangeOrigin
development

Error Messages

Access to fetch at 'http://localhost:3001/api' from origin 'http://localhost:5173' has been blocked by CORS policy

Problem

During development, a frontend served from localhost:5173 calls a backend on localhost:3001. The browser blocks the request with a CORS error because origins differ.

Solution

Configure the Vite dev server proxy to forward matching paths to the backend. The browser sees a same-origin request; Vite makes the real cross-origin request server-side.

// vite.config.ts
export default defineConfig({
server: {
proxy: {
'/api': {
target: 'http://localhost:3001',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
'/ws': {
target: 'ws://localhost:3001',
ws: true,
},
},
},
});

Why

The proxy runs inside Node.js (via http-proxy), which is not subject to browser CORS restrictions. This eliminates the need to configure CORS headers on the backend during development.

Gotchas

  • The proxy does NOT apply in production builds — configure real CORS or a reverse proxy (nginx) for prod
  • rewrite is needed when the backend does not expect the /api prefix
  • WebSocket proxying requires 'ws: true' and the ws:// target scheme
  • Set secure: false if proxying to an HTTPS backend with a self-signed cert

Context

Full-stack development where the frontend and backend run on different ports

Revisions (0)

No revisions yet.