Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions .changeset/dull-moons-share.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
"@react-router/dev": patch
---

Load environment variables before evaluating `routes.ts`

For example, you can now compute your routes based on [`VITE_`-prefixed environment variables](https://vite.dev/guide/env-and-mode#env-variables):

```txt
# .env
VITE_ENV_ROUTE=my-route
```

```ts
// app/routes.ts
import { type RouteConfig, route } from "@react-router/dev/routes";

const routes: RouteConfig = [];
if (import.meta.env.VITE_ENV_ROUTE === "my-route") {
routes.push(route("my-route", "routes/my-route.tsx"));
}

export default routes;
```
1 change: 1 addition & 0 deletions contributors.yml
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@
- remorses
- renyu-io
- reyronald
- RFCreate
- richardscarrott
- rifaidev
- rimian
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
"@types/react": "^18.2.20",
"@types/react-dom": "^18.2.7",
"typescript": "^5.1.6",
"vite": "^6.1.0",
"vite": "^6.3.0",
"wrangler": "^4.23.0"
},
"engines": {
Expand Down
2 changes: 1 addition & 1 deletion integration/helpers/rsc-vite-framework/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"@vitejs/plugin-rsc": "0.4.30",
"cross-env": "^7.0.3",
"typescript": "^5.1.6",
"vite": "^6.2.0",
"vite": "^6.3.0",
"vite-env-only": "^3.0.1",
"vite-tsconfig-paths": "^4.2.1"
},
Expand Down
2 changes: 1 addition & 1 deletion integration/helpers/rsc-vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"@types/react-dom": "^19.1.6",
"@vitejs/plugin-react": "^4.5.2",
"typescript": "^5.1.6",
"vite": "^6.2.0"
"vite": "^6.3.0"
},
"dependencies": {
"@mjackson/node-fetch-server": "0.6.1",
Expand Down
2 changes: 1 addition & 1 deletion integration/helpers/vite-6-template/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
"@types/react-dom": "^18.2.7",
"eslint": "^8.38.0",
"typescript": "^5.1.6",
"vite": "^6.1.0",
"vite": "^6.3.0",
"vite-env-only": "^3.0.1",
"vite-tsconfig-paths": "^4.2.1"
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"@types/react-dom": "^18.2.7",
"eslint": "^8.38.0",
"typescript": "^5.1.6",
"vite": "^6.1.0",
"vite": "^6.3.0",
"vite-tsconfig-paths": "^4.2.1",
"wrangler": "^4.23.0"
},
Expand Down
2 changes: 1 addition & 1 deletion integration/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"strip-indent": "^3.0.0",
"type-fest": "^4.0.0",
"typescript": "^5.1.0",
"vite": "^6.1.0",
"vite": "^6.3.0",
"vite-env-only": "^3.0.1",
"vite-tsconfig-paths": "^4.2.2",
"wait-on": "^7.0.1"
Expand Down
161 changes: 62 additions & 99 deletions integration/vite-dotenv-test.ts
Original file line number Diff line number Diff line change
@@ -1,37 +1,20 @@
import { test, expect } from "@playwright/test";
import { expect } from "@playwright/test";
import tsx from "dedent";
import getPort from "get-port";

import {
type TemplateName,
createProject,
customDev,
EXPRESS_SERVER,
viteConfig,
} from "./helpers/vite.js";

const templateNames = [
"vite-5-template",
"rsc-vite-framework",
] as const satisfies TemplateName[];

