Writing

I Switched My Dev Server to HTTPS and Login Broke — The changeOrigin Naming Trap

2026-08-06

14 mins to read

Share article

The config said changeOrigin: true, yet the Origin header was forwarded to the upstream untouched. The "origin" in that option's name and the Origin of the same-origin policy are not the same concept. This post documents a complete 403 investigation: the final fix is six lines of code, but getting there meant digging into several low-level details of how vite's proxy works.

The problem at a glance
  • Symptom: The day after I enabled HTTPS on my local dev server, the login endpoint started returning 403 with an empty body. The test and production environments were fine, and no business code had changed. Read-only pages worked perfectly; only form-submission requests failed.
  • What you'll take away: A full investigation path for "request headers passed through a proxy" (controlled variables plus bisecting with curl), a correction of the common misunderstanding about the changeOrigin option, and a checklist for what to verify after enabling HTTPS in dev.

1. Where It Started: WhatsApp Embedded Signup

I had been integrating the WhatsApp channel into an admin console. Meta provides a flow for the WhatsApp Business Platform called Embedded Signup: the merchant never leaves our page. They click a button, a Facebook JS SDK popup walks them through authorization, the frontend receives a temporary code and hands it to the backend to exchange for a token, and the WABA (WhatsApp Business Account) is linked.

The flow has one hard prerequisite: Facebook Login requires an HTTPS origin. That's a non-issue in production, which is HTTPS anyway. The problem shows up during local integration: npm run dev serves http://localhost:5173.

Local integration came with a second requirement. The Embedded Signup authorization callback endpoint needed to point at my local Python service (FastAPI, running on 127.0.0.1:8000) so I could debug it, while every other endpoint on the page (login, session, and so on) still had to go to the test environment. Two streams of traffic, routed to two places.

2. The Plan: Self-Signed HTTPS + Same-Origin Proxy Routing

Two changes (vite 5.4).

(1) Enable @vitejs/plugin-basic-ssl in dev. This official plugin generates a self-signed certificate at startup (signed by itself and trusted by no CA, which is where the browser's "Not secure" warning in the address bar comes from) so the dev server can serve over HTTPS.

(2) Empty the API baseURL and route through a same-origin proxy. The axios instance takes its baseURL from an environment variable (axios.create({ baseURL: import.meta.env.VITE_API_BASE_URL })). Leave it empty in dev and requests become relative paths sent to the page's own origin, where vite's server.proxy routes them:

# .env.development
# Empty → axios uses relative paths → requests go to the page's own origin, where vite's server.proxy takes over routing
VITE_API_BASE_URL=

Here is the complete vite.config.ts as it stood at the end of that day (all structure relevant to this post is kept, business plugins are omitted, and it can be pasted as-is for comparison):

// vite.config.ts
import { defineConfig, loadEnv, type ConfigEnv, type UserConfig } from "vite";
import basicSsl from "@vitejs/plugin-basic-ssl";

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
  // Load .env.development / .env.test / ... by mode (this post only relies on VITE_API_BASE_URL being empty)
  const env = loadEnv(mode, process.cwd());

  return {
    server: {
      port: 5173,
      proxy: {
        // Authorization callback → local Python. Must come before /svc: vite matches prefixes in declaration order, first hit wins
        "/svc/whatsapp/embedded-signup": { target: "http://127.0.0.1:8000", changeOrigin: true },
        // Everything else → test environment
        "/svc": { target: "https://dev-gateway.example.com", changeOrigin: true },
        "/api": { target: "https://dev-gateway.example.com", changeOrigin: true }
      }
    },
    // Self-signed HTTPS in development mode only; production builds don't include this plugin
    plugins: mode === "development" ? [basicSsl()] : []
  };
});

The node with the darker border is the key component of this post: the proxy layer built into the vite dev server. The two streams of traffic split here, and this is also the layer where the problem later occurred.

Why a same-origin proxy rather than letting the browser talk to both backends directly? Hitting the local Python service directly means an HTTPS page calling an http:// endpoint, which lands in mixed content territory. Mainstream browsers do exempt loopback addresses, but their behavior differs. Hitting the test environment directly means depending on its CORS configuration. Put everything behind a same-origin proxy and, from the browser's point of view, every request is same-origin. Both problems go away at once.

