Skip to content

Enable prerendering in TanStack Start Vite plugin - #8

Merged
daveycodez merged 18 commits into
mainfrom
web-cloudflare-prerender
Nov 21, 2025
Merged

daveycodez merged 18 commits into
mainfrom
web-cloudflare-prerender

Conversation

@daveycodez

@daveycodez daveycodez commented Nov 21, 2025 •

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

Release Notes

  • Build & Infrastructure
    • Enabled static prerendering for optimized deployment.
    • Added database connection fallback for improved initialization flexibility.
    • Updated TypeScript and build tool configurations for enhanced compatibility.

✏️ Tip: You can customize this high-level summary in your review settings.

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.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 21, 2025 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

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

@cloudflare-workers-and-pages

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
❌ Deployment failed
View logs
pgrealtime 1bbf546 Nov 21 2025, 01:38 AM

@coderabbitai

coderabbitai Bot commented Nov 21, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

💤 Files selected but had no reviewable changes (1)
  • apps/web/worker-configuration.d.ts

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

Configuration 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

Cohort / File(s) Summary
Build & Configuration Updates
apps/web/vite.config.ts, apps/web/tsconfig.json, apps/web/biome.json
vite.config.ts: Enable prerendering via tanstackStart plugin config. tsconfig.json: Add include array with "src/\\/\*" and "worker-configuration.d.ts". biome.json: Exclude worker-configuration.d.ts from file processing.
Database Runtime Changes
apps/web/src/database/db.ts
Remove DATABASE_URL presence guard; implement fallback to default PostgreSQL connection string if env var undefined. Public export signature unchanged.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

  • apps/web/src/database/db.ts: Verify the fallback PostgreSQL URL is intentional and safe; confirm this change aligns with intended deployment and development workflows. The removal of the runtime guard warrants attention to ensure no silent failures in production.

Poem

🐰 With prerender's glow and config's might,
The build hops forward, shining bright!
A fallback string for databases true,
TypeScript now knows just what to brew!
Configuration whispers, "Let's go!" ✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Enable prerendering in TanStack Start Vite plugin' directly describes the primary change in vite.config.ts, but the PR also includes unrelated configuration changes to db.ts, biome.json, and tsconfig.json that the title does not capture.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

Comment @coderabbitai help to get the list of available commands and usage tips.

@nx-cloud

nx-cloud Bot commented Nov 21, 2025 •

Copy link
Copy Markdown
Contributor

View your CI Pipeline Execution ↗ for commit 08e1b16

Command Status Duration Result
nx affected -t test build ✅ Succeeded 16s View ↗
nx-cloud record -- biome check ✅ Succeeded <1s View ↗

☁️ Nx Cloud last updated this comment at 2025-11-21 08:23:09 UTC

@coderabbitai coderabbitai Bot changed the title @coderabbitai Enable prerendering in TanStack Start Vite plugin Nov 21, 2025
nx-cloud[bot]

This comment was marked as outdated.

Replaces the runtime check for DATABASE_URL with a TypeScript type assertion, removing the error throw and simplifying the initialization of the database connection.
nx-cloud[bot]

This comment was marked as outdated.

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.
nx-cloud[bot]

This comment was marked as outdated.

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab23777 and 1630cd3.

📒 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 NeonHttpDatabase type is appropriate for the type annotation added below.

Comment thread apps/web/vite.config.ts Resolved
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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1630cd3 and 0f8553e.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is 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.ts from Biome scanning aligns with the existing pattern of excluding generated files like routeTree.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.ts exists 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.

nx-cloud[bot]

This comment was marked as outdated.

Provides a default PostgreSQL connection string if env.DATABASE_URL is undefined, preventing errors during database initialization.
@pgrealtime pgrealtime deleted a comment from coderabbitai Bot Nov 21, 2025
nx-cloud[bot]

This comment was marked as outdated.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
apps/web/src/database/db.ts (2)

1-1: Confirm cloudflare:workers synthetic import is valid for all db.ts consumers

Importing env from "cloudflare:workers" tightly couples this module to the Workers/Vite plugin. If apps/web/src/database/db.ts is ever imported from plain Node (e.g., migration scripts, Vitest, CLI tools), module resolution will fail. Please double‑check that db.ts is 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 when DATABASE_URL is 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 (missing DATABASE_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 when env.DATABASE_URL is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f8553e and 019f122.

📒 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
apps/web/wrangler.jsonc (1)

14-17: Wrangler vars usage looks correct; just ensure FOO-style values stay non-secret

The new top-level "vars": { "FOO": "BAR" } block is syntactically valid for wrangler.jsonc and correctly wired for use as env.FOO in the Worker. Just keep in mind that vars values live in plain-text config, so this pattern is fine for demo/config flags but should not be used for secrets (those should go through wrangler secret instead).

apps/web/src/routes/index.tsx (1)

27-31: Loader data consumption is correct; consider behavior when FOO is unset and long-term UI intent

Using Route.useLoaderData() and destructuring { foo } matches the new loader and will correctly hydrate from prerendered data; React will render an empty <p> if env.FOO is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 019f122 and b3e4773.

📒 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 required

Verification confirms the TanStack Start + Cloudflare Workers + Vite integration is correctly configured:

  • cloudflare({ viteEnvironment: { name: "ssr" } }) marks cloudflare:workers imports 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.FOO is safely accessed only within createServerFn().handler(), which runs on the server.
  • wrangler.jsonc correctly defines FOO: "BAR" and uses @tanstack/react-start/server-entry as the entry point.

The loader pattern is correct, and prerender will not choke on the cloudflare:workers import. 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.

@nx-cloud nx-cloud Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
   }
 })
 

Apply fix via Nx Cloud  Reject fix via Nx Cloud


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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7710d74 and d1a81b6.

📒 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/$.tsx is an API-only route with server handlers and no component, it will not be prerendered. The cloudflare:workers import in db.ts is 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.

@pgrealtime pgrealtime deleted a comment from coderabbitai Bot Nov 21, 2025
@pgrealtime pgrealtime deleted a comment from coderabbitai Bot Nov 21, 2025
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.
@daveycodez
daveycodez merged commit d77c9e3 into main Nov 21, 2025
@daveycodez
daveycodez deleted the web-cloudflare-prerender branch November 21, 2025 08:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant