89ad87aa64
## Introduction
In aim to reduce and optimize the number of twenty-front build we do
during our cd process and allow twenty-front build promotion
### Build time
**Nothing is baked.** The `build/` directory is a clean, env-agnostic
artifact. `index.html` contains the empty placeholder:
```html
<script id="twenty-env-config">
window._env_ = {
// This will be overwritten
};
</script>
```
The JS bundles contain no hardcoded server URL.
---
### Deploy mode 1: Frontend served by the backend (Docker / NestJS)
1. Container starts, NestJS boots in `main.ts`
2. `generateFrontConfig()` runs, reads `process.env.SERVER_URL`
3. Rewrites `dist/front/index.html`, replacing the placeholder with:
```html
<script id="twenty-env-config">
window._env_ = {
REACT_APP_SERVER_BASE_URL: "https://api.example.com"
};
</script>
```
4. NestJS serves the static `dist/front/` directory
5. Browser loads `index.html`, `window._env_` is set before the app JS
executes
6. `src/config/index.ts` reads `window._env_.REACT_APP_SERVER_BASE_URL`
and uses it
---
### Deploy mode 2: Frontend served standalone (CDN / nginx / static
server)
1. Take the `build/` artifact as-is
2. Before serving, run at deploy time:
```bash
REACT_APP_SERVER_BASE_URL=https://api.example.com sh
./scripts/inject-runtime-env.sh
```
3. This does the same `sed` replacement on `build/index.html`
4. Serve the `build/` directory with your static server of choice
5. Same resolution in the browser:
`window._env_.REACT_APP_SERVER_BASE_URL` is picked up by
`src/config/index.ts`
---
### Fallback: no injection at all
If neither mechanism runs (e.g. local dev with `vite dev`),
`window._env_.REACT_APP_SERVER_BASE_URL` is `undefined`, and
`getDefaultUrl()` kicks in:
- **Localhost**: returns `http://localhost:3000`
- **Non-localhost**: returns same-origin (`window.location.origin`)
22 lines
842 B
TypeScript
22 lines
842 B
TypeScript
const getDefaultUrl = () => {
|
|
if (
|
|
window.location.hostname.endsWith('localhost') ||
|
|
window.location.hostname.endsWith('127.0.0.1')
|
|
) {
|
|
// In development environment front and backend usually run on separate ports
|
|
// we set the default value to localhost:3000.
|
|
// In dev context, we use env vars to overwrite it
|
|
return `http://${window.location.hostname}:3000`;
|
|
} else {
|
|
// Outside of localhost we assume that they run on the same port
|
|
// because the backend will serve the frontend
|
|
// In prod context, we use index.html + window var to ovewrite it
|
|
return `${window.location.protocol}//${window.location.hostname}${
|
|
window.location.port ? `:${window.location.port}` : ''
|
|
}`;
|
|
}
|
|
};
|
|
|
|
export const REACT_APP_SERVER_BASE_URL =
|
|
window._env_?.REACT_APP_SERVER_BASE_URL || getDefaultUrl();
|