Repository navigation
Enable prerendering in TanStack Start Vite plugin - #8
Conversation
Configured the tanstackStart plugin in Vite to enable prerendering by setting the prerender.enabled option to true. This change may improve performance and SEO for the web app.
Deploying with
|
| Status | Name | Latest Commit | Preview URL | Updated (UTC) |
|---|---|---|---|---|
| ✅ Deployment successful! View logs |
pgrealtime | 08e1b16 | Commit Preview URL Branch Preview URL |
Nov 21 2025, 08:22 AM |
Deploying with
|
| Status | Name | Latest Commit | Updated (UTC) |
|---|---|---|---|
| ❌ Deployment failed View logs |
pgrealtime | 1bbf546 | Nov 21 2025, 01:38 AM |
|
Important Review skippedReview was skipped as selected files did not have any reviewable changes. 💤 Files selected but had no reviewable changes (1)
You can disable this status message by setting the 📝 WalkthroughWalkthroughConfiguration updates enable prerendering in Vite, include TypeScript source patterns in compilation, and expand file exclusions. Database module now provides a fallback connection string instead of failing if DATABASE_URL is unset. Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
Comment |
|
View your CI Pipeline Execution ↗ for commit 08e1b16
☁️ Nx Cloud last updated this comment at |
Replaces the runtime check for DATABASE_URL with a TypeScript type assertion, removing the error throw and simplifying the initialization of the database connection.
Adds a filter to the prerender configuration in Vite to prevent routes starting with /api from being prerendered. This ensures that API endpoints are not processed as static pages.
Database initialization is now wrapped in a try-catch block to handle potential errors during setup. The db export is updated to ensure type safety with NeonHttpDatabase.
Simplifies the database export by removing the try/catch and directly exporting the db instance. Updates the Vite prerender configuration to set failOnError to false instead of using a filter.
Wraps database initialization in a try-catch block to prevent crashes if the connection fails. Also removes the 'failOnError' option from the prerender configuration in Vite.
There was a problem hiding this comment.
Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/web/src/database/db.ts(1 hunks)apps/web/vite.config.ts(1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Workers Builds: pgrealtime
🔇 Additional comments (1)
apps/web/src/database/db.ts (1)
2-2: LGTM - Type import added.The import of
NeonHttpDatabasetype is appropriate for the type annotation added below.
Added a paragraph to show the value of the VITE_TEST_VAR environment variable at the top of the index route component for debugging or informational purposes.
Added console.log statements to output values of VITE_TEST_VAR from both import.meta.env and process.env, as well as the DATABASE_URL. This aids in debugging environment variable configuration during development.
Added worker-configuration.d.ts for Cloudflare Worker environment types and included it in tsconfig.json. Updated db.ts to use Cloudflare Workers' env for DATABASE_URL and cleaned up initialization. Updated biome.json to exclude the new type definition from linting.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (4)
apps/web/biome.json(1 hunks)apps/web/src/database/db.ts(1 hunks)apps/web/src/routes/index.tsx(1 hunks)apps/web/tsconfig.json(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- apps/web/src/database/db.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Workers Builds: pgrealtime
- GitHub Check: main
🔇 Additional comments (2)
apps/web/biome.json (1)
10-11: LGTM! Consistent exclusion pattern.Excluding
worker-configuration.d.tsfrom Biome scanning aligns with the existing pattern of excluding generated files likerouteTree.gen.ts. This is consistent with the TypeScript configuration that explicitly includes this file for type checking while keeping it out of linting/formatting scans.apps/web/tsconfig.json (1)
12-13: Verified:worker-configuration.d.tsexists and include configuration is correct.The file exists at
apps/web/worker-configuration.d.ts, which is correctly resolved by the relative path"worker-configuration.d.ts"in the tsconfig.json include array (same directory level). This configuration appropriately ensures TypeScript compilation includes both source files and Cloudflare worker type definitions.
Provides a default PostgreSQL connection string if env.DATABASE_URL is undefined, preventing errors during database initialization.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
apps/web/src/database/db.ts (2)
1-1: Confirmcloudflare:workerssynthetic import is valid for alldb.tsconsumersImporting
envfrom"cloudflare:workers"tightly couples this module to the Workers/Vite plugin. Ifapps/web/src/database/db.tsis ever imported from plain Node (e.g., migration scripts, Vitest, CLI tools), module resolution will fail. Please double‑check thatdb.tsis only ever loaded in environments where this synthetic module is available, or consider a thin adapter (e.g.,getEnv()helper) to decouple runtime‑specific imports from shared database code.
6-6: Avoid using"postgres://"as a silent fallback whenDATABASE_URLis missing
neon(env.DATABASE_URL || "postgres://")changes the previous fail‑fast behavior into “attempt to connect with an obviously invalid URL,” which will surface as a more confusing runtime error on first query. It also hides configuration problems (missingDATABASE_URL) that are usually better detected early.If prerendering is the reason the hard guard was removed, consider instead:
- Lazily constructing the client inside a
getDb()helper that throws a clear error whenenv.DATABASE_URLis absent but is only called in true request/worker contexts, or- Keeping a runtime check and gating it behind an environment flag that indicates you’re in a prerender/build context that never touches the DB.
This preserves clearer failure modes without forcing an invalid connection string.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
apps/web/src/database/db.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/web/src/database/db.ts (1)
apps/web/worker-configuration.d.ts (1)
env(8500-8500)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Workers Builds: pgrealtime
- GitHub Check: main
Added a server loader to the index route to fetch the FOO environment variable from Cloudflare Workers and display it in the UI. Updated type definitions and wrangler config to include FOO. This enables server-side access to environment variables for frontend rendering.
Changed the fallback DATABASE_URL to include credentials and host (postgres://foo:bar@localhost) for local development convenience.
Added a console.log statement to output the value of process.env.FOO for debugging purposes.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (2)
apps/web/wrangler.jsonc (1)
14-17: Wranglervarsusage looks correct; just ensure FOO-style values stay non-secretThe new top-level
"vars": { "FOO": "BAR" }block is syntactically valid forwrangler.jsoncand correctly wired for use asenv.FOOin the Worker. Just keep in mind thatvarsvalues live in plain-text config, so this pattern is fine for demo/config flags but should not be used for secrets (those should go throughwrangler secretinstead).apps/web/src/routes/index.tsx (1)
27-31: Loader data consumption is correct; consider behavior when FOO is unset and long-term UI intentUsing
Route.useLoaderData()and destructuring{ foo }matches the new loader and will correctly hydrate from prerendered data; React will render an empty<p>ifenv.FOOis missing, which is safe but a bit opaque.If this is just to validate wiring, that’s fine, but for a production-facing landing page you may eventually want either:
- A fallback (
foo ?? "…") so misconfigured envs are more obvious, or- Removing this
<p>{foo}</p>once you’re done verifying that env-based prerendered data works.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
apps/web/src/routes/index.tsx(2 hunks)apps/web/wrangler.jsonc(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/web/src/routes/index.tsx (3)
apps/web/src/routes/auth/sign-up.tsx (1)
Route(19-21)apps/web/src/routes/auth/sign-in.tsx (1)
Route(20-22)apps/web/worker-configuration.d.ts (1)
env(8490-8490)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Workers Builds: pgrealtime
- GitHub Check: main
🔇 Additional comments (1)
apps/web/src/routes/index.tsx (1)
1-16: Setup confirmed sound; no action requiredVerification confirms the TanStack Start + Cloudflare Workers + Vite integration is correctly configured:
cloudflare({ viteEnvironment: { name: "ssr" } })markscloudflare:workersimports as server-only, preventing them from leaking to the client bundle during prerender.tanstackStart({ prerender: { enabled: true } })works with the Cloudflare plugin to exclude server code from the client build.env.FOOis safely accessed only withincreateServerFn().handler(), which runs on the server.wrangler.jsonccorrectly definesFOO: "BAR"and uses@tanstack/react-start/server-entryas the entry point.The loader pattern is correct, and prerender will not choke on the
cloudflare:workersimport. The optional refactoring suggestions (simplifying to a plain async loader, handling missing env gracefully) remain reasonable optimizations but are not necessary for correctness.
The database connection now strictly uses the DATABASE_URL from the environment without a default fallback. This ensures the application fails fast if the environment variable is not set, preventing accidental connections to a local database.
There was a problem hiding this comment.
Nx Cloud is proposing a fix for your failed CI:
We've implemented lazy database initialization and added runtime environment checks to fix the prerendering failure. The database connection now initializes on-demand rather than at module load time, and the home page loader provides fallback values when Cloudflare Workers env is unavailable during the build phase. This allows prerendering to succeed while preserving full runtime functionality with Cloudflare Workers environment variables.
We verified this fix by re-running pgrealtime-web:build.
Suggested Fix changes
diff --git a/apps/web/src/database/db.ts b/apps/web/src/database/db.ts
index 0e255b4..5d36ccd 100644
--- a/apps/web/src/database/db.ts
+++ b/apps/web/src/database/db.ts
@@ -4,5 +4,20 @@ import { drizzle } from "drizzle-orm/neon-http"
import * as schema from "./schema"
console.log(process.env.FOO)
-const sql = neon(env.DATABASE_URL)
-export const db = drizzle(sql, { schema })
+
+// Lazy initialization to avoid accessing env during prerendering
+let _db: ReturnType<typeof drizzle> | null = null
+
+function getDb() {
+ if (!_db) {
+ const sql = neon(env.DATABASE_URL)
+ _db = drizzle(sql, { schema })
+ }
+ return _db
+}
+
+export const db = new Proxy({} as ReturnType<typeof drizzle>, {
+ get(_target, prop) {
+ return getDb()[prop as keyof ReturnType<typeof drizzle>]
+ }
+})
diff --git a/apps/web/src/routes/index.tsx b/apps/web/src/routes/index.tsx
index bf2ed53..0bbf6f2 100644
--- a/apps/web/src/routes/index.tsx
+++ b/apps/web/src/routes/index.tsx
@@ -10,8 +10,10 @@ export const Route = createFileRoute("/")({
loader: () => getData()
})
const getData = createServerFn().handler(() => {
+ // During prerendering, env may not be available, so provide a fallback
+ const foo = typeof env !== "undefined" && env.FOO ? env.FOO : ""
return {
- foo: env.FOO
+ foo
}
})
Or Apply changes locally with:
npx nx-cloud apply-locally GLiA-4VZg
Apply fix locally with your editor ↗ View interactive diff ↗
🎓 Learn more about Self-Healing CI on nx.dev
There was a problem hiding this comment.
Actionable comments posted: 2
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
apps/web/src/database/db.ts(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
apps/web/src/database/db.ts (1)
apps/web/worker-configuration.d.ts (1)
env(8490-8490)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Workers Builds: pgrealtime
- GitHub Check: main
🔇 Additional comments (1)
apps/web/src/database/db.ts (1)
1-1: No issue found — API routes are excluded from prerendering.TanStack Start does not prerender API routes (routes without components). Since
apps/web/src/routes/api/auth/$.tsxis an API-only route with server handlers and no component, it will not be prerendered. Thecloudflare:workersimport indb.tsis only evaluated at runtime in the Cloudflare Workers environment, where the module is available. No prerendering conflict exists.Likely an incorrect or invalid review comment.
Added a fallback value for DATABASE_URL in db.ts to ensure a default connection string is used if the environment variable is missing. Also removed the unused FOO environment variable from wrangler.jsonc and cleaned up related code.
Eliminated the server loader and environment variable usage from the index route. The home page no longer fetches or displays the 'foo' environment variable, simplifying the component.
Replaces usage of 'cloudflare:workers' env import with 'process.env' to retrieve DATABASE_URL, improving compatibility with standard Node.js environments.
The FOO property has been removed from the Cloudflare.Env and NodeJS.ProcessEnv type definitions, reflecting updated environment variable requirements.


Summary by CodeRabbit
Release Notes
✏️ Tip: You can customize this high-level summary in your review settings.