---
title: "Vite Proxies an API Request but the Browser Drops Session Cookies on the Response"
description: "The proxied request succeeds, yet the browser ignores `Set-Cookie` because the proxy and cookie attributes do not line up."
url: "/vite-proxies-an-api-request-but-the-browser-drops-session-cookies-on-the-response"
canonical_url: "https://bfzli.com/vite-proxies-an-api-request-but-the-browser-drops-session-cookies-on-the-response"
source_url: "https://bfzli.com/vite-proxies-an-api-request-but-the-browser-drops-session-cookies-on-the-response.md"
type: "article"
updated: "2026-12-01"
date: "2026-12-01"
tags: ["vite", "proxy", "cookies", "browser"]
---

> Markdown copy of https://bfzli.com/vite-proxies-an-api-request-but-the-browser-drops-session-cookies-on-the-response. Append `.md` to any page path on bfzli.com for its markdown twin. Full index: https://bfzli.com/llms.txt

# 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:

- `Domain`
- `Path`
- `SameSite`
- `Secure`
- `HttpOnly`
- 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 `Secure` cookies 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.test` does not match the response host `localhost`
- 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=localhost` is often problematic because `localhost` is treated specially and some stacks reject or mishandle it.
- If the response comes from `localhost`, omit `Domain` unless you have a specific cross-subdomain setup.
- If you need multiple subdomains in dev, use a real local domain such as `app.local.test` and `api.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=/api` sends 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=Lax` is the default in modern browsers when omitted.
- `SameSite=Strict` is the most restrictive.
- `SameSite=None` allows cross-site use, but requires `Secure`.

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://localhost` cannot receive `Secure` cookies
- `https://localhost` can, 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: true`
- `sameSite: 'lax'`
- `secure: false` for plain HTTP dev
- `path: '/'`

If the frontend and API are actually on different sites, use HTTPS and switch to:

```ts
res.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.

```ts
res.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=Lax` if the request is same-site and the proxy keeps it that way

### Wrong `Domain`

```ts
res.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`

```ts
res.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.

```ts
fetch('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=Lax` or the default same-site behavior
- the cookie has `Secure: false`
- the cookie `Domain` is omitted or matches the visible host
- the cookie `Path` covers 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 `Secure` cookies 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 url`
- `This 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.