On the day I finished the setup, the WhatsApp authorization flow worked end to end.

3. The Next Day: Login Returns 403

The next day I started the local server, tried to log in again, and the endpoint misbehaved:

  • Request URL: https://localhost:5173/api/auth/login
  • Status: 403 Forbidden, empty response body
  • The response headers included Access-Control-Allow-Origin: *

Three things were odd: the test and production environments were fine, no business code had changed, and everything had worked locally the day before. Had I opened a page that only issues GET requests, I would have noticed one more detail: the page loads perfectly, and only POST requests such as login return 403 (section 5 explains why).

There were three candidate causes: vite blocking the request locally, the test environment gateway blocking it, or the proxy configuration itself being wrong.

4. Investigation: Control the Variables Until the Trigger Is "One Value of One Header"

A request in the browser has too many variables, so I used curl to take the chain apart and test each piece on its own. Step one, call the test environment upstream directly with curl:

curl -sk -i --noproxy "*" -X POST "https://dev-gateway.example.com/api/auth/login" \
  -H "Content-Type: application/json" -d "{}"

It returned 200 plus a business error, "email must not be empty". The upstream service itself was healthy; the problem was not on the service side.

Side note: a proxy detour. My first curl request didn't include --noproxy, and the first line of output contained HTTP/1.1 200 Connection established. That is the reply from the proxy tool on my machine when it sets up a CONNECT tunnel, which means curl was actually going out through the system proxy. vite's forwarding, on the other hand, is a Node process connecting straight to the upstream, so the two take different network paths. To rule this variable out, I cross-checked both paths, "through the system proxy" and "forced direct": with the same combination of request headers, both paths produced identical results. That eliminated the network path as a variable, and the rest of this post shows only the direct-connection results.

The only real variable left was the request headers. I added the headers a browser sends to the curl command one at a time and quickly narrowed it down to Origin, then bisected on its value:

Origin header addedResult
No Origin200
Origin: http://localhost:5173200
Origin: https://localhost:5173403
Origin: https://app.example.com (the real domain)200
No Origin, only Referer: https://localhost:5173/200

Of the five cases, exactly one returned 403. The trigger had been narrowed down to one value of one header: Origin: https://localhost. The upstream is a reverse-proxy gateway, and either it or the WAF (web application firewall) in front of it has a rule that treats an "HTTPS + localhost" origin as the signature of a forged request and answers with a 403.

The response itself carries extra information. The semantics of 403 are "the server understood the request but refuses to fulfil it". It is not 405 (method not allowed) and not 500 (the server itself failed), which means the request arrived intact, was recognized, and was deliberately rejected by the server. An empty body is common WAF practice: reject without explaining, so that rule details aren't leaked to anyone probing. The combination "403 + empty body" is itself circumstantial evidence of a rule-based block.

5. Root Cause: I Didn't Upgrade the Protocol, I Changed the Origin

Three pieces of knowledge come together here.

1. An origin is a triple. In the same-origin policy, an origin is defined as scheme + host + port. http://localhost:5173 and https://localhost:5173 differ in scheme, so they are two different origins. The real meaning of that one basicSsl line is therefore not "add a certificate" but "move the entire local development environment to a new origin".

2. The Origin request header is attached by the browser, and frontend code cannot change it. The Origin header is added to a request by the browser, and its value is the origin of the initiating page (just the triple, no path). Per the Fetch spec, cross-origin requests in CORS mode always carry it, and so does any request whose method is not GET or HEAD, same-origin or not, as a signal for CSRF (cross-site request forgery) protection. It is a forbidden header: frontend code can neither forge nor remove it. That explains what I saw in section 3. Same-origin GET requests don't carry Origin, so display-only pages are unaffected. The login POST always carries Origin, so it always trips the rule. It is also worth distinguishing the similar-looking Referer: it carries the full URL (path included, trimmed according to Referrer-Policy) and is not the same thing as the Origin header.

3. vite's proxy passes Origin through when forwarding. After receiving the browser's request, the proxy opens a new request to the upstream and copies the request headers over as they are (except Host, see the next section), including that Origin header I cannot touch.

The causal chain is now complete:

