Unbreaking Cookies in Local Dev with Vite Proxy

Vite is a popular and powerful local dev server. One of my favorite Vite features is the proxy, which allows you to develop your frontend locally against an arbitrary backend URL.

I found myself in a situation where my backend required authentication but the upstream server’s Set-Cookie directive was being ignored by my browser. The cause? The cookies were sporting the ‘Secure’ flag, and were being set with the ‘Domain’ flag equaling the real upstream’s domain name, while I needed “localhost”.

When both a lot of Googling and even praying to the LLM gods didn’t offer a viable solution, I had to stumble through finding it myself. Here’s the vite.config.js which resolves this challenge:

import { defineConfig } from 'vite'

// https://vitejs.dev/config/
export default defineConfig({
  server: {
    proxy: {
      '/auth': {
        target: 'https://example.com',
        changeOrigin: true,
        configure: (proxy, options) => {
          proxy.on('proxyRes', (proxyRes, req, res) => {
            const cookies = proxyRes.headers['set-cookie'];
            if (cookies) {
              proxyRes.headers['set-cookie'] = cookies.map(cookie =>
                cookie
                  .replace(/;\s*Secure/i, '')
                  .replace(/domain=[^;]+/i, 'domain=localhost')
              );
            }
          });
        }
      }
    }
  }
})

Quick note: in my case, the backend was utilizing the authlib library for Python and Auth0 as the identity provider. To be able to have a successful auth redirect to localhost, I also had to add http://localhost:5173 to both the allowed origins and allowed callback URLs. You would generally not want to do this in a production setting.