Proxying API requests and cookies with Vite
Configure the Vite development proxy for same-origin API requests, path rewriting, WebSocket forwarding, and local session cookie handling.
When the SPA uses Vite on port 5173 and the API listens on port 8080, even two localhost URLs can be cross-origin. I route local API requests through Vite so I can keep relative URLs in the browser and inspect the session cookie the browser actually receives.
Separate origin checks from cookie checks
An origin is a scheme, host, and port. http://localhost:5173 and http://localhost:8080 have different origins, even though their hostname is the same. Calling the API directly may require CORS response headers and an OPTIONS preflight, depending on the request. Credentialed cross-origin requests have their own browser and server requirements.
Cookie eligibility is a separate check. Two localhost ports can be same-site. Cookies do not have a port attribute. Domain, Path, SameSite, and Secure still determine what the browser stores and sends. A cookie issued for .backend.internal cannot be accepted for localhost simply by enabling CORS. Inspecting both the request origin and the server’s exact Set-Cookie value makes the failure easier to locate.
Follow the request through Vite
A relative request such as fetch('/api/v1/users/me') goes to the origin that served the page. Vite matches the path and opens a server-side connection to the backend. To the browser, the URL and the returned response remain on localhost:5173. The API stays on localhost:8080.
sequenceDiagram
autonumber
actor Browser as Browser (localhost:5173)
participant Vite as Vite Dev Server (localhost:5173)
participant Backend as Backend API (localhost:8080)
Note over Browser,Vite: The browser uses one origin (localhost:5173)
Browser->>Vite: GET /api/v1/users/me (Cookie: SESSIONID=...)
Note over Vite: 1. Match the proxy route<br/>2. Strip the configured prefix<br/>3. Change the upstream Host header
Vite->>Backend: GET /v1/users/me (Host: localhost:8080)
Backend-->>Vite: 200 OK (Set-Cookie: SESSIONID=...; Domain=8080)
Note over Vite: The proxyRes hook adjusts Set-Cookie for localhost
Vite-->>Browser: 200 OK (Set-Cookie: SESSIONID=...; Path=/; SameSite=Lax)
Note over Browser: Same-origin response carries the cookie
The diagram shows the responsibilities in sequence. The exact rewrite is a configuration decision. In the first example, the upstream route retains /v1 because the rewrite removes only /api. The browser still sees its original request URL.
Configure the HTTP and WebSocket routes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// vite.config.ts
import { defineConfig } from 'vite';
export default defineConfig({
server: {
port: 5173,
proxy: {
// Proxy requests whose path starts with '/api'
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
secure: false,
ws: true
}
}
}
});
targetselects the upstream URL.changeOriginrewrites the upstreamHostheader to match the target. It does not change the origin shown in the browser.rewriteadapts the URL path. A call to/api/v1/usersreaches/v1/userswhen only/apiis stripped.ws: trueenables forwarding for routes that accept WebSocket upgrades. Verify the deployed proxy handles the upgrade too if your application uses SockJS, STOMP, or native WebSockets.
Vite’s configure option gives the application access to its proxy instance. The example hooks events to distinguish an outgoing request, an upstream response, and a connection error. Vite server options
Keep cookie rewriting local
If the backend sets a deployment-specific Domain, removing it makes the cookie host-only for the browser-visible host. The example also shows rewriting SameSite and removing Secure for a deliberately plain-HTTP development setup. I prefer trusted local HTTPS for testing cookies that require Secure, including SameSite=None and cookie name prefixes that impose additional restrictions.
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// vite.config.ts
import { defineConfig } from 'vite';
import type { HttpProxy } from 'vite';
export default defineConfig({
server: {
port: 5173,
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
configure: (proxy: HttpProxy.Server) => {
// 1. Log the proxied request for debugging
proxy.on('proxyReq', (proxyReq, req) => {
console.log(`[vite:proxy] ${req.method} ${req.url} -> ${proxyReq.path}`);
});
// 2. Rework Set-Cookie on the upstream response
proxy.on('proxyRes', (proxyRes, req, res) => {
const setCookieHeaders = proxyRes.headers['set-cookie'];
if (setCookieHeaders) {
const rewrittenCookies = setCookieHeaders.map((cookieStr) => {
return cookieStr
// Remove the upstream Domain to make the cookie host-only
.replace(/Domain=[^;]+;?/gi, '')
// Local HTTP example only: remove Secure
.replace(/Secure;?/gi, '')
// Set the local session policy to SameSite=Lax
.replace(/SameSite=Strict/gi, 'SameSite=Lax')
.trim();
});
// Return the rewritten headers to the browser
proxyRes.headers['set-cookie'] = rewrittenCookies;
console.log('[vite:proxy] Rewritten Set-Cookie for local dev:', rewrittenCookies);
}
});
// 3. Handle an upstream connection failure
proxy.on('error', (err, req, res) => {
console.error('[vite:proxy] Proxy error encountered:', err.message);
});
}
}
}
}
});
Keep the rewrite in development config and preserve the original policy in production. Check each cookie’s purpose before changing its attributes. A cookie with a suitable domain can still fail if its
Pathno longer matches the browser-visible route.
The hook processes each Set-Cookie header individually. That matters when the login response sets more than one cookie or includes an Expires date containing a comma. Keep attributes such as HttpOnly intact, and confirm the actual stored attributes in browser developer tools.
Verify the forwarded route and the session
Figure 1. Vite accepts the /api request on port 5173 and the upstream route returns a successful response.
I verify the final upstream path, request host, and response code on the API call before inspecting login. That narrows a 404 down to routing and keeps it separate from a failure to store a cookie.
Figure 2. The proxy returns the adjusted Set-Cookie header to the browser-visible host.
The next check is an authenticated browser request. A successful login response establishes what the server tried to set. The follow-up request establishes whether the browser stored the cookie and sent it back.
Match the public route to production
I keep /api as the frontend base path and let the development proxy and production gateway map it upstream. Nginx and a cloud API gateway can both serve that public shape, but I test path rewriting, upgrades, and cookie policies on the deployed configuration as well. The local HTTPS setup is useful when the browser should enforce the same transport policy during development.