What makes this chain hard is that every link, viewed on its own, is behaving exactly as expected. The plugin works correctly, the browser follows the spec, the proxy forwards faithfully, and the WAF blocks according to its rules. The final 403 only appears once all of them are stacked together. That is why this class of problem is hard to track down: no single link is "broken".

It also explains every qualifier on the failure. In the test and production environments the Origin is a real domain, which doesn't match the rule. The WhatsApp integration the day before went through the proxy rule for the local Python service and never touched this gateway. So the failure appeared only locally, only after HTTPS was enabled, and only for write requests sent to the test environment gateway.

6. One Level Deeper: How vite's Proxy Actually Works

What the dev server really is. The vite dev server started by npm run dev is a Node HTTP server that does three things: it compiles and serves source modules on demand (native ESM plus esbuild transforms), it pushes HMR (hot module replacement) updates over WebSocket, and it mounts a reverse proxy middleware. A reverse proxy accepts requests on behalf of the server and forwards them to the real backend, without the client being aware of it. A forward proxy, by contrast (such as that proxy tool on my machine), goes out on behalf of the client. You can think of the vite dev server as a mini nginx built into your frontend tooling.

The proxy is built on node-http-proxy. The vite docs state explicitly that server.proxy uses the http-proxy library under the hood. It doesn't shuttle bytes at the TCP layer. It does an application-layer replay: it uses Node's http/https modules to open a brand-new request to the target, copies over the original request's method, path, and headers, and writes the response back to the browser once it arrives. That act of "copying the request headers" is the mechanism by which Origin reaches the upstream.

Matching rules: declaration order + prefix. vite matches the request path against prefixes one rule at a time, in the order the keys are written in the config object, and the first match wins (keys starting with ^ are treated as regular expressions). This is exactly why /svc/whatsapp/embedded-signup has to be written before /svc. Reverse the order and the authorization callback matches the /svc rule first and gets forwarded to the test environment.

The name changeOrigin invites misunderstanding. It rewrites the Host header, not the Origin header. The two headers mean different things, and the difference deserves to be spelled out:

