Vite Proxies an API Request but the Browser Drops Session Cookies on the Response
Browser login succeeds, but the session cookie never appears in DevTools and never comes back on the next API call. In Chrome this often shows up as Set-Cookie was blocked because it had the "SameSite=None" attribute but was not marked "Secure" or as a cookie that is present in the response headers but missing from Application > Cookies and omitted from the follow-up request.
What Vite is proxying, and what it is not
Vite’s dev proxy forwards HTTP requests from the browser-facing dev server to an upstream API. The browser sends the request to http://localhost:5173/api/login, Vite forwards it to something like http://localhost:3000/api/login, and the API responds with Set-Cookie.
That only solves routing. It does not make the browser ignore cookie rules.
The browser still decides whether to store the cookie based on the response’s Set-Cookie attributes and the URL that received the response. If the response arrives through localhost:5173, the browser evaluates the cookie against that origin and path, not against the upstream host that actually generated it. If the cookie attributes do not match the browser’s rules, the cookie is dropped.
That is why a proxied login request can return 200 OK and still fail to persist a session.
The proxy does not rewrite cookie semantics
A Vite proxy can change the request destination. It does not change the browser’s cookie policy.
The usual Vite config looks like this:
ts// vite.config.ts import { defineConfig } from 'vite' export default defineConfig({ server: { proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true, secure: false, }, }, }, })
This forwards /api/* to the backend. changeOrigin: true changes the Host header sent upstream. secure: false allows self-signed HTTPS upstreams, if any.
None of that edits Set-Cookie unless you explicitly add cookie rewriting options. Even then, only some fields are rewritten. A browser still enforces:
DomainPathSameSiteSecureHttpOnly- expiry attributes
If the cookie says SameSite=None, the browser requires Secure. If the cookie is scoped to a domain that does not match the visible response URL, the browser rejects it. If the cookie Path does not match the request path, the browser stores it but does not send it for the endpoint you expect.
Why localhost makes this look random
localhost is special in a few ways, and that makes dev setups confusing.
If your frontend runs on http://localhost:5173 and the API is proxied through that origin, the browser sees the response as same-site only if the cookie attributes permit it. A cookie with default SameSite=Lax is usually fine for same-site navigation and same-site XHR/fetch, but it will not be sent in many cross-site contexts. A cookie with SameSite=None must also have Secure, which means it needs HTTPS. On plain http://localhost, that cookie is rejected.
That creates a common mismatch:
- backend sets
Set-Cookie: sid=abc; SameSite=None; Secure; HttpOnly - frontend is on
http://localhost:5173 - browser receives the response over plain HTTP
- browser blocks the cookie because
Securecookies require HTTPS
Or:
- backend sets
Set-Cookie: sid=abc; Domain=api.local.test; Path=/ - browser receives the response from
http://localhost:5173/api/login Domain=api.local.testdoes not match the response hostlocalhost- browser ignores the cookie
The proxy makes the API reachable, but it does not make those attributes compatible.
The browser rules that matter
The browser applies cookie storage rules after it receives the response. The key ones are:
Domain
A cookie is only accepted for a host or parent domain that matches the Domain attribute.
Domain=localhostis often problematic becauselocalhostis treated specially and some stacks reject or mishandle it.- If the response comes from
localhost, omitDomainunless you have a specific cross-subdomain setup. - If you need multiple subdomains in dev, use a real local domain such as
app.local.testandapi.local.test.
Path
The cookie is only sent for matching request paths.
For example:
Path=/sends the cookie to all paths on the origin.Path=/apisends it only to/api/*.
If login sets Path=/api/login by mistake, the browser may store the cookie but never send it on /api/me.
SameSite
SameSite controls when cookies are sent in cross-site requests.
SameSite=Laxis the default in modern browsers when omitted.SameSite=Strictis the most restrictive.SameSite=Noneallows cross-site use, but requiresSecure.
If your frontend and backend are on different sites, SameSite=None; Secure is usually required.
Secure
Secure cookies are only stored or sent over HTTPS.
That means:
http://localhostcannot receiveSecurecookieshttps://localhostcan, if the certificate is trusted by the browser- a dev proxy over plain HTTP does not satisfy
Secure
HttpOnly
HttpOnly does not affect storage or sending. It only prevents JavaScript from reading the cookie with document.cookie.
For session cookies, HttpOnly should usually be enabled.
A working Vite proxy for session cookies
If frontend and API are both on localhost but different ports, the simplest setup is often to keep the cookie same-site and same-origin from the browser’s perspective by proxying API requests through Vite and using a cookie path of /.
Here is a Vite config that forwards /api and preserves the upstream response:
ts// vite.config.ts import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], server: { proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true, secure: false, }, }, }, })
And a client request:
ts// src/auth.ts export async function login(email: string, password: string) { const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, credentials: 'include', body: JSON.stringify({ email, password }), }) if (!response.ok) { throw new Error(`Login failed: ${response.status}`) } return response.json() }
credentials: 'include' matters when the request is cross-origin. When the proxy keeps the browser-facing URL on the same origin, it is still safe to include it, and it avoids accidental omission if the setup changes later.
The cookie settings that the browser will accept
On the backend, set the cookie attributes to match the actual dev transport.
For a proxied http://localhost:5173 frontend talking to an API on http://localhost:3000, this is usually the safest shape:
ts// server/auth.ts import type { Request, Response } from 'express' import express from 'express' const app = express() app.use(express.json()) app.post('/api/login', async (_req: Request, res: Response) => { const sessionId = 'generated-session-id' res.cookie('sid', sessionId, { httpOnly: true, sameSite: 'lax', secure: false, path: '/', }) res.json({ ok: true }) }) app.get('/api/me', (req: Request, res: Response) => { const sid = req.headers.cookie?.includes('sid=') if (!sid) { return res.status(401).json({ error: 'unauthorized' }) } res.json({ user: { id: '123' } }) })
For Express, the res.cookie() API comes from the app itself, not from a separate package. The important part is the attribute set:
httpOnly: truesameSite: 'lax'secure: falsefor plain HTTP devpath: '/'
If the frontend and API are actually on different sites, use HTTPS and switch to:
tsres.cookie('sid', sessionId, { httpOnly: true, sameSite: 'none', secure: true, path: '/', })
That combination is required by modern browsers. SameSite=None without Secure is rejected.
What goes wrong with the wrong cookie attributes
A few specific misconfigurations produce the exact symptom where login appears successful but the session vanishes.
SameSite=None on HTTP
This is the most common failure.
tsres.cookie('sid', sessionId, { sameSite: 'none', secure: true, })
On http://localhost, the browser blocks it. Chrome reports:
This Set-Cookie was blocked because it had the "SameSite=None" attribute but was not marked "Secure"
The fix is either:
- use HTTPS in dev, or
- use
SameSite=Laxif the request is same-site and the proxy keeps it that way
Wrong Domain
tsres.cookie('sid', sessionId, { domain: 'api.local.test', path: '/', })
If the browser receives the response from localhost, it may refuse the cookie because the domain does not match the response host. For localhost dev, omit domain unless you are deliberately using local wildcard domains and a trusted cert.
Too narrow Path
tsres.cookie('sid', sessionId, { path: '/api/login', })
That cookie will not be sent to /api/me. The browser may store it, but the follow-up request still looks unauthenticated because the path filter excludes it.
Missing credentials: 'include'
If the frontend is not actually same-origin with the API, fetch will not send or accept cookies unless you opt in.
tsfetch('http://localhost:3000/api/login', { method: 'POST', credentials: 'include', })
Without credentials: 'include', the browser can ignore Set-Cookie on a cross-origin response.
When Vite proxying is enough, and when HTTPS is required
A Vite proxy is enough when:
- frontend and API are effectively same-site in dev
- the cookie uses
SameSite=Laxor the default same-site behavior - the cookie has
Secure: false - the cookie
Domainis omitted or matches the visible host - the cookie
Pathcovers the requests that need it
HTTPS is required when:
- the cookie must use
SameSite=None - you need a cross-site cookie in dev
- your production setup uses
Securecookies and you want dev to match it closely
For HTTPS localhost development, run Vite with a trusted cert and use a matching secure backend. Vite can be started with HTTPS support, but the exact certificate setup depends on your tooling. If you stay on plain HTTP, do not mark the cookie Secure.
How to verify the cause quickly
Use the browser devtools network panel first.
Inspect the login response and check the Set-Cookie header. If the header is missing, the backend never sent it. If the header is present but the cookie does not appear in the Application tab, the browser blocked it.
Chrome often explains the reason in the Issues panel or in the cookie section of the Network response. Typical messages include:
This Set-Cookie was blocked because it had the "SameSite=None" attribute but was not marked "Secure"This Set-Cookie was blocked because it had the "Domain" attribute that was invalid with regards to the current host urlThis Set-Cookie was blocked because its Path attribute was invalid
Then check the next request to /api/me or /api/session and confirm whether the Cookie header is present. If it is missing, the browser did not store the cookie or did not consider the request eligible for sending it.
A complete minimal setup
This combination works for local development with Vite proxying to an Express API on plain HTTP.
ts// vite.config.ts import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' export default defineConfig({ plugins: [react()], server: { proxy: { '/api': { target: 'http://localhost:3000', changeOrigin: true, }, }, }, })
ts// server.ts import express from 'express' const app = express() app.use(express.json()) app.post('/api/login', (_req, res) => { res.cookie('sid', 'session-123', { httpOnly: true, sameSite: 'lax', secure: false, path: '/', }) res.json({ ok: true }) }) app.get('/api/me', (req, res) => { const cookieHeader = req.headers.cookie ?? '' if (!cookieHeader.includes('sid=')) { return res.status(401).json({ error: 'unauthorized' }) } res.json({ user: { id: '123' } }) }) app.listen(3000)
ts// src/auth.ts export async function login() { const response = await fetch('/api/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, credentials: 'include', body: JSON.stringify({ email: 'demo@example.com', password: 'secret' }), }) if (!response.ok) { throw new Error(`Login failed: ${response.status}`) } }
Practical takeaway
Prefer keeping dev cookies same-site and plain HTTP-compatible when possible: proxy API requests through Vite, omit the cookie Domain, set Path=/, use SameSite=Lax, and leave Secure off on http://localhost. Use SameSite=None; Secure only when HTTPS is actually in place. That keeps the browser’s cookie rules aligned with the proxy route and prevents the session from disappearing after a successful login.