let getFiles = async ({
templateName,
envDir,
port,
}: {
templateName: TemplateName;
envDir?: string;
port: number;
}) => {
let envPath = `${envDir ? `${envDir}/` : ""}.env`;

return {
"vite.config.js": await viteConfig.basic({ templateName, port, envDir }),
"server.mjs": EXPRESS_SERVER({ port, templateName }),
[envPath]: `
ENV_VAR_FROM_DOTENV_FILE=Content from ${envPath} file
`,
"app/routes/dotenv.tsx": String.raw`
import * as Express from "./helpers/express";
import { test } from "./helpers/fixtures";
import * as Stream from "./helpers/stream";
import { viteMajorTemplates, getTemplates } from "./helpers/templates";

const templates = [
...viteMajorTemplates,
...getTemplates(["rsc-vite-framework"]),
];

test.use({
files: {
"app/routes/dotenv.tsx": tsx`
import { useState, useEffect } from "react";
import { useLoaderData } from "react-router";
Expand Down Expand Up @@ -59,82 +42,62 @@ let getFiles = async ({
</>
}
`,
};
};

test.describe("Vite .env", () => {
for (const templateName of templateNames) {
test.describe(`template: ${templateName}`, () => {
test.describe("defaults", async () => {
let port: number;
let cwd: string;
let stop: () => void;

test.beforeAll(async () => {
port = await getPort();
cwd = await createProject(
await getFiles({ port, templateName }),
templateName,
);
stop = await customDev({ cwd, port });
});
test.afterAll(() => stop());
},
});

test("express", async ({ page }) => {
let pageErrors: unknown[] = [];
page.on("pageerror", (error) => pageErrors.push(error));
const envs = [
{ name: "default", path: ".env" },
{ name: "custom env dir", path: "custom-env-dir/.env" },
];

await page.goto(`http://localhost:${port}/dotenv`, {
waitUntil: "networkidle",
test.describe("Vite .env", () => {
templates.forEach((template) => {
test.describe(`template: ${template.displayName}`, () => {
const isRsc = template.name.startsWith("rsc-");
test.use({ template: template.name });
envs.forEach((env) => {
test(env.name, async ({ edit, $, page }) => {
await edit({
"server.mjs": isRsc ? Express.rsc() : Express.server(),
".env": `
VITE_ENV_ROUTE=dotenv
ENV_VAR_FROM_DOTENV_FILE=Content from ${env.path} file
`,
"app/routes.ts": (contents) => {
if (template.name === "vite-5-template") return contents;
return tsx`
import { type RouteConfig, route } from "@react-router/dev/routes";
const routes: RouteConfig = [];
if (import.meta.env.VITE_ENV_ROUTE === "dotenv") {
routes.push(route("dotenv", "routes/dotenv.tsx"));
}
export default routes
`;
},
});
expect(pageErrors).toEqual([]);
await $("pnpm build");

let loaderContent = page.locator(
"[data-dotenv-route-loader-content]",
);
await expect(loaderContent).toHaveText("Content from .env file");
const port = await getPort();
const url = `http://localhost:${port}`;

let clientContent = page.locator(
"[data-dotenv-route-client-content]",
);
await expect(clientContent).toHaveText(
"process.env.ENV_VAR_FROM_DOTENV_FILE not available on the client, which is a good thing",
);

expect(pageErrors).toEqual([]);
});
});

test.describe("custom env dir", async () => {
let port: number;
let cwd: string;
let stop: () => void;

test.beforeAll(async () => {
const envDir = "custom-env-dir";
port = await getPort();
cwd = await createProject(
await getFiles({ envDir, port, templateName }),
templateName,
);
stop = await customDev({ cwd, port });
});
test.afterAll(() => stop());

test("express", async ({ page }) => {
let pageErrors: unknown[] = [];
page.on("pageerror", (error) => pageErrors.push(error));

await page.goto(`http://localhost:${port}/dotenv`, {
waitUntil: "networkidle",
const server = $("node server.mjs", {
env: {
PORT: String(port),
HMR_PORT: String(await getPort()),
},
});
expect(pageErrors).toEqual([]);
await Stream.match(server.stdout, url);

await page.goto(`${url}/dotenv`, { waitUntil: "networkidle" });
expect(page.errors).toEqual([]);

let loaderContent = page.locator(
"[data-dotenv-route-loader-content]",
);
await expect(loaderContent).toHaveText(
"Content from custom-env-dir/.env file",
`Content from ${env.path} file`,
);

let clientContent = page.locator(
Expand All @@ -144,9 +107,9 @@ test.describe("Vite .env", () => {
"process.env.ENV_VAR_FROM_DOTENV_FILE not available on the client, which is a good thing",
);

expect(pageErrors).toEqual([]);
expect(page.errors).toEqual([]);
});
});
});
}
});
});
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@
"typescript": "^5.4.5",
"unified": "^10.1.2",
"unist-util-remove": "^3.1.0",
"vite": "^6.1.0"
"vite": "^6.3.0"
},
"engines": {
"node": ">=20.0.0"
Expand Down
2 changes: 1 addition & 1 deletion packages/react-router-dev/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@
"react-router": "workspace:^",
"tsup": "^8.3.0",
"typescript": "^5.1.6",
"vite": "^6.1.0",
"vite": "^6.3.0",
"wireit": "0.14.9",
"wrangler": "^4.23.0"
},
Expand Down
12 changes: 6 additions & 6 deletions packages/react-router-dev/vite/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1279,20 +1279,20 @@ export const reactRouterVitePlugin: ReactRouterVitePlugin = () => {
});
}

reactRouterConfigLoader = await createConfigLoader({
await loadDotenv({
rootDirectory,
viteUserConfig,
mode,
watch: viteCommand === "serve",
});

await updatePluginContext();

await loadDotenv({
reactRouterConfigLoader = await createConfigLoader({
rootDirectory,
viteUserConfig,
mode,
watch: viteCommand === "serve",
});

await updatePluginContext();

let environments = await getEnvironmentsOptions(ctx, viteCommand, {
viteUserConfig,
});
Expand Down
12 changes: 6 additions & 6 deletions packages/react-router-dev/vite/rsc/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ export function reactRouterRSCVitePlugin(): Vite.PluginOption[] {
const rootDirectory = getRootDirectory(viteUserConfig);
const watch = command === "serve";

await loadDotenv({
rootDirectory,
viteUserConfig,
mode,
});

configLoader = await createConfigLoader({
rootDirectory,
mode,
Expand Down Expand Up @@ -104,12 +110,6 @@ export function reactRouterRSCVitePlugin(): Vite.PluginOption[] {
);
}

await loadDotenv({
rootDirectory,
viteUserConfig,
mode,
});

const vite = await import("vite");
logger = vite.createLogger(viteUserConfig.logLevel, {
prefix: "[react-router]",
Expand Down
2 changes: 1 addition & 1 deletion playground/framework-express/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"@types/react-dom": "^18.2.7",
"cross-env": "^7.0.3",
"typescript": "^5.1.6",
"vite": "^6.1.0",
"vite": "^6.3.0",
"vite-tsconfig-paths": "^4.2.1"
},
"engines": {
Expand Down
2 changes: 1 addition & 1 deletion playground/framework-spa/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"@types/react": "^18.2.20",
"@types/react-dom": "^18.2.7",
"typescript": "^5.1.6",
"vite": "^6.1.0",
"vite": "^6.3.0",
"vite-tsconfig-paths": "^4.2.1"
},
"engines": {
Expand Down
2 changes: 1 addition & 1 deletion playground/framework/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"@types/react": "^18.2.20",
"@types/react-dom": "^18.2.7",
"typescript": "^5.1.6",
"vite": "^6.1.0",
"vite": "^6.3.0",
"vite-tsconfig-paths": "^4.2.1"
},
"engines": {
Expand Down
2 changes: 1 addition & 1 deletion playground/middleware/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"@types/react-dom": "^18.2.7",
"tsx": "^4.19.3",
"typescript": "^5.1.6",
"vite": "^6.0.0",
"vite": "^6.3.0",
"vite-tsconfig-paths": "^4.2.1"
},
"engines": {
Expand Down
2 changes: 1 addition & 1 deletion playground/rsc-vite-framework/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
"remark-frontmatter": "^5.0.0",
"remark-mdx-frontmatter": "^5.2.0",
"typescript": "^5.1.6",
"vite": "^6.2.0"
"vite": "^6.3.0"
},
"dependencies": {
"@mjackson/node-fetch-server": "0.6.1",
Expand Down
Loading