CORS & Vite

CORS is enabled by default in Vite dev server, and it allows any origin. However, you might also need to do more configurations if the API server is on another domain, which is very common during the development environment.

In this case, you need to edit the vite.config.ts or vite.config.js file in your project and configure custom proxy rules for the dev server.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
export default defineConfig({
server: {
proxy: {
// string shorthand: http://localhost:5173/foo -> http://localhost:4567/foo
'/foo': 'http://localhost:4567',
// with options: http://localhost:5173/api/bar-> http://jsonplaceholder.typicode.com/bar
'/api': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
// with RegEx: http://localhost:5173/fallback/ -> http://jsonplaceholder.typicode.com/
'^/fallback/.*': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/fallback/, ''),
},
// Using the proxy instance
'/api': {
target: 'http://jsonplaceholder.typicode.com',
changeOrigin: true,
configure: (proxy, options) => {
// proxy will be an instance of 'http-proxy'
},
},
// Proxying websockets or socket.io: ws://localhost:5173/socket.io -> ws://localhost:5174/socket.io
'/socket.io': {
target: 'ws://localhost:5174',
ws: true,
},
},
},
})