wealth/docs/decisions/0018-browser-calls-the-api-...

2.0 KiB

0018 The browser calls the API through a Next.js rewrite

Status: Superseded by 0065 · Area: architecture · Date: 2026-10-06 · Decided by: user

Context

The browser called the gateway on its own origin with credentials, so every call was cross-origin: CORS preflights, a CORS allowlist to keep in step, and session cookies that belonged to the API host.

Decision

  • The browser calls the API on the app's own origin (bull :7000, bear :7001) under /api (API_PROXY_PATH): /api/v1/… and /api/files/…. Each app's next.config.ts rewrites /api/:path* to ${apiInternalUrl()}/:path*, the gateway's API_INTERNAL_ORIGIN.
  • Media and avatar URLs from the API go through the same path (toApiUrl, market env apiBaseUrl), so private media gets the session cookie.
  • The server render still calls the gateway directly at API_INTERNAL_ORIGIN and still sends no session cookies.
  • The gateway scopes the refresh cookie to /api/v1/auth (AUTH_COOKIE_PATH_PREFIX=/api), and keeps the apps' origins in CORS_ORIGINS for its origin check.

Alternatives

  • Direct cross-origin calls with CORS: the previous setup, replaced.
  • A route handler proxy reading the origin at run time: not chosen; the rewrite is simpler.

Consequences

  • No NEXT_PUBLIC_API_ORIGIN. next build fixes the rewrite's destination at build time, so each environment's build needs its own API_INTERNAL_ORIGIN; SKIP_ENV_VALIDATION can't skip it, and a build without it fails.
  • API traffic, uploads included, passes through the Next.js server. Its proxy waits API_PROXY_TIMEOUT_MS (120 s, experimental.proxyTimeout) instead of Next.js's 30 s.
  • The proxy adds only X-Forwarded-Host and passes the browser's X-Forwarded-For on as sent; Next.js can't see the client's address. The client IP must come from the edge in front of the apps (it sets X-Forwarded-For), with the gateway trusting that chain (back end: 02-architecture, 08-devops). Without such an edge, the forwarded IP is the client's own claim.