feat(build): fail build on misconfigured absolute VITE_API_URL

This commit is contained in:
Arthur Bassi 2026-06-17 09:35:34 -03:00
parent b0ce047154
commit 74b73620b3
3 changed files with 30 additions and 1 deletions

View file

@ -0,0 +1,21 @@
/** Absolute VITE_API_URL values must end with this segment (API_PATHS omit /api). */
export const ABSOLUTE_API_URL_SUFFIX = /\/api\/?$/;
/**
* Fails fast when an absolute VITE_API_URL omits the /api segment.
* Relative values (e.g. /api) are valid and skipped.
*/
export function assertAbsoluteApiUrlHasApiSegment(apiUrl: string | undefined): void {
const trimmed = apiUrl?.trim();
if (!trimmed?.startsWith("http")) {
return;
}
if (!ABSOLUTE_API_URL_SUFFIX.test(trimmed)) {
throw new Error(
`VITE_API_URL absolute URLs must end with /api (got: ${trimmed}). ` +
"API route paths do not include /api — set VITE_API_URL to the full API base, e.g. https://api.example.com/api. " +
"See README.md and .env.example.",
);
}
}

View file

@ -16,5 +16,10 @@
"outDir": "./node_modules/.tmp/tsconfig.node", "outDir": "./node_modules/.tmp/tsconfig.node",
"types": ["node"] "types": ["node"]
}, },
"include": ["vite.config.ts", "vitest.config.ts"] "include": [
"vite.config.ts",
"vitest.config.ts",
"config/api-url-contract.ts",
"config/api-url-contract.test.ts"
]
} }

View file

@ -2,10 +2,13 @@ import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite"; import tailwindcss from "@tailwindcss/vite";
import path from "node:path"; import path from "node:path";
import { defineConfig, loadEnv, transformWithEsbuild } from "vite"; import { defineConfig, loadEnv, transformWithEsbuild } from "vite";
import { assertAbsoluteApiUrlHasApiSegment } from "./config/api-url-contract";
export default defineConfig(({ mode }) => { export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), ""); const env = loadEnv(mode, process.cwd(), "");
assertAbsoluteApiUrlHasApiSegment(env.VITE_API_URL);
return { return {
plugins: [ plugins: [
{ {