Files
twenty/packages/twenty-front/vite.config.ts
T
Paul Rastoin 8bfa9c4adb Proxy API routes through the vite dev server to keep local dev same-origin (#23779)
Replaces #23774 (closed), rebased on latest main.

## Problem

Since the cookie-session migration (#23642), the front sends every
request with `credentials: 'include'` and the server only reflects
`Access-Control-Allow-Origin` for the exact origins in the credentialed
allowlist (`SERVER_URL`, `FRONTEND_URL`, `AUTH_COOKIE_ALLOWED_ORIGINS`).
Any other origin gets the `*` wildcard, which browsers reject for
credentialed requests.

Local dev is split-origin by default (front on `localhost:3001`, API on
`localhost:3000`), and with `IS_MULTIWORKSPACE_ENABLED` every workspace
subdomain (`apple.localhost:3001`, ...) is yet another origin. Each
locally created workspace would need a manual
`AUTH_COOKIE_ALLOWED_ORIGINS` entry.

## Solution

Make local dev same-origin instead of widening the CORS policy: the vite
dev server now proxies all top-level API route prefixes to the backend,
and the front calls its own origin.

- `vite.config.ts` adds a `server.proxy` covering the backend's
top-level prefixes (`/graphql`, `/metadata`, `/admin-panel`, `/auth`,
`/rest`, `/file`, `/client-config`, ...), defined in
`src/config/apiProxyPrefixes.ts`. Keys are anchored regexes
(`^/auth($|[/?])`) so SPA routes sharing a prefix (`/authorize`,
`/settings`) are not swallowed. The target defaults to
`http://localhost:3000` and follows `REACT_APP_SERVER_BASE_URL`.
`changeOrigin` stays off so the backend sees the browser's Host:
same-origin checks (CSRF, cookie issuance) and workspace resolution by
subdomain work unchanged through the proxy.
- `config/index.ts` collapses to
`window._env_?.REACT_APP_SERVER_BASE_URL || window.location.origin`.
Every supported production path injects `window._env_` (docker
entrypoint fails hard without `REACT_APP_SERVER_BASE_URL`; a
server-served front gets it from `generateFrontConfig()`), and in dev
the current origin is correct on `localhost:3001` and every
`*.localhost:3001` workspace subdomain thanks to the proxy. The removed
`http://<hostname>:3000` fallback only served an un-injected production
bundle browsed on localhost, a setup whose credentialed auth the
cookie-session migration had already broken.

The credentialed allowlist itself is unchanged and stays strict; since
dev traffic is same-origin, the per-subdomain cookie-allowlist problem
disappears without loosening any production CORS/CSRF policy.

## Tests

- `src/config/__tests__/apiProxyPrefixes.test.ts` guards the proxy
boundary in both directions: representative backend path shapes
(including `/metadata?query=...` and `/auth/...`) must match, every SPA
route from the `AppPath` enum and vite's own dev paths must not — so a
future route collision fails unit tests instead of breaking dev.
- Verified against running dev servers: API paths proxy to the backend
from both `localhost:3001` and `apple.localhost:3001`, while SPA routes
`/settings` and `/authorize` still serve the vite app; a same-origin
POST from `apple.localhost:3001` goes through with no CORS involvement.
- `lint:diff-with-main` and `typecheck` pass for twenty-front.

---------

Co-authored-by: Félix Malfait <felix@twenty.com>
2026-08-05 08:08:51 +00:00

294 lines
9.1 KiB
TypeScript

import { lingui } from '@lingui/vite-plugin';
import { isNonEmptyString } from '@sniptt/guards';
import react from '@vitejs/plugin-react-swc';
import wyw from '@wyw-in-js/vite';
import fs from 'fs';
import path from 'path';
import { visualizer } from 'rollup-plugin-visualizer';
import {
defineConfig,
loadEnv,
type PluginOption,
searchForWorkspaceRoot,
} from 'vite';
import svgr from 'vite-plugin-svgr';
import { createWywProfilingPlugin } from 'twenty-shared/vite';
import {
API_PROXY_PATHS,
buildApiProxyMatcher,
} from './src/config/apiProxyPrefixes';
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, __dirname, '');
const {
VITE_BUILD_SOURCEMAP,
VITE_HOST,
SSL_CERT_PATH,
SSL_KEY_PATH,
REACT_APP_PORT,
REACT_APP_SERVER_BASE_URL,
IS_DEBUG_MODE,
} = env;
const port = isNonEmptyString(REACT_APP_PORT)
? parseInt(REACT_APP_PORT)
: 3001;
const apiProxyTarget = isNonEmptyString(REACT_APP_SERVER_BASE_URL)
? REACT_APP_SERVER_BASE_URL
: 'http://localhost:3000';
const apiProxy = Object.fromEntries(
API_PROXY_PATHS.map((apiPath) => [
buildApiProxyMatcher(apiPath),
{ target: apiProxyTarget },
]),
);
const CHUNK_SIZE_WARNING_LIMIT = 1024 * 1024; // 1MB
// Please don't increase this limit for main index chunk
// If it gets too big then find modules in the code base
// that can be loaded lazily, there are more!
const MAIN_CHUNK_SIZE_LIMIT = 6.8 * 1024 * 1024; // 6.8MB for main index chunk
const OTHER_CHUNK_SIZE_LIMIT = 5 * 1024 * 1024; // 5MB for other chunks
if (VITE_BUILD_SOURCEMAP === 'true') {
// oxlint-disable-next-line no-console
console.log(`VITE_BUILD_SOURCEMAP: ${VITE_BUILD_SOURCEMAP}`);
}
return {
root: __dirname,
cacheDir: '../../node_modules/.vite/packages/twenty-front',
server: {
port: port,
proxy: apiProxy,
...(VITE_HOST ? { host: VITE_HOST } : {}),
...(SSL_KEY_PATH && SSL_CERT_PATH
? {
protocol: 'https',
https: {
key: fs.readFileSync(env.SSL_KEY_PATH),
cert: fs.readFileSync(env.SSL_CERT_PATH),
},
}
: {
protocol: 'http',
}),
fs: {
allow: [
searchForWorkspaceRoot(process.cwd()),
'**/@blocknote/core/src/fonts/**',
],
},
},
plugins: [
react({
plugins: [['@lingui/swc-plugin', {}]],
}),
svgr(),
lingui({
configPath: path.resolve(__dirname, './lingui.config.ts'),
}),
createWywProfilingPlugin(
wyw({
include: [path.resolve(__dirname, 'src') + '/**/*.{ts,tsx}'],
exclude: [
'**/generated-metadata/**',
'**/generated-admin/**',
'**/testing/mock-data/**',
'**/testing/jest/**',
'**/testing/hooks/**',
'**/testing/utils/**',
'**/testing/constants/**',
'**/testing/cache/**',
'**/*.test.{ts,tsx}',
'**/*.spec.{ts,tsx}',
'**/__tests__/**',
'**/__mocks__/**',
'**/types/**',
'**/constants/**',
'**/states/**',
'**/selectors/**',
'**/guards/**',
'**/schemas/**',
'**/utils/**',
'**/contexts/**',
'**/hooks/**',
'**/enums/**',
'**/queries/**',
'**/mutations/**',
'**/fragments/**',
'**/graphql/**',
'**/decorators/**',
],
babelOptions: {
presets: ['@babel/preset-typescript', '@babel/preset-react'],
plugins: ['@babel/plugin-transform-export-namespace-from'],
},
}),
),
...(env.ANALYZE === 'true'
? [
visualizer({
open: !process.env.CI,
gzipSize: true,
brotliSize: true,
filename: 'dist/stats.html',
}) as PluginOption,
]
: []),
],
optimizeDeps: {
exclude: [
'../../node_modules/.vite',
'../../node_modules/.cache',
'../../node_modules/twenty-ui',
],
// Pre-bundle React and the heavy libraries reached through lazy() chains
// (charts, rich-text editors). Otherwise a lazy story (e.g. a graph widget)
// makes Vite discover the dep mid-render, triggering a re-optimize + page
// reload that 404s every in-flight story import in browser-mode Storybook
// tests (vite 8 / rolldown).
include: [
'react',
'react-dom',
'react-dom/client',
'react/jsx-runtime',
'react/jsx-dev-runtime',
'@nivo/core',
'@nivo/pie',
'@nivo/line',
'@nivo/arcs',
'@react-spring/web',
'd3-shape',
],
},
build: {
minify: 'esbuild',
outDir: 'build',
sourcemap: VITE_BUILD_SOURCEMAP === 'true' ? 'hidden' : false,
chunkSizeWarningLimit: CHUNK_SIZE_WARNING_LIMIT,
rollupOptions: {
// Don't use manual chunks as it causes many issue
// including this one we wasted a lot of time on:
// https://github.com/rollup/rollup/issues/2793
output: {
// Custom plugin to fail build if chunks exceed max size
plugins: [
{
name: 'chunk-size-limit',
generateBundle(_options, bundle) {
const oversizedChunks: string[] = [];
Object.entries(bundle).forEach(([fileName, chunk]) => {
if (chunk.type === 'chunk' && chunk.code !== undefined) {
const size = Buffer.byteLength(chunk.code, 'utf8');
const isMainChunk =
fileName.includes('index') && chunk.isEntry;
const sizeLimit = isMainChunk
? MAIN_CHUNK_SIZE_LIMIT
: OTHER_CHUNK_SIZE_LIMIT;
const limitType = isMainChunk ? 'main' : 'other';
if (size > sizeLimit) {
oversizedChunks.push(
`${fileName} (${limitType}): ${(size / 1024 / 1024).toFixed(2)}MB (limit: ${(sizeLimit / 1024 / 1024).toFixed(2)}MB)`,
);
}
}
});
if (oversizedChunks.length > 0) {
const errorMessage = `Build failed: The following chunks exceed their size limits:\n${oversizedChunks.map((chunk) => ` - ${chunk}`).join('\n')}`;
this.error(errorMessage);
}
},
},
// TODO; later - think about prefetching modules such
// as date time picker, phone input etc...
/*
{
name: 'add-prefetched-modules',
transformIndexHtml(html: string,
ctx: {
path: string;
filename: string;
server?: ViteDevServer;
bundle?: import('rollup').OutputBundle;
chunk?: import('rollup').OutputChunk;
}) {
const bundles = Object.keys(ctx.bundle ?? {});
let modernBundles = bundles.filter(
(bundle) => bundle.endsWith('.map') === false
);
// Remove existing files and concatenate them into link tags
const prefechBundlesString = modernBundles
.filter((bundle) => html.includes(bundle) === false)
.map((bundle) => `<link rel="prefetch" href="${ctx.server?.config.base}${bundle}">`)
.join('');
// Use regular expression to get the content within <head> </head>
const headContent = html.match(/<head>([\s\S]*)<\/head>/)?.[1] ?? '';
// Insert the content of prefetch into the head
const newHeadContent = `${headContent}${prefechBundlesString}`;
// Replace the original head
html = html.replace(
/<head>([\s\S]*)<\/head>/,
`<head>${newHeadContent}</head>`
);
return html;
},
}*/
],
},
},
},
envPrefix: 'REACT_APP_',
define: {
'process.env': {
IS_DEBUG_MODE,
IS_DEV_ENV: mode === 'development' ? 'true' : 'false',
},
},
css: {
modules: {
localsConvention: 'camelCaseOnly',
},
},
resolve: {
tsconfigPaths: true,
alias: [
// wyw-in-js 1.x resolves modules in its CSS evaluator via vite's
// resolve.alias (not resolve.tsconfigPaths), so the `@/` and `~/`
// tsconfig path aliases must be mirrored here.
{
find: /^@\//,
replacement: path.resolve(__dirname, 'src/modules') + '/',
},
{ find: /^~\//, replacement: path.resolve(__dirname, 'src') + '/' },
{
find: 'path',
replacement: 'rollup-plugin-node-polyfills/polyfills/path',
},
],
},
};
});