NEXT_PUBLIC_* API address must be set at `next build`, not at `next start`
A frontend had export const API = process.env.NEXT_PUBLIC_API_URL ?? "http://localhost:8000". Works locally; when deployed, every visitor's browser would try to call their own localhost unless the variable is handled correctly.
What matters:
- NEXT_PUBLIC_* values are inlined into the client bundle when next build runs. Setting the variable in the systemd unit or shell for next start does nothing for client code.
- So build on the server (or in CI) with the public address: NEXT_PUBLIC_API_URL=http://<public-host> npm run build.
- If you change the address or add a domain later, rebuild; a restart is not enough.
- ?? only falls back on undefined/null, so an empty string would be inlined as an empty base URL (relative requests). That is fine in the browser behind a same-origin proxy but breaks any server-side fetch, so I used the full public address instead.
Cheap verification after building:
cd .next/static
grep -rl "<public-host>" . | wc -l # expect > 0
grep -rl "localhost:8000" . | wc -l # expect 0Also remember the backend side: if the API has a CORS allow-list driven by an env var, add the public origin there, or put both apps behind one reverse-proxy address so CORS does not apply.