Origin header vs. Host header, once and for all
  • Origin header: generated by the browser. It represents the scheme + domain + port of the page that initiated the request and answers "where does the request come from". JavaScript cannot change it, and it is used for CORS and CSRF protection.
  • Host header: filled in by the client (or a proxy). It represents the target host this request is addressed to and answers "where is the request going". Virtual hosts and gateway routing rely on it to dispatch requests.
  • changeOrigin: true rewrites only Host (from localhost:5173 to the target's hostname; without that, many gateways that route by domain will simply return 404) and never touches Origin. The "origin" in the name is used in the plain sense of "where the request originates", and it happens to collide with the Origin of the same-origin policy. It is a historical naming leftover and shouldn't be read literally.

This was the easiest point to misjudge in the whole investigation: the config says changeOrigin: true, yet the Origin header arrives at the upstream unchanged.

The configure hook exposes the underlying instance. On every proxy rule, vite offers a configure(proxy, options) hook that hands you the http-proxy instance so you can listen to its lifecycle events. Among them, the proxyReq event fires just before the new request to the upstream is sent, and its callback receives an http.ClientRequest. This is the last chance to modify the outgoing request.

7. The Fix: Remove the Origin Header Before Forwarding

At this point the fix is clear. The minimal change is to remove the Origin header before forwarding.

import type { ProxyOptions } from "vite";

const stripOrigin: ProxyOptions["configure"] = proxy => {
  proxy.on("proxyReq", proxyReq => proxyReq.removeHeader("origin"));
};

// In server.proxy, attach the hook to the two rules that target the test environment:
"/svc": { target: "https://dev-gateway.example.com", changeOrigin: true, configure: stripOrigin },
"/api": { target: "https://dev-gateway.example.com", changeOrigin: true, configure: stripOrigin },

Six lines changed in total (lowercase in removeHeader("origin") is fine, since HTTP header names are case-insensitive). Restart the dev server, because changes to vite.config.ts are not hot-reloaded, and login returns 200 again.

The request's journey before and after the fix is easiest to understand side by side:

Before the fix (the failing path):

After the fix:

The only difference between the two diagrams is in the vite proxy box. On the failing path it faithfully copies every request header, Origin included. After the fix it runs removeHeader("origin") before forwarding. Not a single byte of the browser's request has changed. What changed is only the copy the proxy sends out.

Is it safe to remove the Origin header? This question needs clear boundaries, so here are three points:

  1. On the local dev path, nothing consumes this header in the first place. Behind a same-origin proxy, the browser sees the request as same-origin and makes no security decision based on Origin (the CORS check never happens). The upstream's business authentication is token-based and doesn't read it either. On this path, removing the Origin header weakens no protection that is actually in effect.
  2. The change does not affect the test or production environments. server.proxy is runtime behavior of the dev server, while vite build produces nothing but static files. I searched the build output for proxyReq and 127.0.0.1:8000 and found no matches. In production the browser talks to the backend directly, and cross-origin security is handled by the gateway's CORS configuration, which has nothing to do with this change.
  3. ⚠️ But don't treat this as a universal answer. The Fetch spec makes every non-GET/HEAD request carry Origin precisely to give servers a CSRF-defense signal, and some gateways and frameworks really do check write requests against an Origin allowlist. If your upstream relies on Origin for CSRF protection, removing it takes away a layer of defense. Confirm the upstream's authentication model before you remove it.

Why not adjust the rule on the gateway side instead? First, the gateway is outside what the frontend controls, and changing a rule there requires cross-team coordination. Second, "a dev proxy shouldn't send a localhost Origin to a public gateway" holds up on its own merits. Removing it at the proxy layer is arguably the more expected behavior.

8. The Big Picture: One Line of Code, Three Environments, Three Paths

The business code is a single line, axios.post("/api/auth/login"), yet it maps to completely different paths in different environments. The fork is an environment variable that is statically inlined at build time. vite replaces import.meta.env.VITE_* with string literals, and you can find plain text such as baseURL:"https://..." in the build output:

EnvironmentVITE_API_BASE_URLActual pathCross-origin approach
Local devemptyRelative path → same origin localhost:5173 → forwarded by vite proxySame-origin proxy (nothing is cross-origin)
Testhttps://dev-gateway.example.comBrowser connects directlyCORS response headers
Productionhttps://api.example.comBrowser connects directlyCORS response headers

Now look back at the Access-Control-Allow-Origin: * response header from section 3. It is the CORS configuration the gateway provides for the direct-connection scenario. On the proxied local path, the browser never consumes it at any point. Its presence on the 403 response only shows that the gateway attaches this header to everything. It has nothing to do with the logic that decided to block the request.

9. Retrospective

  1. Putting HTTPS on dev isn't adding a certificate, it's changing the origin. Every behavior keyed on origin changes with it: the Origin header, CORS, the Secure/SameSite cookie attributes, localStorage isolation. A change like this deserves to be treated as a "migration", not as a "config tweak".
  2. changeOrigin doesn't change Origin. It changes Host. When reading a config option, read its definition in the docs, not its name.
  3. Controlling variables is the backbone of debugging. Change one variable at a time (network path, request headers, header value) and four or five curl comparisons will narrow the trigger down to one value of one header. That is far more efficient than guessing item by item in the browser console.
  4. Headers passed through a proxy are an invisible contract. You think the proxy forwards "your request", but what it actually forwards is "the request the browser assembled". That request contains several headers the browser generates automatically and the frontend cannot modify, and the upstream may well be making decisions based on them.

Appendix: checklist after enabling HTTPS on local dev

  • Run every write endpoint (POST/PUT/DELETE) through the main flows such as login and form submission. They carry the Origin header whether same-origin or not, so focus on whether the proxy or the upstream gateway has any rule keyed on Origin
  • localStorage / sessionStorage / IndexedDB are isolated by origin: login state, drafts, and caches stored under the http origin are all unreadable under the https origin. This is expected behavior and doesn't need to be investigated as a bug
  • Re-check cookie behavior: cookies with the Secure attribute are only sent and received over HTTPS, and SameSite=None must be paired with Secure. Verify login state and session persistence once before and once after the scheme switch
  • Use a packet capture tool, or log from the proxyReq event, to verify that changeOrigin really rewrites Host to the target's hostname, and remember that it does not change Origin
  • If the self-signed certificate isn't trusted by the browser, the page may open while the HMR WebSocket (wss) connection fails. Trust the certificate in the browser first, or switch to mkcert to generate a locally trusted certificate