Skip to content

feat: add clerk auth support with convex - #548

Merged
AmanVarshney01 merged 12 commits into
mainfrom
add-clerk-convex
Aug 28, 2025
Merged

AmanVarshney01 merged 12 commits into
mainfrom
add-clerk-convex

Conversation

@AmanVarshney01

@AmanVarshney01 AmanVarshney01 commented Aug 27, 2025 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

Release Notes

  • New Features

    • Added a selectable authentication provider option across the CLI, prompts, and templates. Users can now choose between Better-Auth, Clerk, or No Authentication.
    • Introduced full Clerk + Convex integration for web and native applications, including providers, middleware, dashboard, sign-in/sign-up/sign-out, and environment variables.
  • Changes

    • The CLI now uses the --auth <provider> flag, where <provider> can be better-auth, clerk, or none. The README, UI display, validation, and stack configuration reflect these new provider choices.
    • Clerk authentication is only available when using the Convex backend. Authentication requires a database, except when using the Convex backend with the "none" authentication option.
  • Refactor

    • The Home, Analytics, and Showcase pages have been updated to use server-side data fetching and preloaded data, with components accepting props instead of managing their own state.
  • Chores / Tests

    • Added new dependencies, including expo-crypto and type definitions.
    • Expanded test coverage to include more scenarios involving Clerk authentication.

@coderabbitai

coderabbitai Bot commented Aug 27, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Auth changed from a boolean flag to an enum-like type ("better-auth" | "clerk" | "none") across CLI types, prompts, validation, templates, scaffolding and docs; Clerk support for Convex (web + native) was added with provider-specific templates, deps, env vars, and provider wiring; many web pages moved to server/preload data patterns.

Changes

Cohort / File(s) Summary
Core types & constants
apps/cli/src/types.ts, apps/cli/src/constants.ts, apps/cli/src/index.ts
Add AuthSchema / Auth type; change CreateInput/project config auth to Auth; DEFAULT_CONFIG_BASE.auth updated to "better-auth"; add Clerk-related dependencyVersionMap entries.
CLI prompts & UX
apps/cli/src/prompts/*, apps/cli/src/prompts/config-prompts.ts, apps/cli/src/prompts/auth.ts, apps/cli/src/utils/display-config.ts, apps/cli/src/utils/generate-reproducible-command.ts
Replace confirm with select prompts; propagate Auth through prompts; display auth as string; reproducible command emits --auth <value>.
Scaffolding / create-project wiring
apps/cli/src/helpers/core/create-project.ts, template-manager.ts, auth-setup.ts, env-setup.ts, add-addons.ts, add-deployment.ts, post-installation.ts, command-handlers.ts
Rewire auth gating to use enum values; always invoke auth template setup; provider-scoped template copying; install provider-specific deps; add Clerk env vars; defaults changed from false→"none".
Templates — tighten better-auth gating
apps/cli/templates/**/server/**, apps/cli/templates/**/web/**, apps/cli/templates/**/api/**, apps/cli/templates/backend/server/**
Replace truthy {{#if auth}} with {{#if (eq auth "better-auth")}} in many templates; add explicit no-auth branches; emit protected routes/middleware only for "better-auth".
Templates — Clerk + Convex additions
apps/cli/templates/auth/clerk/convex/**, apps/cli/templates/frontend/**/tanstack-start, .../tanstack-router, .../react/**, .../native/**
New Clerk-specific templates: middleware, dashboard routes/pages, Convex privateData handlers, auth.config, TanStack Start server handler, native sign-in/up/out, provider wiring and route hooks.
Frontend provider wiring
apps/cli/templates/frontend/react/next/**, .../react/tanstack-start/**, .../react/tanstack-router/**, apps/cli/templates/frontend/native/*/_layout.tsx.hbs, .../(drawer)/index.tsx.hbs
Add conditional ClerkProvider + ConvexProviderWithClerk wiring for convex+clerk while preserving non-Clerk paths.
Compatibility & validation
apps/cli/src/utils/compatibility-rules.ts, apps/cli/src/utils/config-validation.ts, apps/cli/src/utils/config-processing.ts
Update coercion and emission of auth flags; enforce Clerk-only-with-Convex and Better-Auth incompatible-with-Convex rules; frontend compatibility now considers auth.
README & generated files
apps/cli/src/helpers/core/create-readme.ts, apps/cli/templates/addons/ruler/.ruler/bts.md.hbs
README helpers accept Auth and render auth-related lines only when appropriate; ruler template shows Authentication only for "better-auth".
Template package changes
apps/cli/templates/frontend/native/*/package.json.hbs, apps/cli/templates/backend/convex/packages/backend/package.json.hbs
Add expo-crypto to native templates; add @types/node devDependency to convex backend package.json template.
Web app: config, UI, data flow
apps/web/src/lib/constant.ts, apps/web/src/lib/stack-url-state.ts, apps/web/src/app/(home)/**, apps/web/src/app/(home)/_components/stack-builder.tsx, apps/web/src/app/(home)/layout.tsx
Move auth options to explicit ids (better-auth/clerk/none), update defaults/parsing; convert many pages/components to server/preloaded data model and adjust component props; stack-builder and command gen use explicit auth values.
Tests & programmatic API
apps/cli/test/cli.smoke.test.ts, apps/cli/test/programmatic-api.test.ts
Tests and programmatic API updated to string auth values; added convex+clerk test coverage; programmatic init expects "better-auth".
Docs & scripts
apps/web/content/docs/**, apps/web/scripts/generate-analytics.ts
Documentation updated for provider-based --auth usage and compatibility notes; external analytics/CSV host changed to r2.better-t-stack.dev.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant CLI
  participant Prompts
  participant Rules as CompatRules
  participant Templates
  participant AuthSetup
  participant Env as EnvSetup
  participant FS

  User->>CLI: run init (flags / interactive)
  CLI->>Prompts: getAuthChoice(flags.auth, hasDB, backend, frontend)
  Prompts-->>CLI: returns Auth ("better-auth"|"clerk"|"none")
  CLI->>Rules: coerceBackendPresets(config)
  Rules-->>CLI: normalized config (auth coerced)
  CLI->>Templates: setupAuthTemplate(context with auth)
  alt backend=convex and auth=clerk
    Templates->>FS: copy Clerk+Convex templates (backend, web, native)
  else auth="better-auth"
    Templates->>FS: copy better-auth templates (server/web/native)
  else auth="none"
    Templates-->>CLI: skip auth templates
  end
  CLI->>AuthSetup: setupAuth(context)
  AuthSetup->>FS: add provider deps to appropriate dirs
  CLI->>Env: setupEnvironmentVariables(context)
  Env->>FS: add provider env vars (.env) if needed
  CLI-->>User: scaffold complete (post-install notes)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

Poem

I hopped through flags from true to name,
Now clerk or better-auth stake their claim.
Templates scurry, providers nest,
Env keys lined up, dependencies dressed.
Thump-thump — scaffolds sprout, a tidy game. 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch add-clerk-convex

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbit in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbit in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbit gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbit read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbit help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbit ignore or @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbit summary or @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbit or @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@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: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (6)
apps/cli/src/constants.ts (1)

42-146: Add Clerk dependency to dependencyVersionMap

The newly added Clerk templates import from @clerk/nextjs (both client and server-side modules), but apps/cli/src/constants.ts does not yet pin this package. Without it, running the CLI installer on a Clerk-enabled project will fail.

• In apps/cli/src/constants.ts, within dependencyVersionMap, add an entry for "@clerk/nextjs".
– Use the latest stable version (≥ 6.15.0); for example:
"@clerk/nextjs": "^6.17.0" (npmjs.com, clerk.com)

Example diff:

 export const dependencyVersionMap = {
     // … existing entries …
     dotenv: "^17.2.1",
+    "@clerk/nextjs": "^6.17.0",
 } as const;

• Verify that the pinned version supports both imports used in your templates:
– import { clerkMiddleware } from "@clerk/nextjs/server" (middleware.ts.hbs)
– import { SignInButton, UserButton } from "@clerk/nextjs" (dashboard/page.tsx.hbs)
– import { useAuth } from "@clerk/nextjs" (providers.tsx.hbs)

These changes will ensure that template-generated projects have all required Clerk packages installed.

apps/cli/src/utils/compatibility-rules.ts (1)

136-145: Don’t override auth: "clerk" for Convex.

This forces auth to "none" for Convex, which conflicts with the PR goal (Clerk + Convex). Allow Clerk while still coercing defaults.

 export function coerceBackendPresets(config: Partial<ProjectConfig>) {
   if (config.backend === "convex") {
-    config.auth = "none" as ProjectConfig["auth"];
+    // Allow Clerk with Convex; otherwise default to "none"
+    if (config.auth !== "clerk") {
+      config.auth = "none" as ProjectConfig["auth"];
+    }
     config.database = "none";
     config.orm = "none";
     config.api = "none";
     config.runtime = "none";
     config.dbSetup = "none";
     config.examples = ["todo"] as ProjectConfig["examples"];
   }
apps/web/src/app/(home)/_components/stack-builder.tsx (1)

203-213: Don’t force auth to "none" for Convex; allow Clerk with Convex.

The PR title promises “add clerk auth support with convex”, but this override sets auth: "none", preventing Clerk. Remove this override and coerce only unsupported providers (e.g., “better-auth”) to a supported one or to “none”.

Apply this diff:

   if (isConvex) {
     const convexOverrides: Partial<StackState> = {
       runtime: "none",
       database: "none",
       orm: "none",
       api: "none",
-      auth: "none",
       dbSetup: "none",
       examples: ["todo"],
     };
+    // Auth with Convex: Better-Auth unsupported. Prefer Clerk; otherwise 'none'.
+    if (nextStack.auth === "better-auth") {
+      notes.auth.notes.push("Convex does not support Better-Auth. Switching to 'Clerk'.");
+      notes.auth.hasIssue = true;
+      nextStack.auth = "clerk";
+      changed = true;
+      changes.push({ category: "convex", message: "Auth set to 'Clerk' (Convex supports Clerk)" });
+    } else if (nextStack.auth !== "clerk" && nextStack.auth !== "none") {
+      notes.auth.notes.push("Convex supports 'Clerk' only. Auth set to 'None'.");
+      notes.auth.hasIssue = true;
+      nextStack.auth = "none";
+      changed = true;
+      changes.push({ category: "convex", message: "Authentication set to 'None' (unsupported provider)" });
+    }
apps/cli/src/helpers/core/create-project.ts (1)

46-50: Ensure auth templates are copied for Convex+Clerk.

Auth templates are skipped for Convex entirely; Clerk with Convex needs them.

Apply this diff:

-    if (!isConvex) {
+    if (!isConvex) {
       await setupDbOrmTemplates(projectDir, options);
       await setupDockerComposeTemplates(projectDir, options);
-      await setupAuthTemplate(projectDir, options);
     }
+    // Allow Clerk auth templates on Convex
+    if (!isConvex || options.auth === "clerk") {
+      await setupAuthTemplate(projectDir, options);
+    }
apps/cli/src/helpers/addons/auth-setup.ts (1)

77-86: Use cryptographically secure randomness for auth secrets.

Math.random() is not suitable for secrets. Switch to Node crypto for CSPRNG.

Apply:

+import crypto from "node:crypto";
@@
-export function generateAuthSecret(length = 32): string {
-  const characters =
-    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
-  let result = "";
-  const charactersLength = characters.length;
-  for (let i = 0; i < length; i++) {
-    result += characters.charAt(Math.floor(Math.random() * charactersLength));
-  }
-  return result;
-}
+export function generateAuthSecret(length = 32): string {
+  // Use URL-safe base64 and trim to length
+  const bytes = crypto.randomBytes(Math.ceil((length * 3) / 4));
+  const base = bytes.toString("base64url"); // Node 20+
+  return base.slice(0, length);
+}
apps/cli/src/prompts/config-prompts.ts (1)

59-121: Update docs to remove hardcoded boolean auth

  • Verified that in apps/cli/src there are no remaining auth: boolean or z.boolean() schemas, no auth === true/false comparisons, no negated !auth checks, and no direct flags.auth boolean usages.
  • However, in apps/web/content/docs/bts-config.mdx (lines 38–42) there is still a hardcoded example:
    {
      "orm": "drizzle",
      "api": "trpc",
      "auth": true,
      "addons": ["turborepo"],
      "examples": []
    }
    This should be updated to reflect the new auth schema (e.g. an object with provider details) instead of a boolean.

Please replace that example with the new auth configuration format to keep our documentation in sync with the CLI changes.

🧹 Nitpick comments (11)
apps/web/src/lib/stack-url-state.ts (2)

9-11: Return a readonly array to better align with parseAsStringEnum’s expectations.

Minor typing improvement; avoids accidental mutation.

-const getValidIds = (category: keyof typeof TECH_OPTIONS): string[] => {
+const getValidIds = (category: keyof typeof TECH_OPTIONS): readonly string[] => {
   return TECH_OPTIONS[category]?.map((opt) => opt.id) ?? [];
};

39-41: Optional: Precompute and validate AUTH IDs in stack-url-state.ts

Currently, TECH_OPTIONS.auth contains ["better-auth", "clerk", "none"] and DEFAULT_STACK.auth is "better-auth", so the inline call

parseAsStringEnum<StackState["auth"]>(getValidIds("auth")).withDefault(DEFAULT_STACK.auth)

will always succeed. If you’d like to guard against future changes or avoid repeating getValidIds, you can optionally:

• In apps/web/src/lib/stack-url-state.ts, precompute and validate the IDs:

const AUTH_IDS = getValidIds("auth");
const DEFAULT_AUTH = AUTH_IDS.includes(DEFAULT_STACK.auth)
  ? DEFAULT_STACK.auth
  : AUTH_IDS[0] ?? DEFAULT_STACK.auth; // fallback if options shift

• Update the parser to use these constants:

 export const stackParsers = {
   …
-  auth: parseAsStringEnum<StackState["auth"]>(getValidIds("auth")).withDefault(
-    DEFAULT_STACK.auth,
-  ),
+  auth: parseAsStringEnum<StackState["auth"]>(AUTH_IDS).withDefault(DEFAULT_AUTH),
   …
 };

This optional refactor reduces redundant calls and ensures the default remains valid even if TECH_OPTIONS.auth is ever modified.

apps/cli/templates/auth/clerk/convex/web/react/next/src/app/dashboard/page.tsx.hbs (1)

7-19: Add a lightweight loading state for the private query.

useQuery returns undefined while loading; render a small fallback to avoid flashing “undefined”.

       <Authenticated>
-        <div>
-          <h1>Dashboard</h1>
-          <p>Welcome {privateData?.user?.name}</p>
-          <p>privateData: {privateData?.message}</p>
-          <UserButton />
-        </div>
+        {privateData === undefined ? (
+          <p>Loading...</p>
+        ) : (
+          <div>
+            <h1>Dashboard</h1>
+            <p>Welcome {privateData.user?.name}</p>
+            <p>privateData: {privateData.message}</p>
+            <UserButton />
+          </div>
+        )}
       </Authenticated>
apps/cli/templates/frontend/react/next/src/components/providers.tsx.hbs (1)

27-28: Fail fast if NEXT_PUBLIC_CONVEX_URL is missing.

Surfacing a clear error helps new projects diagnose misconfig quickly.

-const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL!);
+const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL;
+if (!convexUrl) {
+  throw new Error("Missing NEXT_PUBLIC_CONVEX_URL. Set it in your .env.local.");
+}
+const convex = new ConvexReactClient(convexUrl);
apps/cli/src/utils/display-config.ts (1)

42-44: Improve backward-compat display for legacy boolean auth.

Older detected configs may still set a boolean; show Yes/No for booleans to keep output tidy.

-  if (config.auth !== undefined) {
-    configDisplay.push(`${pc.blue("Authentication:")} ${String(config.auth)}`);
-  }
+  if (config.auth !== undefined) {
+    const authText =
+      typeof config.auth === "boolean" ? (config.auth ? "Yes" : "No") : String(config.auth);
+    configDisplay.push(`${pc.blue("Authentication:")} ${authText}`);
+  }
apps/cli/src/helpers/core/command-handlers.ts (1)

157-162: Standardize “auto-set” message flag formatting.

Mixes auth=none with --database=none and --auth none. Prefer consistent --flag <value> for readability.

- "Due to '--backend convex' flag, the following options have been automatically set: auth=none, database=none, orm=none, api=none, runtime=none, dbSetup=none, examples=todo",
+ "Due to '--backend convex' flag, the following options have been automatically set: --auth none, --database none, --orm none, --api none, --runtime none, --db-setup none, --examples todo",
@@
- "Due to '--backend none', the following options have been automatically set: --auth none, --database=none, --orm=none, --api=none, --runtime=none, --db-setup=none, --examples=none",
+ "Due to '--backend none', the following options have been automatically set: --auth none, --database none, --orm none, --api none, --runtime none, --db-setup none, --examples none",
apps/cli/src/helpers/addons/auth-setup.ts (1)

10-12: Convex short-circuit blocks provider-specific setup (no path for Clerk).

Early return on backend === "convex" prevents any auth provider setup. If Convex + Clerk is intended, consider branching by provider instead of exiting here, or add a clear TODO pointing to where Clerk deps are added (templates vs. installer). Without that, Convex projects cannot get provider-driven deps via this helper.

Apply this minimal structure to future-proof provider handling:

-  if (backend === "convex" || !auth || auth === "none") {
-    return;
-  }
+  if (!auth || auth === "none") return;
+
+  // Provider-specific handling (Convex may only allow Clerk)
+  if (backend === "convex") {
+    if (auth === "clerk") {
+      // no-op if templates include deps; otherwise add Clerk deps here
+      // TODO: implement/add comment referencing template-managed deps
+    }
+    return;
+  }
apps/cli/src/index.ts (2)

206-206: Doc example updated — suggest listing allowed values.

Small DX win: mention allowed values ("better-auth" | "clerk" | "none") in JSDoc.

Suggested tweak:

- *   auth: "better-auth",
+ *   auth: "better-auth", // "better-auth" | "clerk" | "none"

247-266: Re-export Auth type for programmatic consumers.

Expose Auth alongside other public types to ease type-safe callers.

Patch:

 export type {
   Database,
   ORM,
   Backend,
   Runtime,
   Frontend,
   Addons,
   Examples,
   PackageManager,
   DatabaseSetup,
   API,
   WebDeploy,
   ServerDeploy,
   DirectoryConflict,
   CreateInput,
   AddInput,
   ProjectConfig,
   BetterTStackConfig,
   InitResult,
+  // New:
+  Auth,
 };
apps/cli/src/prompts/config-prompts.ts (1)

79-83: Avoid inline import type-cast; use the imported Auth type.

Local Auth import exists; prefer that for clarity.

-        getAuthChoice(
-          flags.auth as import("../types").Auth | undefined,
+        getAuthChoice(
+          flags.auth as Auth | undefined,
           results.database !== "none",
           results.backend,
         ),
apps/cli/src/prompts/auth.ts (1)

12-16: Consistent typing: avoid unnecessary cast on "none".

Line 12 casts to Auth while line 15 returns "none" without a cast. Prefer consistent style; rely on inference or cast both.

-    return "none" as Auth;
+    return "none";
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 77b3b72 and 1ac5946.

📒 Files selected for processing (19)
  • apps/cli/src/constants.ts (1 hunks)
  • apps/cli/src/helpers/addons/auth-setup.ts (3 hunks)
  • apps/cli/src/helpers/core/command-handlers.ts (2 hunks)
  • apps/cli/src/helpers/core/create-project.ts (1 hunks)
  • apps/cli/src/helpers/core/create-readme.ts (5 hunks)
  • apps/cli/src/index.ts (3 hunks)
  • apps/cli/src/prompts/auth.ts (1 hunks)
  • apps/cli/src/prompts/config-prompts.ts (4 hunks)
  • apps/cli/src/types.ts (4 hunks)
  • apps/cli/src/utils/compatibility-rules.ts (4 hunks)
  • apps/cli/src/utils/config-processing.ts (2 hunks)
  • apps/cli/src/utils/display-config.ts (1 hunks)
  • apps/cli/src/utils/generate-reproducible-command.ts (1 hunks)
  • apps/cli/templates/auth/clerk/convex/web/react/next/src/app/dashboard/page.tsx.hbs (1 hunks)
  • apps/cli/templates/auth/clerk/convex/web/react/next/src/middleware.ts.hbs (1 hunks)
  • apps/cli/templates/frontend/react/next/src/components/providers.tsx.hbs (2 hunks)
  • apps/web/src/app/(home)/_components/stack-builder.tsx (6 hunks)
  • apps/web/src/lib/constant.ts (8 hunks)
  • apps/web/src/lib/stack-url-state.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/convex_rules.mdc)

**/*.{ts,tsx}: Use Id from './_generated/dataModel' to type document ids (e.g., Id<'users'>)
Ensure Record key/value types align with validators (e.g., v.record(v.id('users'), v.string()) => Record<Id<'users'>, string>)
Be strict with types for document ids; prefer Id<'table'> over string
Use 'as const' for string literals in discriminated unions
When using Array and Record types, declare with explicit generic types (e.g., const arr: Array = ...)

Files:

  • apps/cli/src/types.ts
  • apps/cli/src/helpers/core/create-project.ts
  • apps/cli/src/utils/config-processing.ts
  • apps/cli/src/utils/display-config.ts
  • apps/cli/src/utils/compatibility-rules.ts
  • apps/cli/src/helpers/core/command-handlers.ts
  • apps/cli/src/prompts/auth.ts
  • apps/cli/src/helpers/addons/auth-setup.ts
  • apps/web/src/app/(home)/_components/stack-builder.tsx
  • apps/cli/src/utils/generate-reproducible-command.ts
  • apps/cli/src/prompts/config-prompts.ts
  • apps/web/src/lib/constant.ts
  • apps/cli/src/constants.ts
  • apps/web/src/lib/stack-url-state.ts
  • apps/cli/src/index.ts
  • apps/cli/src/helpers/core/create-readme.ts
**/*.{js,jsx,ts,tsx,mjs,cjs}

📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)

**/*.{js,jsx,ts,tsx,mjs,cjs}: Do not use dotenv; Bun auto-loads .env
Use Bun.serve() for HTTP/WebSockets; do not use express
Use bun:sqlite for SQLite; do not use better-sqlite3
Use Bun.redis for Redis; do not use ioredis
Use Bun.sql for Postgres; do not use pg or postgres.js
Use built-in WebSocket; do not use ws
Prefer Bun.file over node:fs readFile/writeFile
Use Bun.$ instead of execa for shelling out

Files:

  • apps/cli/src/types.ts
  • apps/cli/src/helpers/core/create-project.ts
  • apps/cli/src/utils/config-processing.ts
  • apps/cli/src/utils/display-config.ts
  • apps/cli/src/utils/compatibility-rules.ts
  • apps/cli/src/helpers/core/command-handlers.ts
  • apps/cli/src/prompts/auth.ts
  • apps/cli/src/helpers/addons/auth-setup.ts
  • apps/web/src/app/(home)/_components/stack-builder.tsx
  • apps/cli/src/utils/generate-reproducible-command.ts
  • apps/cli/src/prompts/config-prompts.ts
  • apps/web/src/lib/constant.ts
  • apps/cli/src/constants.ts
  • apps/web/src/lib/stack-url-state.ts
  • apps/cli/src/index.ts
  • apps/cli/src/helpers/core/create-readme.ts
🧠 Learnings (1)
📚 Learning: 2025-08-24T18:01:11.544Z
Learnt from: CR
PR: AmanVarshney01/create-better-t-stack#0
File: .cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc:0-0
Timestamp: 2025-08-24T18:01:11.544Z
Learning: Applies to **/*.{js,jsx,ts,tsx,mjs,cjs} : Use `bun:sqlite` for SQLite; do not use `better-sqlite3`

Applied to files:

  • apps/web/src/lib/constant.ts
🧬 Code graph analysis (9)
apps/cli/src/utils/config-processing.ts (1)
apps/cli/src/types.ts (1)
  • Auth (86-86)
apps/cli/src/utils/display-config.ts (1)
apps/cli/templates/backend/server/next/src/middleware.ts (1)
  • config (17-19)
apps/cli/src/utils/compatibility-rules.ts (1)
apps/cli/src/types.ts (1)
  • ProjectConfig (164-183)
apps/cli/src/prompts/auth.ts (3)
apps/cli/src/types.ts (2)
  • Auth (86-86)
  • Backend (16-16)
apps/cli/src/constants.ts (1)
  • DEFAULT_CONFIG (40-40)
apps/cli/src/utils/errors.ts (1)
  • exitCancelled (17-23)
apps/cli/src/helpers/addons/auth-setup.ts (1)
apps/cli/src/utils/add-package-deps.ts (1)
  • addPackageDependency (6-43)
apps/cli/src/prompts/config-prompts.ts (2)
apps/cli/src/types.ts (1)
  • Auth (86-86)
apps/cli/src/prompts/auth.ts (1)
  • getAuthChoice (6-32)
apps/web/src/lib/stack-url-state.ts (1)
apps/web/src/lib/constant.ts (1)
  • StackState (696-714)
apps/cli/src/index.ts (1)
apps/cli/src/types.ts (1)
  • AuthSchema (83-85)
apps/cli/src/helpers/core/create-readme.ts (1)
apps/cli/src/types.ts (1)
  • Auth (86-86)
🔇 Additional comments (23)
apps/cli/templates/frontend/react/next/src/components/providers.tsx.hbs (1)

4-8: Conditional Convex+Clerk provider wiring looks correct.

Imports and JSX branches correctly switch to ConvexProviderWithClerk when auth === "clerk". Nice.

Also applies to: 43-49

apps/cli/templates/auth/clerk/convex/web/react/next/src/middleware.ts.hbs (1)

1-12: LGTM; matcher is appropriately scoped for Clerk middleware.

Reasonable defaults that skip static assets and include API/TRPC routes.

apps/cli/src/types.ts (1)

83-87: AuthSchema addition looks good and future-proof.

Enum values match the new flow; exported Auth type is clear.

apps/cli/src/utils/generate-reproducible-command.ts (1)

17-17: Confirmed --auth <value> flag correctly enforces string union

I verified that the CLI parser and generators rely on the new AuthSchema and always emit --auth <value>, where <value> must be one of "better-auth" | "clerk" | "none" (no boolean support):

• AuthSchema is defined as z.enum(["better-auth","clerk","none"]) in apps/cli/src/types.ts (lines 83–86).
• The root parser schema includes auth: AuthSchema.optional() in apps/cli/src/index.ts (lines 15 & 82).
• The reproducible-command util always does flags.push(\--auth ${config.auth}`)inapps/cli/src/utils/generate-reproducible-command.ts` (line 17).

No further changes needed here.

apps/cli/src/constants.ts (1)

16-16: Default auth: "better-auth" as a literal — LGTM.

Matches the new Auth union and keeps defaults sane.

apps/cli/src/helpers/core/command-handlers.ts (1)

106-107: Fallback auth: "none" in error result — OK.

Consistent with typed defaults and safer than boolean false.

apps/cli/src/utils/compatibility-rules.ts (1)

178-180: Backend "none" rejecting any auth — OK.

Projects without a backend shouldn’t install/auth wireups.

apps/web/src/lib/constant.ts (2)

399-412: Auth providers added correctly; labels/icons/readability look good.

"Better-Auth" default and "Clerk" provider are wired consistently with TECH_OPTIONS. No issues.


597-597: Presets/defaults align with new auth model; convex defaulting to "none" noted.

Defaults/presets use "better-auth" (general) and "none" (convex) coherently. This sets user expectation that Convex has no auth by default.

Also applies to: 619-619, 641-641, 663-663, 685-685, 725-725, 748-748

apps/web/src/app/(home)/_components/stack-builder.tsx (3)

160-162: Light-theme icon swap extended to Clerk and Express.

Nice UX polish; safe change.


340-354: DB=none ⇒ Auth=none coercion is good.

Consistent with dependency constraints; note text is clear.


1529-1538: Boolean toggle restriction to git/install only is correct.

Keeps auth out of legacy boolean flip logic. Good separation.

apps/cli/src/helpers/core/create-readme.ts (1)

7-7: Type import for Auth is correct.

Keeps generated docs aligned with new schema.

apps/cli/src/utils/config-processing.ts (1)

4-4: Auth flag processing wired to Auth type.

Casts look correct; no issues.

Also applies to: 61-62

apps/cli/src/helpers/addons/auth-setup.ts (3)

23-28: Scoped Better-Auth server deps — LGTM.

Only adding better-auth to apps/server when present and selected keeps workspaces clean.


42-49: Web deps guarded by framework presence and provider — LGTM.

The hasWebFrontend check plus auth === "better-auth" avoids accidental installs.


56-67: Verify whether the Expo adapter belongs in the server workspace

I didn’t find any references to @better-auth/expo in the CLI codebase itself (there’s no apps/server folder here), which suggests this dependency is only added for the user’s project if a apps/server directory exists. Since @better-auth/expo is a runtime adapter for native/Expo environments, it typically isn’t consumed by a backend. Please confirm in your project whether any server-side code imports or uses @better-auth/expo. If not, it’s safe to remove this block.

• Location to inspect/remove:
• File: apps/cli/src/helpers/addons/auth-setup.ts
• Lines: 61–67

-        if (serverDirExists) {
-          await addPackageDependency({
-            dependencies: ["@better-auth/expo"],
-            projectDir: serverDir,
-          });
-        }
+        // No server-side usage of Expo adapter expected; remove this block if unused
apps/cli/src/index.ts (2)

15-15: Importing AuthSchema — LGTM.

Aligns API validation with new string-union provider model.


82-82: Auth input validated via AuthSchema — LGTM.

Prevents legacy boolean inputs from slipping through.

apps/cli/src/prompts/config-prompts.ts (3)

5-5: Auth type import — LGTM.

Keeps prompt result strongly typed to provider union.


42-42: PromptGroupResults.auth typed as Auth — LGTM.

Prevents regressions back to boolean.


133-141: Defaulting auth to "none" when backend is "none" — LGTM.

Consistent with provider selection semantics.

apps/cli/src/prompts/auth.ts (1)

19-27: Provider list — LGTM.

Select prompt reflects the new union and sane default via DEFAULT_CONFIG.auth.

Comment thread apps/cli/src/prompts/auth.ts Resolved
Comment thread apps/cli/src/types.ts Resolved

@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: 13

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (14)
apps/cli/templates/deploy/alchemy/alchemy.run.ts.hbs (2)

54-54: Fix cwd conditionals: currently gated by the wrong deploy flag(s).

  • Web runners set cwd: "apps/web" only when serverDeploy === "alchemy". This breaks when only web uses Alchemy.
  • Server worker sets cwd: "apps/server" only when webDeploy === "alchemy". This breaks when only server uses Alchemy.
  • Exec for D1 DB generate sets cwd only when both web+server are Alchemy.

Make these cwd assignments unconditional within their respective blocks.

Apply this diff:

@@
-  {{#if (and (eq webDeploy "alchemy") (eq serverDeploy "alchemy"))}}cwd: "apps/server",{{/if}}
+  cwd: "apps/server",
   command: "{{packageManager}} run db:generate",
@@
-export const web = await Next("web", {
-  {{#if (eq serverDeploy "alchemy")}}cwd: "apps/web",{{/if}}
+export const web = await Next("web", {
+  cwd: "apps/web",
@@
-export const web = await Nuxt("web", {
-  {{#if (eq serverDeploy "alchemy")}}cwd: "apps/web",{{/if}}
+export const web = await Nuxt("web", {
+  cwd: "apps/web",
@@
-export const web = await SvelteKit("web", {
-  {{#if (eq serverDeploy "alchemy")}}cwd: "apps/web",{{/if}}
+export const web = await SvelteKit("web", {
+  cwd: "apps/web",
@@
-export const web = await TanStackStart("web", {
-  {{#if (eq serverDeploy "alchemy")}}cwd: "apps/web",{{/if}}
+export const web = await TanStackStart("web", {
+  cwd: "apps/web",
@@
-export const web = await Vite("web", {
-  {{#if (eq serverDeploy "alchemy")}}cwd: "apps/web",{{/if}}
+export const web = await Vite("web", {
+  cwd: "apps/web",
@@
-export const web = await ReactRouter("web", {
-  {{#if (eq serverDeploy "alchemy")}}cwd: "apps/web",{{/if}}
+export const web = await ReactRouter("web", {
+  cwd: "apps/web",
@@
-export const web = await Vite("web", {
-  {{#if (eq serverDeploy "alchemy")}}cwd: "apps/web",{{/if}}
+export const web = await Vite("web", {
+  cwd: "apps/web",
@@
-export const server = await Worker("server", {
-  {{#if (eq webDeploy "alchemy")}}cwd: "apps/server",{{/if}}
+export const server = await Worker("server", {
+  cwd: "apps/server",

Also applies to: 68-68, 82-82, 96-96, 110-110, 125-125, 139-139, 157-157, 41-44


160-177: Add missing Clerk bindings for Alchemy deploy

The clerk auth option isn’t handled in alchemy.run.ts.hbs, so requests will fail when auth === "clerk" due to missing credentials.

• File: apps/cli/templates/deploy/alchemy/alchemy.run.ts.hbs, around lines 160–177
• Insert a new conditional block for Clerk immediately after the Better-Auth bindings

Suggested diff:

   bindings: {
     CORS_ORIGIN: process.env.CORS_ORIGIN || "",
     {{#if (eq auth "better-auth")}}
     BETTER_AUTH_SECRET: alchemy.secret(process.env.BETTER_AUTH_SECRET),
     BETTER_AUTH_URL: process.env.BETTER_AUTH_URL || "",
     {{/if}}
+    {{#if (eq auth "clerk")}}
+    CLERK_SECRET_KEY: alchemy.secret(process.env.CLERK_SECRET_KEY),
+    CLERK_JWT_ISSUER: process.env.CLERK_JWT_ISSUER || "",
+    {{/if}}
     {{#if (includes examples "ai")}}
     GOOGLE_GENERATIVE_AI_API_KEY: alchemy.secret(process.env.GOOGLE_GENERATIVE_AI_API_KEY),
     {{/if}}
     {{#if (eq dbSetup "turso")}}
     DATABASE_AUTH_TOKEN: alchemy.secret(process.env.DATABASE_AUTH_TOKEN),
     {{/if}}
   },

Please confirm whether your server-side integration expects CLERK_JWT_ISSUER (versus e.g. CLERK_JWT_ISSUER_URL), so we can adjust the variable name accordingly.

apps/web/src/app/(home)/_components/stack-builder.tsx (2)

203-213: Blocking: Convex override forces auth='none', preventing Clerk-on-Convex.

This contradicts the PR goal (“add clerk auth support with convex”) and makes Clerk impossible whenever backend is Convex.

Apply this diff to stop forcing auth off for Convex:

   if (isConvex) {
     const convexOverrides: Partial<StackState> = {
       runtime: "none",
       database: "none",
       orm: "none",
       api: "none",
-      auth: "none",
       dbSetup: "none",
       examples: ["todo"],
     };

Then, prefer Clerk when an unsupported auth is selected under Convex:

@@
-    }
+    }
+
+    // Normalize auth for Convex: allow only 'clerk' or 'none'
+    if (nextStack.auth !== "clerk" && nextStack.auth !== "none") {
+      notes.auth.notes.push(
+        "Convex supports 'Clerk' or 'None' authentication. 'Clerk' will be selected.",
+      );
+      notes.auth.hasIssue = true;
+      nextStack.auth = "clerk";
+      changed = true;
+      changes.push({
+        category: "convex",
+        message: "Auth set to 'Clerk' (Convex supports Clerk or None)",
+      });
+    }

955-1002: Bug: Missing changed = true after mutations under serverDeploy → Workers path.

You mutate nextStack.orm, nextStack.database, and nextStack.dbSetup but don’t flip changed, risking adjustedStack=null despite changes.

Apply these diffs:

@@
   if (nextStack.orm !== "drizzle" && nextStack.orm !== "none") {
@@
     nextStack.orm = "drizzle";
+    changed = true;
@@
   if (nextStack.database === "mongodb") {
@@
     nextStack.database = "sqlite";
+    changed = true;
@@
   if (nextStack.dbSetup === "docker") {
@@
     nextStack.dbSetup = "d1";
+    changed = true;
apps/cli/src/helpers/core/env-setup.ts (1)

243-259: BETTER_AUTH_ envs are set for any truthy auth; restrict to better-auth only.*

When auth === "clerk", this still writes BETTER_AUTH_SECRET and BETTER_AUTH_URL. Gate these on auth === "better-auth".

Apply:

@@
-    {
-      key: "BETTER_AUTH_SECRET",
-      value: generateAuthSecret(),
-      condition: !!auth,
-    },
-    {
-      key: "BETTER_AUTH_URL",
-      value: "http://localhost:3000",
-      condition: !!auth,
-    },
+    {
+      key: "BETTER_AUTH_SECRET",
+      value: generateAuthSecret(),
+      condition: auth === "better-auth",
+    },
+    {
+      key: "BETTER_AUTH_URL",
+      value: "http://localhost:3000",
+      condition: auth === "better-auth",
+    },
apps/cli/templates/frontend/react/tanstack-start/src/router.tsx.hbs (1)

85-93: Ensure cookies are sent for Clerk too (not just Better Auth).

For cookie-based auth, omitting credentials: "include" will drop session cookies when calling the server across origins. Gate this for any auth ≠ "none" so Clerk works as well.

-      {{#if (eq auth "better-auth")}}
+      {{#if (ne auth "none")}}
       fetch(url, options) {
         return fetch(url, {
           ...options,
           credentials: "include",
         });
       },
       {{/if}}
apps/cli/templates/addons/ruler/.ruler/bts.md.hbs (1)

80-95: Support Clerk Authentication in the Ruler Markdown Template

The current bts.md.hbs only renders the Authentication section when auth === "better-auth", which prevents any guidance from appearing for Clerk users. We should show this section for all non-none auth providers.

• File: apps/cli/templates/addons/ruler/.ruler/bts.md.hbs
Replace the outer conditional to gate on auth !== "none" instead of only "better-auth".

-{{#if (eq auth "better-auth")}}
+{{#if (ne auth "none")}}

After widening the gate, we can follow up with updated copy for Clerk—e.g. links to @clerk/nextjs setup, environment variables, and any server-side considerations—so that users see accurate paths and instructions for Clerk integration.

apps/cli/templates/backend/server/fastify/src/index.ts.hbs (1)

80-109: Avoid forwarding restricted hop-by-hop headers to Fetch.

Forwarding headers like host, content-length, connection, accept-encoding can throw or cause incorrect behavior.

-  Object.entries(request.headers).forEach(([key, value]) => {
-    if (value) headers.append(key, value.toString());
-  });
+  const forbidden = new Set(["host", "content-length", "connection", "accept-encoding", "transfer-encoding"]);
+  Object.entries(request.headers).forEach(([key, value]) => {
+    if (value && !forbidden.has(key.toLowerCase())) {
+      headers.append(key, value.toString());
+    }
+  });
apps/cli/templates/api/orpc/web/nuxt/app/plugins/orpc.ts.hbs (1)

15-22: Send cookies for Clerk as well (not only Better Auth).

Without credentials: "include", browser won’t send auth cookies to /rpc when cross-origin.

-    {{#if (eq auth "better-auth")}}
+    {{#if (ne auth "none")}}
     fetch(url, options) {
         return fetch(url, {
         ...options,
         credentials: "include",
         });
     },
     {{/if}}
apps/cli/templates/api/orpc/web/react/base/src/utils/orpc.ts.hbs (1)

29-36: Clerk likely needs credentials or headers—gating only for better-auth is too narrow

If Clerk uses cookie-based sessions, you’ll need credentials: "include" as well. Expand the guard to cover Clerk.

Apply:

-  {{#if (eq auth "better-auth")}}
+  {{#if (or (eq auth "better-auth") (eq auth "clerk"))}}
   fetch(url, options) {
     return fetch(url, {
       ...options,
       credentials: "include",
     });
   },
   {{/if}}
apps/cli/templates/api/trpc/web/react/base/src/utils/trpc.ts.hbs (2)

31-38: Broaden fetch credentials to support Clerk where cookies are used

Mirror better-auth behavior for Clerk to avoid auth breakage on cross-origin calls.

Apply:

-      {{#if (eq auth "better-auth")}}
+      {{#if (or (eq auth "better-auth") (eq auth "clerk"))}}
       fetch(url, options) {
         return fetch(url, {
           ...options,
           credentials: "include",
         });
       },
       {{/if}}

81-88: Same fix for the non-Next path

Keep behavior consistent across both code paths.

Apply:

-      {{#if (eq auth "better-auth")}}
+      {{#if (or (eq auth "better-auth") (eq auth "clerk"))}}
       fetch(url, options) {
         return fetch(url, {
           ...options,
           credentials: "include",
         });
       },
       {{/if}}
apps/cli/templates/api/orpc/web/svelte/src/lib/orpc.ts.hbs (1)

18-25: Include credentials for Clerk when using cookie sessions

Parallels React template to avoid auth issues.

Apply:

-	{{#if (eq auth "better-auth")}}
+	{{#if (or (eq auth "better-auth") (eq auth "clerk"))}}
 	fetch(url, options) {
 		return fetch(url, {
 			...options,
 			credentials: "include",
 		});
 	},
 	{{/if}}
apps/cli/templates/api/trpc/server/base/src/lib/trpc.ts.hbs (1)

10-26: Ensure a fallback protectedProcedure for all auth modes to prevent broken imports

Verification shows that protectedProcedure is only exported when auth === "better-auth" in

  • apps/cli/templates/api/trpc/server/base/src/lib/trpc.ts.hbs (lines 10–26)
    and is imported conditionally—even though routers reference it unconditionally—in
  • apps/cli/templates/backend/server/server-base/src/routers/index.ts.hbs (import at line 2; usage at lines 13 & 40) .

As a result, when auth is "clerk" or "none", generated code will fail due to a missing protectedProcedure. To fix this, update the trpc.ts.hbs template to always emit a protectedProcedure, with mode-specific behavior and a no-op fallback:

-{{#if (eq auth "better-auth")}}
-export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
-  if (!ctx.session) {
-    throw new TRPCError({
-      code: "UNAUTHORIZED",
-      message: "Authentication required",
-      cause: "No session",
-    });
-  }
-  return next({
-    ctx: { ...ctx, session: ctx.session },
-  });
-});
-{{/if}}
+{{#if (eq auth "better-auth")}}
+export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
+  if (!ctx.session) {
+    throw new TRPCError({
+      code: "UNAUTHORIZED",
+      message: "Authentication required",
+      cause: "No session",
+    });
+  }
+  return next({ ctx: { ...ctx, session: ctx.session } });
+});
+{{else if (eq auth "clerk")}}
+export const protectedProcedure = t.procedure.use(({ ctx, next }) => {
+  if (!ctx.auth?.userId) {
+    throw new TRPCError({ code: "UNAUTHORIZED", message: "Authentication required" });
+  }
+  return next({ ctx });
+});
+{{else}}
+// No-auth mode: export no-op to satisfy imports
+export const protectedProcedure = t.procedure;
+{{/if}}

With this change:

  • Routers can continue to import protectedProcedure unconditionally.
  • Behavior adjusts based on auth (“better-auth”, “clerk”, or none) without breaking templates.
♻️ Duplicate comments (3)
apps/web/src/app/(home)/_components/stack-builder.tsx (1)

1124-1126: Still not emitting --auth for Convex when non-default. Move out of Convex guard.

This was flagged earlier; it persists. Non-default auth (e.g., Clerk) won’t be reflected in the command for Convex.

-    if (!checkDefault("auth", stackState.auth)) {
-      flags.push(`--auth ${stackState.auth}`);
-    }

Insert after the Convex/non-Convex block (below Line 1131):

+  // Emit auth flag for any backend when it differs from default.
+  if (!checkDefault("auth", stackState.auth)) {
+    flags.push(`--auth ${stackState.auth}`);
+  }
apps/cli/src/helpers/core/create-project.ts (1)

73-75: Auth runtime setup now runs for Convex+Clerk too — aligns with prior guidance.

apps/cli/src/prompts/auth.ts (1)

11-23: Convex prompt now allows Clerk/None — resolves prior concern

This addresses the earlier feedback that Convex was forcing none. Good change.

🧹 Nitpick comments (26)
apps/cli/templates/frontend/nuxt/app/components/Header.vue.hbs (3)

3-5: Clerk menu import path missing; add Clerk UI import (or confirm it’s auto-registered).

Right now only "better-auth" imports a user menu. In "clerk" mode, consider importing Clerk UI components (unless your Nuxt module auto-registers them) so the header can render auth controls.

-{{#if (eq auth "better-auth")}}
-import UserMenu from './UserMenu.vue'
-{{/if}}
+{{#if (eq auth "better-auth")}}
+import UserMenu from './UserMenu.vue'
+{{else if (eq auth "clerk")}}
+// If not using auto-registered components, import Clerk UI:
+import { SignedIn, SignedOut, SignInButton, UserButton } from '@clerk/vue'
+{{/if}}

9-11: Dashboard link gating: looks consistent; verify route + protection exist for both auth modes.

Showing “Dashboard” for both "better-auth" and "clerk" is consistent with the new enum. Please confirm that the Nuxt /dashboard page and middleware/route guards are generated in both templates so this link doesn’t 404 or expose unprotected content. Optionally hide the link for signed-out users (e.g., Clerk’s ).


37-39: Render Clerk header controls (SignedIn/UserButton + SignedOut/SignInButton).

Provide a user control area when auth === "clerk" (current code renders nothing). Wrapping in helps avoid SSR hydration issues.

-{{#if (eq auth "better-auth")}}
-<UserMenu />
-{{/if}}
+{{#if (eq auth "better-auth")}}
+<UserMenu />
+{{else if (eq auth "clerk")}}
+<ClientOnly>
+  <SignedIn><UserButton /></SignedIn>
+  <SignedOut><SignInButton mode="modal">Sign in</SignInButton></SignedOut>
+</ClientOnly>
+{{/if}}
apps/cli/templates/auth/clerk/convex/backend/convex/privateData.ts.hbs (3)

1-5: Include returns validator per Convex new function syntax

Per your Convex rules (“Always use new syntax with args/returns/handler”), add returns and import v.

-import { query } from "./_generated/server";
+import { query } from "./_generated/server";
+import { v } from "convex/values";
 
 export const get = query({
-  args: {},
+  args: {},
+  returns: v.object({
+    message: v.string(),
+    user: v.optional(v.any()),
+  }),

6-15: Avoid duplicate identity fetch; reuse the value

Minor cleanup and micro-optimization: reuse identity instead of calling ctx.auth.getUserIdentity() twice.

-    const identity = await ctx.auth.getUserIdentity();
-    if (identity === null) {
+    const identity = await ctx.auth.getUserIdentity();
+    if (identity === null) {
       return {
         message: "Not authenticated",
       };
     }
-    return {
-      message: "This is private",
-      user: await ctx.auth.getUserIdentity(),
-    };
+    return {
+      message: "This is private",
+      user: identity,
+    };

6-15: Consider normalizing the response shape and limiting PII

Today the unauthenticated path omits user, while the authenticated path includes it. Consider always returning { message, user } with user: null when unauthenticated, and/or whitelisting safe fields (e.g., subject, email) to avoid leaking unexpected PII to clients.

Would you like me to update the template to always return { message, user } and map identity to a minimal shape?

apps/cli/templates/deploy/alchemy/alchemy.run.ts.hbs (1)

167-167: Optional: fail fast on missing CORS_ORIGIN.

Empty default can mask misconfig; consider asserting non-empty in dev or defaulting to web.url when both are on Alchemy.

apps/cli/templates/frontend/svelte/src/components/Header.svelte.hbs (1)

8-10: Gate Dashboard for Clerk too (or for any non-"none" auth)

If the Dashboard exists for Clerk, it should be visible there as well.

         {{#if (eq auth "better-auth")}}
         { to: "/dashboard", label: "Dashboard" },
         {{/if}}
+        {{#if (eq auth "clerk")}}
+        { to: "/dashboard", label: "Dashboard" },
+        {{/if}}

If Dashboard is only scaffolded for better-auth, ignore this.

apps/cli/templates/frontend/solid/src/components/header.tsx.hbs (1)

30-32: User menu render path doesn’t cover Clerk.

Same issue as the import: only renders for "better-auth". Add a Clerk branch or render a provider-agnostic AuthUserMenu.

Example (template-level; adjust to actual component names you ship):

-          {{#if (eq auth "better-auth")}}
-          <UserMenu />
-          {{/if}}
+          {{#if (eq auth "better-auth")}}
+          <UserMenu />
+          {{/if}}
+          {{#if (eq auth "clerk")}}
+          <ClerkUserMenu />
+          {{/if}}

If you adopt a wrapper:

-          {{#if (eq auth "better-auth")}}
-          <UserMenu />
-          {{/if}}
+          {{#unless (eq auth "none")}}
+          <AuthUserMenu />
+          {{/unless}}
apps/web/src/app/(home)/_components/stack-builder.tsx (1)

359-364: Copy text mismatch: says “Basic/Basic Setup” but code sets dbSetup='none'.

Align the user-facing notes with the actual value.

-          "Database 'None' selected: DB Setup will be set to 'Basic'.",
+          "Database 'None' selected: DB Setup will be set to 'None'.",
@@
-          "DB Setup requires a database. It will be set to 'Basic Setup'.",
+          "DB Setup requires a database. It will be set to 'None'.",
apps/cli/src/helpers/core/env-setup.ts (1)

147-166: Add optional canonical Clerk env var alias for parity

I ran a search across the repo for the existing Clerk environment variable keys and only found their definitions in apps/cli/src/helpers/core/env-setup.ts. Adding the widely used server-side alias won’t conflict with any existing references but will improve alignment with Clerk’s docs.

• File: apps/cli/src/helpers/core/env-setup.ts (lines 147–166)
• Search confirmed no other occurrences of these keys beyond this snippet

Suggested patch (optional refactor):

@@ apps/cli/src/helpers/core/env-setup.ts
-      if (backend === "convex" && auth === "clerk" && hasNextJs) {
+      if (backend === "convex" && auth === "clerk" && hasNextJs) {
         clientVars.push(
           {
             key: "NEXT_PUBLIC_CLERK_FRONTEND_API_URL",
             value: "",
             condition: true,
           },
+          {
+            // Optional server-side alias for parity with Clerk docs
+            key: "CLERK_FRONTEND_API_URL",
+            value: "",
+            condition: true,
+          },
           {
             key: "NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY",
             value: "",
             condition: true,
           },
           {
             key: "CLERK_SECRET_KEY",
             value: "",
             condition: true,
           },
         );
       }
apps/cli/src/helpers/core/template-manager.ts (1)

529-586: Web provider templates selection is correct; ensure coverage for all frameworks in enum.

If new frameworks are added to types, remember to extend this switch.

apps/cli/templates/backend/convex/packages/backend/package.json.hbs (1)

12-14: Align @types/node with the targeted Node runtime.

Types 24.x may not match your project’s Node LTS in 2025 (commonly 22.x). Recommend matching the engine you scaffold or parameterizing it.

-    "@types/node": "^24.3.0",
+    "@types/node": "^22.0.0",

Optionally expose a {{nodeTypesVersion}} variable to keep this consistent across templates.

apps/cli/templates/backend/server/elysia/src/index.ts.hbs (1)

41-48: Return the 405 response explicitly

Minor clarity/readability.

Apply:

     if (["POST", "GET"].includes(request.method)) {
       return auth.handler(request);
     }
-    context.error(405);
+    return context.error(405);
apps/cli/test/programmatic-api.test.ts (1)

316-329: Enhance programmatic-API tests to fully cover auth options

To ensure the new auth enum is exercised end-to-end in the programmatic API, please update apps/cli/test/programmatic-api.test.ts around lines 316–329 to:

  • Add two new test cases mirroring the existing better-auth case but with auth: "clerk" and auth: "none".
  • After verifying result.projectConfig.auth, assert that result.reproducibleCommand includes the corresponding --auth flag.

Suggested diff:

       const result = await init("auth-app", {
         yes: true,
         auth: "better-auth",
         database: "sqlite",
         orm: "drizzle",
         install: false,
         git: false,
       });

       expect(result.success).toBe(true);
       await assertBtsConfig(result.projectDirectory, {
         database: "sqlite",
         orm: "drizzle",
       });
       expect(result.projectConfig.auth).toBe("better-auth");
+      expect(result.reproducibleCommand).toContain("--auth better-auth");

And add two sibling tests:

// Clerk auth
const clerkResult = await init("auth-app-clerk", {
  yes: true,
  auth: "clerk",
  database: "sqlite",
  orm: "drizzle",
  install: false,
  git: false,
});
expect(clerkResult.success).toBe(true);
await assertBtsConfig(clerkResult.projectDirectory, { database: "sqlite", orm: "drizzle" });
expect(clerkResult.projectConfig.auth).toBe("clerk");
expect(clerkResult.reproducibleCommand).toContain("--auth clerk");

// None auth
const noneResult = await init("auth-app-none", {
  yes: true,
  auth: "none",
  database: "sqlite",
  orm: "drizzle",
  install: false,
  git: false,
});
expect(noneResult.success).toBe(true);
await assertBtsConfig(noneResult.projectDirectory, { database: "sqlite", orm: "drizzle" });
expect(noneResult.projectConfig.auth).toBe("none");
expect(noneResult.reproducibleCommand).toContain("--auth none");

apps/cli/test/programmatic-api.test.ts (lines 316–329): please add these tests and the reproducibleCommand assertions to complete coverage for all auth enum values.

apps/cli/templates/api/trpc/native/utils/trpc.ts.hbs (2)

1-3: Add conditional import for Clerk in native TRPC utils

In apps/cli/templates/api/trpc/native/utils/trpc.ts.hbs, we currently only import authClient when auth === "better-auth":

{{#if (eq auth "better-auth")}}
import { authClient } from "@/lib/auth-client";
{{/if}}

To mirror the new auth enum (which also includes "clerk") and keep native TRPC in line with ORPC support, add a conditional import for Clerk (or a shared helper) as well:

 {{#if (eq auth "better-auth")}}
 import { authClient } from "@/lib/auth-client";
 {{/if}}
+{{#if (eq auth "clerk")}}
+import { clerkClient } from "@/lib/clerk-client";
+{{/if}}

Points to check:

  • Ensure @/lib/clerk-client exists (or adjust the path to your Clerk helper).
  • If you prefer a shared auth helper, import it here instead of the raw client.

15-24: Add async Clerk header branch in httpBatchLink

httpBatchLink’s headers option accepts a function that can return a Promise of headers, allowing fresh tokens to be fetched per request (trpc.io)

In apps/cli/templates/api/trpc/native/utils/trpc.ts.hbs, update the httpBatchLink options to include an async branch for Clerk:

       httpBatchLink({
         url: `${process.env.EXPO_PUBLIC_SERVER_URL}/trpc`,
         {{#if (eq auth "better-auth")}}
         headers() {
           const headers = new Map<string, string>();
           const cookies = authClient.getCookie();
           if (cookies) {
             headers.set("Cookie", cookies);
           }
           return Object.fromEntries(headers);
         },
         {{/if}}
+        {{#if (eq auth "clerk")}}
+        async headers() {
+          const token = await getClerkToken?.();
+          return token ? { Authorization: `Bearer ${token}` } : {};
+        },
+        {{/if}}
       }),

• Don’t forget to import your Clerk helper, e.g.
import { getClerkToken } from "@/lib/clerk-client";

This ensures each request carries a fresh Bearer token when auth === "clerk".

apps/cli/templates/api/orpc/server/next/src/app/rpc/[...all]/route.ts.hbs (1)

1-3: Prefer always calling createContext for consistent ctx shape (drop template branching).

Keeps ctx predictable across auth modes and aligns better with other backends.

-{{#if (eq auth "better-auth")}}
-import { createContext } from '@/lib/context'
-{{/if}}
+import { createContext } from '@/lib/context'
@@
-    context: {{#if (eq auth "better-auth")}}await createContext(req){{else}}{}{{/if}},
+    context: await createContext(req),

Also applies to: 13-13

apps/cli/templates/frontend/react/next/src/app/layout.tsx.hbs (1)

33-45: Avoid relying on the and helper; use nested ifs for portability.

Reduces coupling to custom helpers and mirrors import-guard style above.

-{{#if (and (eq auth "clerk") (eq backend "convex"))}}<ClerkProvider>
-  <Providers>
-    <div className="grid grid-rows-[auto_1fr] h-svh">
-      <Header />
-      {children}
-    </div>
-  </Providers>
-</ClerkProvider>{{else}}<Providers>
-  <div className="grid grid-rows-[auto_1fr] h-svh">
-    <Header />
-    {children}
-  </div>
-</Providers>{{/if}}
+{{#if (eq auth "clerk")}}
+  {{#if (eq backend "convex")}}
+    <ClerkProvider>
+      <Providers>
+        <div className="grid grid-rows-[auto_1fr] h-svh">
+          <Header />
+          {children}
+        </div>
+      </Providers>
+    </ClerkProvider>
+  {{else}}
+    <Providers>
+      <div className="grid grid-rows-[auto_1fr] h-svh">
+        <Header />
+        {children}
+      </div>
+    </Providers>
+  {{/if}}
+{{else}}
+  <Providers>
+    <div className="grid grid-rows-[auto_1fr] h-svh">
+      <Header />
+      {children}
+    </div>
+  </Providers>
+{{/if}}
apps/cli/templates/api/orpc/server/base/src/lib/context.ts.hbs (1)

8-17: Unify no-auth context shape with other backends (return { session: null }).

ORPC Next returns {} while others return { session: null } — align for consistency.

 {{else}}
-  return {}
+  return {
+    session: null,
+  }
 {{/if}}
apps/cli/templates/backend/server/express/src/index.ts.hbs (1)

57-61: Keep ORPC ctx shape consistent when auth != better-auth.

Other ORPC contexts return { session: null } in no-auth mode.

-    context: {},
+    context: { session: null },
apps/cli/src/utils/config-validation.ts (1)

69-80: Consolidate and harden “auth requires database” rule; avoid undefined-auth false positives

  • The two checks are redundant, and cfg.auth !== "none" will treat undefined as requiring a DB in programmatic paths.
  • Keep a single unconditional check and gate on truthy cfg.auth.

Apply:

-	// For Convex backend, Clerk and "none" auth are allowed without database
-	if (
-		has("auth") &&
-		has("database") &&
-		cfg.auth !== "none" &&
-		db === "none" &&
-		cfg.backend !== "convex"
-	) {
-		exitWithError(
-			"Authentication requires a database. Please choose a database or set '--auth none'.",
-		);
-	}
+	// For non-Convex backends, any non-"none" auth requires a database
-if (cfg.auth !== "none" && db === "none" && cfg.backend !== "convex") {
+if (cfg.auth && cfg.auth !== "none" && db === "none" && cfg.backend !== "convex") {
 	exitWithError(
 		"Authentication requires a database. Please choose a database or set '--auth none'.",
 	);
}

Also applies to: 82-86

apps/cli/templates/backend/server/server-base/src/routers/index.ts.hbs (1)

2-2: Minor: session is guaranteed by middleware; drop optional chaining

protectedProcedure ensures session exists; prefer consistent non-optional access.

-      user: context.session?.user,
+      user: context.session.user,

Also applies to: 12-19

apps/cli/src/prompts/auth.ts (1)

25-25: Type explicitness nit

Return a typed literal for clarity.

-  if (!hasDatabase) return "none";
+  if (!hasDatabase) return "none" as Auth;
apps/cli/test/cli.smoke.test.ts (2)

506-547: Add positive test for Convex + Clerk

We only assert auth: "none" on Convex. Add a case to scaffold with --auth clerk and assert bts.jsonc contains auth: "clerk".

Example insert near this block:

it("scaffolds convex with Clerk auth", async () => {
  const projectName = "app-convex-clerk";
  await runCli(
    [
      projectName,
      "--yes",
      "--frontend", "tanstack-router",
      "--backend", "convex",
      "--auth", "clerk",
      "--db-setup", "none",
      "--addons", "none",
      "--package-manager", "bun",
      "--no-install",
      "--no-git",
    ],
    workdir,
  );
  const projectDir = join(workdir, projectName);
  await assertScaffoldedProject(projectDir);
  await assertBtsConfig(projectDir, {
    backend: "convex",
    auth: "clerk",
  });
});

1462-1633: Add negative tests for new auth constraints

  • Reject --auth clerk with non-Convex backends.
  • Reject --auth better-auth with --backend convex.

Suggested cases:

it("rejects clerk with non-convex backend", async () => {
  await runCliExpectingError(
    [
      "invalid-clerk-nonconvex",
      "--yes",
      "--frontend", "tanstack-router",
      "--backend", "hono",
      "--runtime", "bun",
      "--database", "none",
      "--orm", "none",
      "--api", "none",
      "--auth", "clerk",
      "--addons", "none",
      "--db-setup", "none",
      "--examples", "none",
      "--package-manager", "bun",
      "--no-install",
      "--no-git",
    ],
    workdir,
  );
});

it("rejects better-auth with convex backend", async () => {
  await runCliExpectingError(
    [
      "invalid-betterauth-convex",
      "--yes",
      "--frontend", "tanstack-router",
      "--backend", "convex",
      "--auth", "better-auth",
      "--db-setup", "none",
      "--addons", "none",
      "--package-manager", "bun",
      "--no-install",
      "--no-git",
    ],
    workdir,
  );
});
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1ac5946 and 292b8d1.

📒 Files selected for processing (40)
  • apps/cli/src/constants.ts (2 hunks)
  • apps/cli/src/helpers/core/auth-setup.ts (3 hunks)
  • apps/cli/src/helpers/core/create-project.ts (3 hunks)
  • apps/cli/src/helpers/core/env-setup.ts (2 hunks)
  • apps/cli/src/helpers/core/template-manager.ts (6 hunks)
  • apps/cli/src/prompts/auth.ts (1 hunks)
  • apps/cli/src/utils/compatibility-rules.ts (4 hunks)
  • apps/cli/src/utils/config-validation.ts (2 hunks)
  • apps/cli/src/utils/display-config.ts (1 hunks)
  • apps/cli/templates/addons/ruler/.ruler/bts.md.hbs (2 hunks)
  • apps/cli/templates/api/orpc/native/utils/orpc.ts.hbs (2 hunks)
  • apps/cli/templates/api/orpc/server/base/src/lib/context.ts.hbs (7 hunks)
  • apps/cli/templates/api/orpc/server/base/src/lib/orpc.ts.hbs (1 hunks)
  • apps/cli/templates/api/orpc/server/next/src/app/rpc/[...all]/route.ts.hbs (2 hunks)
  • apps/cli/templates/api/orpc/web/nuxt/app/plugins/orpc.ts.hbs (1 hunks)
  • apps/cli/templates/api/orpc/web/react/base/src/utils/orpc.ts.hbs (1 hunks)
  • apps/cli/templates/api/orpc/web/solid/src/utils/orpc.ts.hbs (1 hunks)
  • apps/cli/templates/api/orpc/web/svelte/src/lib/orpc.ts.hbs (1 hunks)
  • apps/cli/templates/api/trpc/native/utils/trpc.ts.hbs (2 hunks)
  • apps/cli/templates/api/trpc/server/base/src/lib/context.ts.hbs (7 hunks)
  • apps/cli/templates/api/trpc/server/base/src/lib/trpc.ts.hbs (1 hunks)
  • apps/cli/templates/api/trpc/web/react/base/src/utils/trpc.ts.hbs (2 hunks)
  • apps/cli/templates/auth/clerk/convex/backend/convex/auth.config.ts.hbs (1 hunks)
  • apps/cli/templates/auth/clerk/convex/backend/convex/privateData.ts.hbs (1 hunks)
  • apps/cli/templates/backend/convex/packages/backend/package.json.hbs (1 hunks)
  • apps/cli/templates/backend/server/elysia/src/index.ts.hbs (2 hunks)
  • apps/cli/templates/backend/server/express/src/index.ts.hbs (5 hunks)
  • apps/cli/templates/backend/server/fastify/src/index.ts.hbs (4 hunks)
  • apps/cli/templates/backend/server/hono/src/index.ts.hbs (3 hunks)
  • apps/cli/templates/backend/server/server-base/src/routers/index.ts.hbs (4 hunks)
  • apps/cli/templates/deploy/alchemy/alchemy.run.ts.hbs (2 hunks)
  • apps/cli/templates/frontend/nuxt/app/components/Header.vue.hbs (2 hunks)
  • apps/cli/templates/frontend/react/next/src/app/layout.tsx.hbs (2 hunks)
  • apps/cli/templates/frontend/react/tanstack-start/src/router.tsx.hbs (1 hunks)
  • apps/cli/templates/frontend/react/web-base/src/components/header.tsx.hbs (2 hunks)
  • apps/cli/templates/frontend/solid/src/components/header.tsx.hbs (2 hunks)
  • apps/cli/templates/frontend/svelte/src/components/Header.svelte.hbs (2 hunks)
  • apps/cli/test/cli.smoke.test.ts (61 hunks)
  • apps/cli/test/programmatic-api.test.ts (3 hunks)
  • apps/web/src/app/(home)/_components/stack-builder.tsx (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/cli/src/utils/display-config.ts
  • apps/cli/src/constants.ts
  • apps/cli/src/utils/compatibility-rules.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/convex_rules.mdc)

**/*.{ts,tsx}: Use Id from './_generated/dataModel' to type document ids (e.g., Id<'users'>)
Ensure Record key/value types align with validators (e.g., v.record(v.id('users'), v.string()) => Record<Id<'users'>, string>)
Be strict with types for document ids; prefer Id<'table'> over string
Use 'as const' for string literals in discriminated unions
When using Array and Record types, declare with explicit generic types (e.g., const arr: Array = ...)

Files:

  • apps/cli/src/utils/config-validation.ts
  • apps/cli/src/helpers/core/template-manager.ts
  • apps/cli/src/helpers/core/env-setup.ts
  • apps/cli/src/helpers/core/create-project.ts
  • apps/web/src/app/(home)/_components/stack-builder.tsx
  • apps/cli/src/helpers/core/auth-setup.ts
  • apps/cli/src/prompts/auth.ts
  • apps/cli/test/programmatic-api.test.ts
  • apps/cli/test/cli.smoke.test.ts
**/*.{js,jsx,ts,tsx,mjs,cjs}

📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)

**/*.{js,jsx,ts,tsx,mjs,cjs}: Do not use dotenv; Bun auto-loads .env
Use Bun.serve() for HTTP/WebSockets; do not use express
Use bun:sqlite for SQLite; do not use better-sqlite3
Use Bun.redis for Redis; do not use ioredis
Use Bun.sql for Postgres; do not use pg or postgres.js
Use built-in WebSocket; do not use ws
Prefer Bun.file over node:fs readFile/writeFile
Use Bun.$ instead of execa for shelling out

Files:

  • apps/cli/src/utils/config-validation.ts
  • apps/cli/src/helpers/core/template-manager.ts
  • apps/cli/src/helpers/core/env-setup.ts
  • apps/cli/src/helpers/core/create-project.ts
  • apps/web/src/app/(home)/_components/stack-builder.tsx
  • apps/cli/src/helpers/core/auth-setup.ts
  • apps/cli/src/prompts/auth.ts
  • apps/cli/test/programmatic-api.test.ts
  • apps/cli/test/cli.smoke.test.ts
🧠 Learnings (5)
📚 Learning: 2025-08-24T18:01:11.544Z
Learnt from: CR
PR: AmanVarshney01/create-better-t-stack#0
File: .cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc:0-0
Timestamp: 2025-08-24T18:01:11.544Z
Learning: Applies to {**/package.json,**/webpack.config.@(js|ts|mjs|cjs),**/esbuild.config.@(js|ts|mjs|cjs)} : Use `bun build <file>` instead of `webpack` or `esbuild`

Applied to files:

  • apps/cli/templates/addons/ruler/.ruler/bts.md.hbs
📚 Learning: 2025-08-24T18:00:39.152Z
Learnt from: CR
PR: AmanVarshney01/create-better-t-stack#0
File: .cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-08-24T18:00:39.152Z
Learning: Applies to package.json : Add types/node to package.json when using Node.js built-in modules

Applied to files:

  • apps/cli/templates/backend/convex/packages/backend/package.json.hbs
📚 Learning: 2025-08-24T18:00:39.152Z
Learnt from: CR
PR: AmanVarshney01/create-better-t-stack#0
File: .cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-08-24T18:00:39.152Z
Learning: Applies to convex/**/*.ts : Always use the new Convex function syntax (query/mutation/action/internal*) with args/returns/handler

Applied to files:

  • apps/cli/templates/auth/clerk/convex/backend/convex/privateData.ts.hbs
📚 Learning: 2025-08-24T18:00:39.152Z
Learnt from: CR
PR: AmanVarshney01/create-better-t-stack#0
File: .cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-08-24T18:00:39.152Z
Learning: Applies to convex/**/*.ts : Use query/mutation/action for public API; use internalQuery/internalMutation/internalAction for private functions; do not register via api/internal objects

Applied to files:

  • apps/cli/templates/auth/clerk/convex/backend/convex/privateData.ts.hbs
📚 Learning: 2025-08-24T18:00:39.152Z
Learnt from: CR
PR: AmanVarshney01/create-better-t-stack#0
File: .cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-08-24T18:00:39.152Z
Learning: Applies to convex/schema.ts : Always define the Convex schema in convex/schema.ts and import schema helpers from convex/server

Applied to files:

  • apps/cli/templates/auth/clerk/convex/backend/convex/privateData.ts.hbs
🧬 Code graph analysis (4)
apps/cli/src/utils/config-validation.ts (1)
apps/cli/src/utils/errors.ts (1)
  • exitWithError (9-15)
apps/cli/src/helpers/core/template-manager.ts (1)
apps/cli/src/constants.ts (1)
  • PKG_ROOT (8-8)
apps/cli/src/helpers/core/auth-setup.ts (1)
apps/cli/src/utils/add-package-deps.ts (1)
  • addPackageDependency (6-43)
apps/cli/src/prompts/auth.ts (3)
apps/cli/src/types.ts (2)
  • Auth (86-86)
  • Backend (16-16)
apps/cli/src/utils/errors.ts (1)
  • exitCancelled (17-23)
apps/cli/src/constants.ts (1)
  • DEFAULT_CONFIG (40-40)
🔇 Additional comments (39)
apps/cli/templates/deploy/alchemy/alchemy.run.ts.hbs (3)

167-170: Good call: explicit gating on "better-auth".

Switching from truthy check to eq auth "better-auth" is safer and aligns with the new enum-based auth.


193-193: LGTM: finalize after bindings.

await app.finalize(); placement looks correct.


55-61: Bind Clerk Publishable Key in Template Bindings
The NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY (and its framework-specific variants) is already wired up in env-setup.ts, so these names are correct. To enable injecting your Clerk publishable key into each generated app, add this conditional inside every framework’s bindings block in
apps/cli/templates/deploy/alchemy/alchemy.run.ts.hbs:

   bindings: {
     {{#if (eq backend "convex")}}
       …URL bindings…
     {{/if}}
+    {{#if (eq auth "clerk")}}
+      <PREFIX>_CLERK_PUBLISHABLE_KEY: process.env.<PREFIX>_CLERK_PUBLISHABLE_KEY || "",
+    {{/if}}
   },

Replace <PREFIX> per framework:

  • NEXT_PUBLIC (Next.js)
  • NUXT_PUBLIC (Nuxt)
  • PUBLIC (SvelteKit)
  • VITE (TanStack Start, TanStack Router, React Router, Solid)
apps/cli/templates/frontend/svelte/src/components/Header.svelte.hbs (1)

34-36: Confirm Clerk integration support in the Svelte template

Our repository search did not surface any Clerk-related code—no ClerkProvider, SignedIn/SignedOut, or UserButton were found in the Svelte scaffolding under apps/cli/templates/frontend/svelte—which suggests Clerk isn’t wired up in this template by default. Please verify whether Clerk-based auth should be supported here before merging.

• Directory to check:

  • apps/cli/templates/frontend/svelte/src/components/Header.svelte.hbs (around lines 34–36)
    • Current snippet:
{{#if (eq auth "better-auth")}}
  <UserMenu />
{{/if}}

• If Clerk-based auth is required, you’ll need to:

  1. Wrap your app (e.g. in src/main.js or root layout) with <ClerkProvider> and pass the necessary config.
  2. Update the header snippet to include a minimal user button when auth === "clerk":
    {{#if (eq auth "better-auth")}}
      <UserMenu />
    {{/if}}
    + {{#if (eq auth "clerk")}}
    +   <SignedIn><UserButton /></SignedIn>
    + {{/if}}
  3. Optionally provide a SignedOut link elsewhere for sign-in.

Because there’s no existing Clerk scaffolding here, please confirm whether this is intentional (and skip these changes) or—if Clerk support is desired—add the provider setup and the header update as sketched above.

apps/cli/templates/frontend/react/web-base/src/components/header.tsx.hbs (1)

19-21: Dashboard route & auth guard confirmed for Clerk

The Clerk template for the React/Next.js frontend includes a /dashboard page and properly restricts its content based on authentication status:

  • File: apps/cli/templates/auth/clerk/convex/web/react/next/src/app/dashboard/page.tsx.hbs
    • Defines the Dashboard component under /app/dashboard
    • Wraps dashboard content in <Authenticated> and shows a <SignInButton> under <Unauthenticated>, ensuring unauthenticated users cannot see private data or UI.

No further changes are needed here.

apps/web/src/app/(home)/_components/stack-builder.tsx (3)

160-162: Light-mode icon swap for Clerk looks good.

Extends existing pattern; no issues.


262-268: LGTM: ‘backend: none’ forces auth to ‘none’.

Matches the enum-based auth model and prevents invalid combos.


1530-1536: LGTM: Boolean toggle behavior limited to git/install.

Auth is no longer treated as a boolean. Correct for enum-based auth.

apps/cli/src/helpers/core/auth-setup.ts (6)

10-12: Guard for "none"/falsy auth is correct.

Early-return now matches the new enum semantics and avoids unnecessary work.


34-39: Server better-auth install gating looks good.


54-60: Web better-auth install gating is correct.

No installs when auth !== "better-auth" prevents accidental coupling.


67-78: ✅ Verified dependencyVersionMap entries

Both “better-auth” and “@better-auth/expo” are present in apps/cli/src/constants.ts with versions (“^1.3.7”), so the added package dependencies will resolve correctly. No further changes needed.


26-31: No action needed – the version map already includes “@clerk/nextjs”.

  • In apps/cli/src/constants.ts (line 46), you can see:
    "@clerk/nextjs": "^6.31.5",
  • Since dependencyVersionMap already contains this entry, there’s no risk of “not found in version map” warnings.

23-33: No action needed for non-Next frameworks in Convex+Clerk path

The Convex + Clerk flow under apps/cli/templates/auth/clerk/convex/web/react currently only provides a Next.js template (next), so there are no other React frameworks (e.g. React Router or TanStack Router) in this path. The early return after installing only @clerk/nextjs is therefore correct and there is no need to install @clerk/clerk-react for frameworks that aren’t present.

Likely an incorrect or invalid review comment.

apps/cli/src/helpers/core/env-setup.ts (1)

4-4: Import path tweak is fine.

apps/cli/src/helpers/core/template-manager.ts (4)

365-366: Auth early-return updated to include "none" — good.


473-526: Server-side provider templates (non-Convex) selection is clean.


589-626: Native provider templates selection is good.

Base + framework-specific layering is clear.


387-429: Convex + Clerk templating flow verified for Next.js; review remaining framework templates and Clerk deps

• apps/cli/templates/auth/clerk/convex/backend directory is present and will be copied as expected.
• apps/cli/templates/auth/clerk/convex/web/react/next exists, and page.tsx.hbs imports { SignInButton, UserButton } from @clerk/nextjs, confirming templates include Clerk dependencies.
• No other framework subdirectories were found under templates/auth/clerk/convex/web/react (i.e. tanstack-router, react-router, tanstack-start); if those frameworks should be supported, add corresponding template folders or guard against selecting unsupported ones.
• Ensure that the project generator also installs the required @clerk/* packages (e.g. @clerk/nextjs or @clerk/clerk-react) when scaffolding a Clerk-enabled app.

apps/cli/src/helpers/core/create-project.ts (2)

8-8: Updated import path for setupAuth is fine.


50-51: Always running setupAuthTemplate is fine given the new internal guard.

Template manager now no-ops for auth === "none".

apps/cli/templates/addons/ruler/.ruler/bts.md.hbs (1)

132-132: Nit: trailing formatting-only change.

No action needed.

apps/cli/templates/backend/server/fastify/src/index.ts.hbs (1)

152-152: Nit: formatting-only change.

No action needed.

apps/cli/templates/backend/server/hono/src/index.ts.hbs (3)

17-19: Scoped auth import looks good

Importing auth only for better-auth is correct.


52-54: Auth route registration OK

Route is correctly gated to better-auth.


136-136: No action needed on template block closure

Change is mechanical.

apps/cli/templates/backend/server/elysia/src/index.ts.hbs (1)

17-19: Scoped auth import looks good

Matches better-auth only.

apps/cli/test/programmatic-api.test.ts (1)

268-275: Good update: string-based auth in negative path is correct

Switching to auth: "better-auth" aligns with the new enum and the error expectation remains valid.

apps/cli/templates/api/orpc/native/utils/orpc.ts.hbs (1)

20-29: Verify existence of a Clerk token helper before adding the clerk branch

I ran a search for any getClerkToken (or similar Clerk token helper) in your apps/cli/templates directory and found nothing. Before merging in the suggested diff, please confirm that:

  • A utility function like getClerkToken() is implemented (e.g. in your scaffolded Clerk client).
  • It’s exported and available in the context where this Handlebars template is rendered.

Affected location:

  • File: apps/cli/templates/api/orpc/native/utils/orpc.ts.hbs
    Lines 20–29 (the existing better-auth branch)

Suggested update (apply once the Clerk helper is in place):

   {{#if (eq auth "better-auth")}}
   headers() {
     const headers = new Map<string, string>();
     const cookies = authClient.getCookie();
     if (cookies) {
       headers.set("Cookie", cookies);
     }
     return Object.fromEntries(headers);
   },
-  {{/if}}
+  {{else}}
+  {{#if (eq auth "clerk")}}
+  async headers() {
+    // Ensure getClerkToken() is implemented and imported in your scaffolded util
+    const token = await getClerkToken?.();
+    return token ? { Authorization: `Bearer ${token}` } : {};
+  },
+  {{/if}}
+  {{/if}}

Please verify or add the getClerkToken helper (and any necessary imports) before applying this change.

apps/cli/templates/api/orpc/web/solid/src/utils/orpc.ts.hbs (1)

17-24: Add Clerk auth conditional branch in ORPC utils

We currently only handle better-auth (cookies). To support Clerk you’ll need to attach a bearer token instead of relying on credentials: "include". However, there’s no getClerkToken (or equivalent) helper in the web-Solid templates—please verify or implement one before adding this branch.

• File: apps/cli/templates/api/orpc/web/solid/src/utils/orpc.ts.hbs (around lines 17–24)
• Confirm you have a token-retrieval helper for SolidJS (e.g. from @clerk/clerk-react or a custom SDK client) in scope

Suggested diff:

   {{#if (eq auth "better-auth")}}
     fetch(url, options) {
       return fetch(url, {
         ...options,
         credentials: "include",
       });
     },
-  {{/if}}
+  {{else if (eq auth "clerk")}}
+  async fetch(url, options) {
+    // Ensure getClerkToken is defined/imported in this template
+    const token = await getClerkToken?.();
+    return fetch(url, {
+      ...options,
+      headers: {
+        ...(options?.headers ?? {}),
+        ...(token ? { Authorization: `Bearer ${token}` } : {}),
+      },
+      credentials: "omit",
+    });
+  },
+  {{/if}}

Please verify the availability (or add) the Clerk token helper and ensure this branch is wired up correctly.

apps/cli/templates/api/orpc/server/next/src/app/rpc/[...all]/route.ts.hbs (1)

1-1: eq helper registration confirmed
The eq helper is registered in the template processor, so the Handlebars helper is available at generation time.

• Registration found at apps/cli/src/utils/template-processor.ts:31:

handlebars.registerHelper("eq", (a, b) => a === b);
apps/cli/templates/frontend/react/next/src/app/layout.tsx.hbs (2)

4-5: LGTM: Conditional import of ClerkProvider only for clerk+convex.

Matches the PR scope; avoids unused imports otherwise.


33-41: No double-wrapping detected – Providers doesn’t include ClerkProvider

Verified that apps/cli/templates/frontend/react/next/src/components/providers.tsx.hbs only imports useAuth and renders ConvexProviderWithClerk when auth="clerk" && backend="convex", with no present. You can safely leave the layout’s wrapper in place.

apps/cli/templates/api/orpc/server/base/src/lib/context.ts.hbs (1)

73-86: Good use of fromNodeHeaders for Node adapters.

Header normalization is correct for Express.

apps/cli/templates/backend/server/express/src/index.ts.hbs (2)

20-23: LGTM: better-auth wiring via toNodeHandler.

Matches better-auth’s Node adapter expectations.


39-39: No change needed: /api/auth{/*path} is valid Express v5 syntax.

The existing route uses the path-to-regexp “optional repeating” group with a named wildcard (*path), which is exactly how Express v5 requires catch-all parameters:

  • Express v5 enforces named wildcards (either /*name or /{*name}); unnamed * alone will throw “Missing parameter name” (github.com)
  • For optional, repeating wildcards, path-to-regexp uses curly-brace grouping—e.g. /files{/*path}—and /api/auth{/*path} follows that model (github.com, npmjs.com)
  • Changing to /api/auth/* would both omit the required name and lose the optional-segment semantics (failing to match /api/auth), so it would break under Express v5 (github.com)

Please disregard the proposed diff; the original pattern is correct.

Likely an incorrect or invalid review comment.

apps/cli/templates/api/trpc/server/base/src/lib/context.ts.hbs (1)

8-21: LGTM: Consistent { session: null } fallback across TRPC backends.

Clear, predictable context in no-auth mode.

apps/cli/templates/api/orpc/server/base/src/lib/orpc.ts.hbs (1)

8-21: Gating protectedProcedure on auth === "better-auth" is correct

Matches the template strategy elsewhere; no issues spotted.

apps/cli/templates/backend/server/server-base/src/routers/index.ts.hbs (1)

28-31: tRPC branch gating looks good

Import/route are correctly conditional on auth === "better-auth".

Also applies to: 39-46

Comment on lines +188 to +193
if (config.auth === "clerk" && backend !== "convex") {
exitWithError(
"Clerk authentication is only supported with the Convex backend. Please use '--backend convex' or choose a different auth provider.",
);
}

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.

⚠️ Potential issue

Block “better-auth” with Convex; only Clerk|None should be allowed

Currently, better-auth slips through when backend === "convex". Enforce the constraint alongside the Clerk-only rule.

Apply:

  if (config.auth === "clerk" && backend !== "convex") {
    exitWithError(
      "Clerk authentication is only supported with the Convex backend. Please use '--backend convex' or choose a different auth provider.",
    );
  }
+
+  if (
+    backend === "convex" &&
+    config.auth &&
+    config.auth !== "clerk" &&
+    config.auth !== "none"
+  ) {
+    exitWithError(
+      "For '--backend convex', only '--auth clerk' or '--auth none' are supported.",
+    );
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (config.auth === "clerk" && backend !== "convex") {
exitWithError(
"Clerk authentication is only supported with the Convex backend. Please use '--backend convex' or choose a different auth provider.",
);
}
if (config.auth === "clerk" && backend !== "convex") {
exitWithError(
"Clerk authentication is only supported with the Convex backend. Please use '--backend convex' or choose a different auth provider.",
);
}
if (
backend === "convex" &&
config.auth &&
config.auth !== "clerk" &&
config.auth !== "none"
) {
exitWithError(
"For '--backend convex', only '--auth clerk' or '--auth none' are supported.",
);
}
🤖 Prompt for AI Agents
In apps/cli/src/utils/config-validation.ts around lines 188-193, the current
check only blocks Clerk when backend !== "convex" but allows "better-auth" to
slip through for Convex; update the validation so that when backend === "convex"
the auth value must be either "clerk" or "none". Replace or augment the existing
conditional with a single check that if backend === "convex" and config.auth is
not "clerk" and not "none", call exitWithError with a message telling the user
that Convex only supports Clerk or no auth (suggest using '--backend convex'
with '--auth clerk' or choose a different backend/auth), ensuring both the
Clerk-only rule and blocking "better-auth" are enforced.

Comment on lines +6 to 8
{{#if (eq auth "better-auth")}}
import { authClient } from "@/lib/auth-client";
{{/if}}

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.

💡 Verification agent

🧩 Analysis chain

Gate for "clerk" as well (import), or centralize via a generic auth header helper

Right now only "better-auth" is handled. If CLI supports auth: "clerk" for native, import the appropriate helper when auth === "clerk", or unify via a single getAuthHeaders() helper across auth providers.


🏁 Script executed:

#!/bin/bash
# Verify whether any native template handles clerk
rg -n 'eq auth "clerk"' apps/cli/templates | sed -n '1,120p'

Length of output: 829


Support auth: "clerk" in native ORPC utils

In apps/cli/templates/api/orpc/native/utils/orpc.ts.hbs (lines 6–8), we currently only gate on "better-auth":

{{#if (eq auth "better-auth")}}
import { authClient } from "@/lib/auth-client";
{{/if}}

Since the CLI also supports auth: "clerk" elsewhere, the native RPC helper should import the Clerk client when auth === "clerk". You can either:

• Add a second import block:

{{#if (eq auth "clerk")}}
import { clerkClient } from "@/lib/clerk-client";
{{/if}}

• Or consolidate both under a shared helper, e.g.:

import { getAuthHeaders } from "@/lib/auth-headers";

…and then in your generated code use:

const headers = await getAuthHeaders(auth);

This ensures the native client can attach the correct auth headers for Clerk as well as Better Auth.

Comment on lines +1 to +12
export default {
providers: [
{
// Replace with your own Clerk Issuer URL from your "convex" JWT template
// or with `process.env.CLERK_JWT_ISSUER_DOMAIN`
// and configure CLERK_JWT_ISSUER_DOMAIN on the Convex Dashboard
// See https://docs.convex.dev/auth/clerk#configuring-dev-and-prod-instances
domain: process.env.CLERK_JWT_ISSUER_DOMAIN,
applicationID: "convex",
},
],
};

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.

⚠️ Potential issue

Guard missing env var and add type safety to prevent misconfig at runtime

process.env.CLERK_JWT_ISSUER_DOMAIN can be undefined, which may break auth at runtime and fail TS checks (domain expects a string). Add a guard and validate the config with Convex types.

+import type { AuthConfig } from "convex/server";
+
+const domain = process.env.CLERK_JWT_ISSUER_DOMAIN;
+if (!domain) {
+  throw new Error(
+    'Missing CLERK_JWT_ISSUER_DOMAIN. Set it in the Convex Dashboard (Dev/Prod).'
+  );
+}
+
-export default {
+export default {
   providers: [
     {
-      // Replace with your own Clerk Issuer URL from your "convex" JWT template
-      // or with `process.env.CLERK_JWT_ISSUER_DOMAIN`
-      // and configure CLERK_JWT_ISSUER_DOMAIN on the Convex Dashboard
-      // See https://docs.convex.dev/auth/clerk#configuring-dev-and-prod-instances
-      domain: process.env.CLERK_JWT_ISSUER_DOMAIN,
+      // Replace with your own Clerk Issuer URL (domain) from your "convex" JWT template
+      // and configure CLERK_JWT_ISSUER_DOMAIN on the Convex Dashboard.
+      // See https://docs.convex.dev/auth/clerk#configuring-dev-and-prod-instances
+      domain,
       applicationID: "convex",
     },
   ],
-};
+} satisfies AuthConfig;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export default {
providers: [
{
// Replace with your own Clerk Issuer URL from your "convex" JWT template
// or with `process.env.CLERK_JWT_ISSUER_DOMAIN`
// and configure CLERK_JWT_ISSUER_DOMAIN on the Convex Dashboard
// See https://docs.convex.dev/auth/clerk#configuring-dev-and-prod-instances
domain: process.env.CLERK_JWT_ISSUER_DOMAIN,
applicationID: "convex",
},
],
};
import type { AuthConfig } from "convex/server";
const domain = process.env.CLERK_JWT_ISSUER_DOMAIN;
if (!domain) {
throw new Error(
'Missing CLERK_JWT_ISSUER_DOMAIN. Set it in the Convex Dashboard (Dev/Prod).'
);
}
export default {
providers: [
{
// Replace with your own Clerk Issuer URL (domain) from your "convex" JWT template
// and configure CLERK_JWT_ISSUER_DOMAIN on the Convex Dashboard.
// See https://docs.convex.dev/auth/clerk#configuring-dev-and-prod-instances
domain,
applicationID: "convex",
},
],
} satisfies AuthConfig;
🤖 Prompt for AI Agents
In apps/cli/templates/auth/clerk/convex/backend/convex/auth.config.ts.hbs around
lines 1 to 12, process.env.CLERK_JWT_ISSUER_DOMAIN may be undefined and the
exported config lacks Convex typing and runtime validation; update the file to
import and use the Convex AuthConfig type for the exported object, ensure domain
is asserted as a non-empty string (guard against undefined) and throw a clear
error or fail fast if the env var is missing, and include a small runtime
validation step that validates the final config shape against Convex types
before exporting to prevent misconfiguration at runtime.

Comment on lines +34 to 37
{{#if (eq auth "better-auth")}}
allowedHeaders: ["Content-Type", "Authorization"],
credentials: true,
{{/if}}

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.

⚠️ Potential issue

CORS: allow Content-Type always; include Authorization/credentials for Clerk too

Prevents failed preflights and enables Clerk bearer tokens.

Apply:

-      {{#if (eq auth "better-auth")}}
-      allowedHeaders: ["Content-Type", "Authorization"],
-      credentials: true,
-      {{/if}}
+      allowedHeaders: ["Content-Type"{{#if (or (eq auth "better-auth") (eq auth "clerk"))}}, "Authorization"{{/if}}],
+      {{#if (or (eq auth "better-auth") (eq auth "clerk"))}}
+      credentials: true,
+      {{/if}}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{{#if (eq auth "better-auth")}}
allowedHeaders: ["Content-Type", "Authorization"],
credentials: true,
{{/if}}
allowedHeaders: ["Content-Type"{{#if (or (eq auth "better-auth") (eq auth "clerk"))}}, "Authorization"{{/if}}],
{{#if (or (eq auth "better-auth") (eq auth "clerk"))}}
credentials: true,
{{/if}}
🤖 Prompt for AI Agents
In apps/cli/templates/backend/server/elysia/src/index.ts.hbs around lines 34-37,
always include "Content-Type" in CORS allowedHeaders and only add
"Authorization" and credentials: true when auth is "better-auth" (Clerk); update
the template so allowedHeaders always contains "Content-Type" and, inside the
{{#if (eq auth "better-auth")}} block, append "Authorization" to allowedHeaders
and set credentials: true.

Comment on lines +70 to 72
{{#if (eq auth "better-auth")}}
<UserMenu />
{{/if}}

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.

🛠️ Refactor suggestion

Render Clerk’s UserButton/SignInButton when auth="clerk".

Expose a signed-in user menu and a signed-out sign-in CTA for Clerk.

-          {{#if (eq auth "better-auth")}}
-          <UserMenu />
-          {{/if}}
+          {{#if (eq auth "better-auth")}}
+            <UserMenu />
+          {{else if (eq auth "clerk")}}
+            {{#if (includes frontend "next")}}
+              <SignedIn><UserButton /></SignedIn>
+              <SignedOut><SignInButton mode="modal" /></SignedOut>
+            {{else}}
+              <SignedIn><UserButton /></SignedIn>
+              <SignedOut><SignInButton mode="modal" /></SignedOut>
+            {{/if}}
+          {{/if}}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{{#if (eq auth "better-auth")}}
<UserMenu />
{{/if}}
{{#if (eq auth "better-auth")}}
<UserMenu />
{{else if (eq auth "clerk")}}
{{#if (includes frontend "next")}}
<SignedIn><UserButton /></SignedIn>
<SignedOut><SignInButton mode="modal" /></SignedOut>
{{else}}
<SignedIn><UserButton /></SignedIn>
<SignedOut><SignInButton mode="modal" /></SignedOut>
{{/if}}
{{/if}}
🤖 Prompt for AI Agents
In apps/cli/templates/frontend/react/web-base/src/components/header.tsx.hbs
around lines 70 to 72, the template only renders a UserMenu for
auth="better-auth"; update the conditional to handle auth="clerk" by rendering
Clerk's components: show UserButton (or Clerk's signed-in menu component) when
the user is authenticated and render SignInButton (or Clerk's sign-in CTA) when
not authenticated; also add the necessary Clerk component imports and any
required provider/context or prop checks so the correct Clerk components are
available and rendered based on the user's sign-in state.

Comment on lines +2 to 4
{{#if (eq auth "better-auth")}}
import UserMenu from "./user-menu";
{{/if}}

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.

💡 Verification agent

🧩 Analysis chain

User menu import is provider-specific; Clerk path missing.

Import is only emitted for "better-auth", so auth === "clerk" renders no user menu. Either add a Clerk branch here or introduce a provider-agnostic wrapper component (e.g., AuthUserMenu) that the generator swaps per provider.

Run to verify helpers and available templates:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Auth union type:"
rg -nP -C2 "type\s+Auth\s*=\s*'better-auth'\s*\|\s*'clerk'\s*\|\s*'none'" apps/cli/src/types.ts || true

echo -e "\nHandlebars helpers (eq/includes) registration:"
rg -nP -C2 "registerHelper\(['\"](eq|includes)['\"]" apps/cli | true

echo -e "\nCheck for provider-specific user-menu templates/components:"
rg -nP -n -C2 "user-menu(\.|/)" apps/cli/templates | true

Length of output: 564


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Searching for Auth union in entire repo"
rg -nP "type\s+Auth\s*=" -C2 .

echo -e "\nSearching for user-menu references"
rg -n -C2 "user-menu(\.|/)" apps/cli

echo -e "\nFinding header.tsx.hbs file location"
fd header.tsx.hbs apps/cli

echo -e "\nPrinting top 20 lines of the header template file"
FILE_PATH=$(fd header.tsx.hbs apps/cli | head -n1)
if [ -f "$FILE_PATH" ]; then
  sed -n '1,20p' "$FILE_PATH"
else
  echo "File not found: $FILE_PATH"
fi

Length of output: 563


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="apps/cli/templates/frontend/solid/src/components/header.tsx.hbs"

echo "Looking for header template: $FILE"
if [ -f "$FILE" ]; then
  echo "Header template content (lines 1-20):"
  sed -n '1,20p' "$FILE"
else
  echo "File not found: $FILE"
fi

Length of output: 1042


Missing Clerk UserMenu import in header.tsx.hbs

The Solid header template currently only imports and renders a user menu when auth === "better-auth". With auth === "clerk", no user‐menu component is imported or rendered, so Clerk‐authenticated apps won’t display any menu. You’ll need to either:

• Add a Clerk branch alongside the existing BetterAuth check:

{{#if (eq auth "better-auth")}}
import UserMenu from "./user-menu";
{{else if (eq auth "clerk")}}
import ClerkUserMenu from "./clerk-user-menu";
{{/if}}

and similarly render <ClerkUserMenu /> in the JSX.
• Or introduce a provider-agnostic wrapper (e.g. AuthUserMenu) in src/components/auth-user-menu.tsx.hbs and swap its implementation per provider.

Please update:

  • apps/cli/templates/frontend/solid/src/components/header.tsx.hbs – add the clerk import/logic (or switch to a wrapper).
  • If opting for the wrapper approach, create the corresponding auth-user-menu.tsx.hbs implementations for both “better-auth” and “clerk” providers.
🤖 Prompt for AI Agents
In apps/cli/templates/frontend/solid/src/components/header.tsx.hbs around lines
2 to 4, the template only imports UserMenu when auth === "better-auth" which
leaves Clerk apps without a user menu; add logic to import and render a
Clerk-specific menu or use a provider-agnostic wrapper. Option A: add an else-if
branch to import ClerkUserMenu when auth === "clerk" and ensure the JSX renders
<ClerkUserMenu /> where current UserMenu is rendered. Option B (preferred):
create src/components/auth-user-menu.tsx.hbs and implement two provider-specific
versions (one that re-exports UserMenu for better-auth and one that re-exports
ClerkUserMenu for clerk), then replace the conditional imports in header.tsx.hbs
with a single import AuthUserMenu and render <AuthUserMenu />; update templates
accordingly so both providers render a user menu.

Comment on lines +10 to 12
{{#if (eq auth "better-auth")}}
{ to: "/dashboard", label: "Dashboard" },
{{/if}}

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.

⚠️ Potential issue

Dashboard link hidden for Clerk; gate by “has auth” rather than provider-specific.

Showing Dashboard only for auth === "better-auth" hides it when auth === "clerk". Prefer gating for any auth that isn’t "none".

Apply:

-    {{#if (eq auth "better-auth")}}
-    { to: "/dashboard", label: "Dashboard" },
-    {{/if}}
+    {{#unless (eq auth "none")}}
+    { to: "/dashboard", label: "Dashboard" },
+    {{/unless}}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{{#if (eq auth "better-auth")}}
{ to: "/dashboard", label: "Dashboard" },
{{/if}}
{{#unless (eq auth "none")}}
{ to: "/dashboard", label: "Dashboard" },
{{/unless}}
🤖 Prompt for AI Agents
In apps/cli/templates/frontend/solid/src/components/header.tsx.hbs around lines
10-12, the Dashboard link is currently shown only when auth === "better-auth";
change the conditional to show the Dashboard for any configured auth provider
except "none" (i.e., gate by auth !== "none" or use a negated helper/unless
helper) so Clerk and other providers also see the Dashboard; update the
Handlebars conditional accordingly and ensure the template logic remains valid
for projects with no auth.

Comment on lines +3 to 5
{{#if (eq auth "better-auth")}}
import UserMenu from './UserMenu.svelte';
{{/if}}

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.

💡 Verification agent

🧩 Analysis chain

Add Clerk import when auth === "clerk"

Right now, Clerk setups won’t import any auth UI. Add a conditional Clerk import alongside the existing better-auth import.

 {{#if (eq auth "better-auth")}}
 import UserMenu from './UserMenu.svelte';
 {{/if}}
+{{#if (eq auth "clerk")}}
+import { SignedIn, UserButton } from '@clerk/sveltekit';
+{{/if}}

To verify deps are present in the Svelte template:


🏁 Script executed:

#!/bin/bash
# Expect at least one package.json.hbs to include @clerk/sveltekit
rg -n '@clerk/sveltekit' apps/cli/templates/frontend/svelte -g '**/package.json.hbs' -C2

Length of output: 88


I’ll search all Svelte template package.json.hbs files to confirm whether @clerk/sveltekit is already declared:


🏁 Script executed:

#!/bin/bash
# Locate every package.json.hbs under the Svelte templates and grep for @clerk/sveltekit
find apps/cli/templates/frontend/svelte -type f -name 'package.json.hbs' -print -exec grep -Hn '@clerk/sveltekit' {} +

Length of output: 170


Add Clerk UI import and include its dependency in the Svelte template

The Svelte header currently only imports UserMenu when auth === "better-auth", and there is no @clerk/sveltekit dependency in the template’s package.json.hbs. Without adding the package, the proposed import will break. Please update both the component and the template’s dependencies.

• apps/cli/templates/frontend/svelte/src/components/Header.svelte.hbs

 {{#if (eq auth "better-auth")}}
 import UserMenu from './UserMenu.svelte';
 {{/if}}
+{{#if (eq auth "clerk")}}
+import { SignedIn, UserButton } from '@clerk/sveltekit';
+{{/if}}

• apps/cli/templates/frontend/svelte/package.json.hbs

 {
   "dependencies": {
     "svelte": "{{svelteVersion}}",
     // … other deps …
+    {{#if (eq auth "clerk")}}
+    "@clerk/sveltekit": "^<latest-version>",
+    {{/if}}
     // … other deps …
   }
 }

– Replace <latest-version> with the desired Clerk package version.
– Verify that the Handlebars context provides auth to package.json.hbs and that ^<latest-version> matches your project’s release policy.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{{#if (eq auth "better-auth")}}
import UserMenu from './UserMenu.svelte';
{{/if}}
{{#if (eq auth "better-auth")}}
import UserMenu from './UserMenu.svelte';
{{/if}}
{{#if (eq auth "clerk")}}
import { SignedIn, UserButton } from '@clerk/sveltekit';
{{/if}}
Suggested change
{{#if (eq auth "better-auth")}}
import UserMenu from './UserMenu.svelte';
{{/if}}
{
"dependencies": {
"svelte": "{{svelteVersion}}",
// … other deps …
{{#if (eq auth "clerk")}}
"@clerk/sveltekit": "^<latest-version>",
{{/if}}
// … other deps …
}
}

Comment on lines 340 to 355
// For Convex backend, Clerk and "none" auth are allowed without database
if (nextStack.auth !== "none" && nextStack.backend !== "convex") {
notes.database.notes.push(
"Database 'None' selected: Auth will be disabled.",
);
notes.auth.notes.push(
"Authentication requires a database. It will be disabled.",
"Authentication requires a database. It will be set to 'None'.",
);
notes.database.hasIssue = true;
notes.auth.hasIssue = true;
nextStack.auth = "false";
nextStack.auth = "none";
changed = true;
changes.push({
category: "database",
message: "Authentication disabled (requires a database)",
message: "Authentication set to 'None' (requires a database)",
});

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.

🛠️ Refactor suggestion

Refine: Allow Clerk with database='none' only for Convex; coerce ‘better-auth’ → ‘clerk’.

Great that you exempt Convex from disabling auth. Add a guard to transform unsupported auth to Clerk when Convex + no DB.

-      // For Convex backend, Clerk and "none" auth are allowed without database
-      if (nextStack.auth !== "none" && nextStack.backend !== "convex") {
+      // For Convex backend, Clerk and "none" auth are allowed without database
+      if (nextStack.auth !== "none" && nextStack.backend !== "convex") {
         notes.database.notes.push(
           "Database 'None' selected: Auth will be disabled.",
         );
         notes.auth.notes.push(
           "Authentication requires a database. It will be set to 'None'.",
         );
         notes.database.hasIssue = true;
         notes.auth.hasIssue = true;
         nextStack.auth = "none";
         changed = true;
         changes.push({
           category: "database",
           message: "Authentication set to 'None' (requires a database)",
         });
+      } else if (
+        nextStack.backend === "convex" &&
+        nextStack.auth !== "none" &&
+        nextStack.auth !== "clerk"
+      ) {
+        notes.auth.notes.push(
+          "Convex without a database supports only 'Clerk' or 'None'. 'Clerk' will be selected.",
+        );
+        notes.auth.hasIssue = true;
+        nextStack.auth = "clerk";
+        changed = true;
+        changes.push({
+          category: "database",
+          message: "Auth set to 'Clerk' (Convex without DB supports Clerk/None)",
+        });
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// For Convex backend, Clerk and "none" auth are allowed without database
if (nextStack.auth !== "none" && nextStack.backend !== "convex") {
notes.database.notes.push(
"Database 'None' selected: Auth will be disabled.",
);
notes.auth.notes.push(
"Authentication requires a database. It will be disabled.",
"Authentication requires a database. It will be set to 'None'.",
);
notes.database.hasIssue = true;
notes.auth.hasIssue = true;
nextStack.auth = "false";
nextStack.auth = "none";
changed = true;
changes.push({
category: "database",
message: "Authentication disabled (requires a database)",
message: "Authentication set to 'None' (requires a database)",
});
// For Convex backend, Clerk and "none" auth are allowed without database
if (nextStack.auth !== "none" && nextStack.backend !== "convex") {
notes.database.notes.push(
"Database 'None' selected: Auth will be disabled.",
);
notes.auth.notes.push(
"Authentication requires a database. It will be set to 'None'.",
);
notes.database.hasIssue = true;
notes.auth.hasIssue = true;
nextStack.auth = "none";
changed = true;
changes.push({
category: "database",
message: "Authentication set to 'None' (requires a database)",
});
} else if (
nextStack.backend === "convex" &&
nextStack.auth !== "none" &&
nextStack.auth !== "clerk"
) {
notes.auth.notes.push(
"Convex without a database supports only 'Clerk' or 'None'. 'Clerk' will be selected.",
);
notes.auth.hasIssue = true;
nextStack.auth = "clerk";
changed = true;
changes.push({
category: "database",
message: "Auth set to 'Clerk' (Convex without DB supports Clerk/None)",
});
}
🤖 Prompt for AI Agents
In apps/web/src/app/(home)/_components/stack-builder.tsx around lines 340 to
355, refine the auth/database logic so that Clerk is allowed with database ===
"none" only when backend === "convex" and coerce unsupported auth value
"better-auth" to "clerk" in that Convex+no-DB case; keep the existing behavior
that non-Convex backends with database "none" force auth to "none" (set
nextStack.auth="none", mark notes/auth and notes/database hasIssue=true, set
changed=true, and push the same changes entry). Ensure when you coerce
"better-auth" to "clerk" you update notes.auth (no issue), set changed=true and
push a suitable changes entry for the coercion.

@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

🧹 Nitpick comments (6)
apps/cli/templates/frontend/react/tanstack-router/src/main.tsx.hbs (2)

15-21: Optional: import ClerkLoaded to avoid UI flicker and ensure token readiness

When Clerk initializes, there can be a brief unauthenticated render. Importing ClerkLoaded enables gating until Clerk is ready.

-  import { ClerkProvider, useAuth } from "@clerk/clerk-react";
+  import { ClerkProvider, ClerkLoaded, useAuth } from "@clerk/clerk-react";

50-63: Optional: Harden Clerk path

  • Cast the publishable key:
    <ClerkProvider publishableKey={import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string}>
  • Wrap your Convex provider in <ClerkLoaded> (imported from @clerk/clerk-react) to avoid a flash of unauthenticated UI and ensure useAuth is ready:
     <ClerkProvider publishableKey={import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string}>
  • {children}
``` - Your generator already scaffolds both `VITE_CLERK_PUBLISHABLE_KEY` and `VITE_CONVEX_URL` in the env templates.
apps/cli/templates/auth/clerk/convex/web/react/tanstack-router/src/routes/dashboard.tsx.hbs (3)

24-24: Make greeting resilient when fullName is absent.
Fall back to a safe placeholder to avoid rendering “Welcome ”.

Example: Welcome {user.user?.fullName || "there"}


29-31: Consider SignIn UX: modal + post-auth redirect.
Improves flow without a full-page jump.

Example: <SignInButton mode="modal" afterSignInUrl="/dashboard" afterSignUpUrl="/dashboard" />


33-34: Small a11y win for loading state.
Announce loading to screen readers.

Example: <div role="status" aria-live="polite">Loading...</div>

apps/cli/src/helpers/core/auth-setup.ts (1)

78-89: Avoid adding '@better-auth/expo' to the server app.

Expo package belongs in the native app only; adding it to server inflates deps and may break builds.

Apply:

-        if (serverDirExists) {
-          await addPackageDependency({
-            dependencies: ["@better-auth/expo"],
-            projectDir: serverDir,
-          });
-        }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 292b8d1 and a16a583.

📒 Files selected for processing (8)
  • apps/cli/src/constants.ts (2 hunks)
  • apps/cli/src/helpers/core/auth-setup.ts (3 hunks)
  • apps/cli/src/helpers/core/create-project.ts (3 hunks)
  • apps/cli/src/helpers/core/env-setup.ts (2 hunks)
  • apps/cli/src/helpers/core/template-manager.ts (6 hunks)
  • apps/cli/templates/auth/clerk/convex/backend/convex/privateData.ts.hbs (1 hunks)
  • apps/cli/templates/auth/clerk/convex/web/react/tanstack-router/src/routes/dashboard.tsx.hbs (1 hunks)
  • apps/cli/templates/frontend/react/tanstack-router/src/main.tsx.hbs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/cli/templates/auth/clerk/convex/backend/convex/privateData.ts.hbs
  • apps/cli/src/constants.ts
  • apps/cli/src/helpers/core/env-setup.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/convex_rules.mdc)

**/*.{ts,tsx}: Use Id from './_generated/dataModel' to type document ids (e.g., Id<'users'>)
Ensure Record key/value types align with validators (e.g., v.record(v.id('users'), v.string()) => Record<Id<'users'>, string>)
Be strict with types for document ids; prefer Id<'table'> over string
Use 'as const' for string literals in discriminated unions
When using Array and Record types, declare with explicit generic types (e.g., const arr: Array = ...)

Files:

  • apps/cli/src/helpers/core/auth-setup.ts
  • apps/cli/src/helpers/core/template-manager.ts
  • apps/cli/src/helpers/core/create-project.ts
**/*.{js,jsx,ts,tsx,mjs,cjs}

📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)

**/*.{js,jsx,ts,tsx,mjs,cjs}: Do not use dotenv; Bun auto-loads .env
Use Bun.serve() for HTTP/WebSockets; do not use express
Use bun:sqlite for SQLite; do not use better-sqlite3
Use Bun.redis for Redis; do not use ioredis
Use Bun.sql for Postgres; do not use pg or postgres.js
Use built-in WebSocket; do not use ws
Prefer Bun.file over node:fs readFile/writeFile
Use Bun.$ instead of execa for shelling out

Files:

  • apps/cli/src/helpers/core/auth-setup.ts
  • apps/cli/src/helpers/core/template-manager.ts
  • apps/cli/src/helpers/core/create-project.ts
🧠 Learnings (1)
📚 Learning: 2025-08-24T18:00:39.152Z
Learnt from: CR
PR: AmanVarshney01/create-better-t-stack#0
File: .cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-08-24T18:00:39.152Z
Learning: Applies to convex/schema.ts : Always define the Convex schema in convex/schema.ts and import schema helpers from convex/server

Applied to files:

  • apps/cli/templates/frontend/react/tanstack-router/src/main.tsx.hbs
🧬 Code graph analysis (3)
apps/cli/src/helpers/core/auth-setup.ts (1)
apps/cli/src/utils/add-package-deps.ts (1)
  • addPackageDependency (6-43)
apps/cli/src/helpers/core/template-manager.ts (1)
apps/cli/src/constants.ts (1)
  • PKG_ROOT (8-8)
apps/cli/src/helpers/core/create-project.ts (1)
apps/cli/src/helpers/core/template-manager.ts (1)
  • setupAuthTemplate (361-583)
🔇 Additional comments (14)
apps/cli/templates/auth/clerk/convex/web/react/tanstack-router/src/routes/dashboard.tsx.hbs (3)

11-13: Route definition looks correct for TanStack Router v1.
Exporting Route via createFileRoute("/dashboard")({ component }) is consistent.


2-2: Verify the path alias for the generated Convex API resolves in generated apps.
@{{projectName}}/backend/convex/_generated/api assumes a workspace package or TS path alias. Ensure the template generator sets this up (pnpm/yarn workspaces name or tsconfig.paths), otherwise consumers will hit module resolution errors.

I can help add a tsconfig paths snippet in the template if needed.


4-9: Confirm AuthLoading availability in your pinned convex version.
Some versions export Authenticated/Unauthenticated but not AuthLoading. If unavailable, replace with a state derived from useConvexAuth() or simply rely on Clerk’s loading indicators.

Would you like me to adjust the template for older Convex versions if AuthLoading isn’t present?

apps/cli/src/helpers/core/create-project.ts (3)

15-15: Import path update looks correct.

Localizing setupAuth under core resolves the prior relative hop.


73-75: Auth gating is correct; Clerk dependencies present in dependencyVersionMap.


50-50: Unconditionally scaffolding auth templates is correct for Convex + Clerk; double-check for backend template collisions.
The previous overlap check failed to produce results—absence of evidence isn’t evidence of absence. Please run this revised script to confirm that no files in apps/cli/templates/auth/clerk/convex/backend shadow those in apps/cli/templates/backend/convex/packages/backend:

#!/usr/bin/env bash
set -euo pipefail
A="apps/cli/templates/backend/convex/packages/backend"
B="apps/cli/templates/auth/clerk/convex/backend"

if [[ -d "$A" && -d "$B" ]]; then
  echo "Checking for overlapping files…"
  comm -12 \
    <(cd "$A" && find . -type f -printf '%P\n' | sort) \
    <(cd "$B" && find . -type f -printf '%P\n' | sort) \
    && echo "✔️ No overlaps detected" \
    || echo "⚠️ Overlaps found—verify carefully"
else
  echo "Missing template directory: $A or $B"
fi
apps/cli/src/helpers/core/auth-setup.ts (4)

10-12: Early return on 'none' is appropriate.


45-50: Server-side Better-Auth install condition is correct.


64-71: Client-side Better-Auth install scoping is correct.


23-44: Convex + Clerk client deps—version map exists; verify prompt offers only supported React frameworks

  • Constants.ts includes @clerk/nextjs and @clerk/clerk-react entries.
  • Ensure the CLI’s frontend-selection prompt only lists Next.js or TanStack-Router/React-Router when --backend convex --auth clerk; block or document any other frameworks as unsupported.
apps/cli/src/helpers/core/template-manager.ts (4)

365-365: Guard now respects 'none' and proceeds for Convex when needed — good.


430-484: Provider-scoped server templates (skipping Convex) — good separation.


486-544: Provider-scoped web templates — LGTM.


546-583: Provider-scoped native templates — LGTM.

Comment on lines +388 to +429
if (context.backend === "convex" && authProvider === "clerk") {
// Copy Convex backend pieces for Clerk
const convexBackendDestDir = path.join(projectDir, "packages/backend");
const convexClerkBackendSrc = path.join(
PKG_ROOT,
"templates/auth/clerk/convex/backend",
);
if (await fs.pathExists(convexClerkBackendSrc)) {
await fs.ensureDir(convexBackendDestDir);
await processAndCopyFiles(
"**/*",
convexClerkBackendSrc,
convexBackendDestDir,
context,
);
}

// Copy web templates if web app exists
if (webAppDirExists) {
const reactFramework = context.frontend.find((f) =>
["tanstack-router", "react-router", "tanstack-start", "next"].includes(
f,
),
);
if (reactFramework) {
const convexClerkWebSrc = path.join(
PKG_ROOT,
`templates/auth/clerk/convex/web/react/${reactFramework}`,
);
if (await fs.pathExists(convexClerkWebSrc)) {
await processAndCopyFiles(
"**/*",
convexClerkWebSrc,
webAppDir,
context,
);
}
}
}
return;
}

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.

💡 Verification agent

🧩 Analysis chain

Convex + Clerk templating path: verify sources exist and check overlay risk.

Ensure both backend and per-framework web template roots exist; detect collisions with base Convex backend.


🏁 Script executed:

#!/bin/bash
set -euo pipefail
echo "Existence checks:"
for d in \
  apps/cli/templates/auth/clerk/convex/backend \
  apps/cli/templates/auth/clerk/convex/web/react/next \
  apps/cli/templates/auth/clerk/convex/web/react/tanstack-router \
  apps/cli/templates/auth/clerk/convex/web/react/react-router \
  apps/cli/templates/auth/clerk/convex/web/react/tanstack-start
do
  [[ -d "$d" ]] && echo "OK: $d" || echo "MISSING: $d"
done
# Collision check with base Convex backend
A="apps/cli/templates/backend/convex/packages/backend"
B="apps/cli/templates/auth/clerk/convex/backend"
if [[ -d "$A" && -d "$B" ]]; then
  echo "Overlapping files (if any):"
  comm -12 \
    <(cd "$A" && fd -t f -a | sed "s#^$A/##" | sort) \
    <(cd "$B" && fd -t f -a | sed "s#^$B/##" | sort) || true
fi

Length of output: 3184


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Gather file lists
fd -t f -a apps/cli/templates/backend/convex > /tmp/base.txt
fd -t f -a apps/cli/templates/auth/clerk/convex/backend > /tmp/clerk.txt

echo "Base Convex backend templates:"
sed 's#^apps/cli/templates/backend/convex/##' /tmp/base.txt | sort
echo
echo "Clerk Convex backend templates:"
sed 's#^apps/cli/templates/auth/clerk/convex/backend/##' /tmp/clerk.txt | sort
echo
echo "Overlapping files (relative paths):"
comm -12 \
  <(sed 's#^apps/cli/templates/backend/convex/##' /tmp/base.txt | sort) \
  <(sed 's#^apps/cli/templates/auth/clerk/convex/backend/##' /tmp/clerk.txt | sort)

Length of output: 504


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# List all files in base Convex backend templates
find apps/cli/templates/backend/convex -type f | sed 's#^apps/cli/templates/backend/convex/##' | sort > /tmp/base.txt

# List all files in Clerk Convex backend templates
find apps/cli/templates/auth/clerk/convex/backend -type f | sed 's#^apps/cli/templates/auth/clerk/convex/backend/##' | sort > /tmp/clerk.txt

echo "Base Convex backend templates:"
cat /tmp/base.txt
echo
echo "Clerk Convex backend templates:"
cat /tmp/clerk.txt
echo
echo "Overlapping files (relative paths):"
comm -12 /tmp/base.txt /tmp/clerk.txt || echo "(none)"

Length of output: 863


Add missing Clerk+Convex web templates and confirm supported frameworks

  • apps/cli/templates/auth/clerk/convex/web/react/react-router and …/tanstack-start are absent; add those directories (or remove them from the supported-frameworks list) so that processAndCopyFiles can run for those frameworks.
  • No overlapping files detected between templates/backend/convex and templates/auth/clerk/convex/backend.

Comment on lines +15 to +37
function RouteComponent() {
const privateData = useQuery(api.privateData.get);
const user = useUser()

return (
<>
<Authenticated>
<div>
<h1>Dashboard</h1>
<p>Welcome {user.user?.fullName}</p>
<p>privateData: {privateData?.message}</p>
<UserButton />
</div>
</Authenticated>
<Unauthenticated>
<SignInButton />
</Unauthenticated>
<AuthLoading>
<div>Loading...</div>
</AuthLoading>
</>
);
}

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.

⚠️ Potential issue

Fix: avoid unauthorized errors by not running private Convex query before auth resolves.
useQuery(api.privateData.get) runs even when unauthenticated, which can throw (e.g., 401) and crash the route. Mount the querying component only inside <Authenticated> (preserves hook rules) and show an internal loading state for the query.

Apply:

-function RouteComponent() {
-  const privateData = useQuery(api.privateData.get);
-  const user = useUser()
-
-  return (
-    <>
-      <Authenticated>
-        <div>
-          <h1>Dashboard</h1>
-          <p>Welcome {user.user?.fullName}</p>
-          <p>privateData: {privateData?.message}</p>
-          <UserButton />
-        </div>
-      </Authenticated>
-      <Unauthenticated>
-        <SignInButton />
-      </Unauthenticated>
-      <AuthLoading>
-        <div>Loading...</div>
-      </AuthLoading>
-    </>
-  );
-}
+function DashboardAuthed() {
+  const { user } = useUser();
+  const privateData = useQuery(api.privateData.get);
+  if (privateData === undefined) return <div>Loading...</div>;
+  return (
+    <div>
+      <h1>Dashboard</h1>
+      <p>Welcome {user?.user?.fullName || "there"}</p>
+      <p>privateData: {privateData.message}</p>
+      <UserButton />
+    </div>
+  );
+}
+
+function RouteComponent() {
+  return (
+    <>
+      <Authenticated>
+        <DashboardAuthed />
+      </Authenticated>
+      <Unauthenticated>
+        <SignInButton />
+      </Unauthenticated>
+      <AuthLoading>
+        <div>Loading...</div>
+      </AuthLoading>
+    </>
+  );
+}

Alternative (if you prefer a single component): pass “skip” args until signed in, e.g., const { isSignedIn } = useUser(); const privateData = useQuery(api.privateData.get, isSignedIn ? {} : undefined);

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In
apps/cli/templates/auth/clerk/convex/web/react/tanstack-router/src/routes/dashboard.tsx.hbs
around lines 15 to 37, useQuery(api.privateData.get) is executed before auth
resolves and can throw for unauthenticated users; fix by ensuring the Convex
query only runs once authenticated: either move the query into a child component
that is only mounted inside <Authenticated> (to preserve hook rules) and render
that component from <Authenticated>, showing an internal loading state while the
query resolves; OR keep a single component and guard the query with the skip
pattern (e.g., derive isSignedIn from useUser and pass undefined or a skip arg
to useQuery until signed in) so the query never runs for unauthenticated users.

@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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/cli/templates/frontend/react/react-router/src/root.tsx.hbs (1)

65-68: Guard VITE_CONVEX_URL at runtime to avoid hard-to-debug failures

Casting to string hides missing envs; add an invariant before constructing the client.

 export default function App() {
-  const convex = new ConvexReactClient(
-    import.meta.env.VITE_CONVEX_URL as string,
-  );
+  const convexUrl = import.meta.env.VITE_CONVEX_URL as string | undefined;
+  if (!convexUrl) {
+    throw new Error("VITE_CONVEX_URL is not set. Add it to your .env file.");
+  }
+  const convex = new ConvexReactClient(convexUrl);
🧹 Nitpick comments (5)
apps/cli/templates/auth/clerk/convex/web/react/react-router/src/routes/dashboard.tsx.hbs (3)

12-12: Remove “user.user” by destructuring from Clerk’s hook.

Cleaner and avoids nested property access.

-const user = useUser();
+const { user } = useUser();
-<p>Welcome {user.user?.fullName}</p>
+<p>Welcome {user?.fullName}</p>

Also applies to: 19-19


20-20: Prevent “undefined” flash while the query loads.

Show a loading placeholder until privateData resolves.

-<p>privateData: {privateData?.message}</p>
+{privateData ? (
+  <p>privateData: {privateData.message}</p>
+) : (
+  <p>Loading private data...</p>
+)}

24-26: Optional UX: open Clerk sign-in as a modal.

Smoother flow for client-side routing.

-<SignInButton />
+<SignInButton mode="modal" />
apps/cli/templates/frontend/react/react-router/src/root.tsx.hbs (2)

69-88: DRY the duplicated UI shell across Clerk and non-Clerk branches

Extract the shared ThemeProvider/Header/Outlet/Toaster into a small AppShell to reduce maintenance overhead.

// place near other components in this file
function AppShell() {
  return (
    <ThemeProvider attribute="class" defaultTheme="dark" disableTransitionOnChange storageKey="vite-ui-theme">
      <div className="grid grid-rows-[auto_1fr] h-svh">
        <Header />
        <Outlet />
      </div>
      <Toaster richColors />
    </ThemeProvider>
  );
}
-    <ClerkProvider ...>
-      <ConvexProviderWithClerk ...>
-        <ThemeProvider ...> ... </ThemeProvider>
-      </ConvexProviderWithClerk>
-    </ClerkProvider>
+    <ClerkProvider ...>
+      <ConvexProviderWithClerk ...>
+        <AppShell />
+      </ConvexProviderWithClerk>
+    </ClerkProvider>
-  return (
-    <ConvexProvider client={convex}>
-      <ThemeProvider ...> ... </ThemeProvider>
-    </ConvexProvider>
-  );
+  return (
+    <ConvexProvider client={convex}>
+      <AppShell />
+    </ConvexProvider>
+  );

Also applies to: 89-105


65-68: Avoid re-instantiating ConvexReactClient on re-renders

Hoist the client to module scope; this keeps subscriptions stable and avoids unnecessary reconnects.

Add near the top (inside the convex backend hbs guard):

{{#if (eq backend "convex")}}
const convexUrl = import.meta.env.VITE_CONVEX_URL as string | undefined;
if (!convexUrl) {
  throw new Error("VITE_CONVEX_URL is not set. Add it to your .env file.");
}
const convex = new ConvexReactClient(convexUrl);
{{/if}}

Then remove its creation from inside App:

-  const convex = new ConvexReactClient(
-    import.meta.env.VITE_CONVEX_URL as string,
-  );
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a16a583 and e6f1519.

📒 Files selected for processing (3)
  • apps/cli/templates/auth/clerk/convex/web/react/next/src/app/dashboard/page.tsx.hbs (1 hunks)
  • apps/cli/templates/auth/clerk/convex/web/react/react-router/src/routes/dashboard.tsx.hbs (1 hunks)
  • apps/cli/templates/frontend/react/react-router/src/root.tsx.hbs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/cli/templates/auth/clerk/convex/web/react/next/src/app/dashboard/page.tsx.hbs
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-06-08T17:57:33.083Z
Learnt from: Vijayabaskar56
PR: AmanVarshney01/create-better-t-stack#310
File: apps/cli/templates/frontend/angular/src/app.component.html:1-7
Timestamp: 2025-06-08T17:57:33.083Z
Learning: For NgxSonnerToaster in the Angular template, it's sufficient to import it directly in the app-root component's imports array rather than in a module, following the standalone component approach.

Applied to files:

  • apps/cli/templates/frontend/react/react-router/src/root.tsx.hbs
🔇 Additional comments (1)
apps/cli/templates/auth/clerk/convex/web/react/react-router/src/routes/dashboard.tsx.hbs (1)

1-33: Overall structure is solid.

Clear auth states, simple UI, and correct API usage alignment with Convex and Clerk.

Comment on lines +1 to +8
import { SignInButton, UserButton, useUser } from "@clerk/clerk-react";
import { api } from "@{{projectName}}/backend/convex/_generated/api";
import {
Authenticated,
AuthLoading,
Unauthenticated,
useQuery,
} from "convex/react";

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.

💡 Verification agent

🧩 Analysis chain

Verify Convex+Clerk provider wiring and path alias resolution.

  • The Auth wrappers are imported from convex/react; ensure the app is wrapped with ConvexProviderWithClerk so Authenticated/Unauthenticated/AuthLoading function correctly.
  • Confirm tsconfig path aliases resolve @{{projectName}}/backend/convex/_generated/api at build time.

Run:


🏁 Script executed:

#!/bin/bash
# Check provider usage
rg -nP -C2 'ConvexProviderWithClerk|useConvexAuth|Authenticated|Unauthenticated|AuthLoading' --type=ts --type=tsx

# Confirm convex version and presence
rg -nP '"convex"\s*:' -n --glob 'package.json'

# Validate api import target exists in the template output
rg -nP 'backend/convex/_generated/api' -n

# Validate tsconfig path alias
rg -nP '"paths"\s*:\s*\{[^}]*"@[^"]+\/\*"' tsconfig*.json -n

Length of output: 3713


🏁 Script executed:

#!/bin/bash
# Search for ConvexProviderWithClerk in TSX files
rg -n 'ConvexProviderWithClerk' --glob '*.tsx'
# Search for useConvexAuth in TSX files
rg -n 'useConvexAuth' --glob '*.tsx'
# Search for Authenticated wrappers in HBS templates
rg -n 'Authenticated' --glob '*.hbs'
# Search for path aliases in tsconfig files
rg -n '"paths"\s*:' tsconfig*.json tsconfig.*.json

Length of output: 1287


🏁 Script executed:

#!/bin/bash
set -e

echo "1. List all files in the react-router template:"
find apps/cli/templates/auth/clerk/convex/web/react/react-router -type f

echo
echo "2. Search HBS templates for ConvexProviderWithClerk:"
rg -n 'ConvexProviderWithClerk' -g '*.hbs' apps/cli/templates/auth/clerk/convex/web/react/react-router || echo "No occurrences of provider wrapper"

echo
echo "3. Locate any tsconfig template files:"
find apps/cli/templates/auth/clerk/convex/web/react/react-router -type f | rg 'tsconfig' || echo "No tsconfig templates"

echo
echo "4. Search for a 'paths' block in any template:"
rg -n '"paths"' apps/cli/templates/auth/clerk/convex/web/react/react-router || echo "No path aliases defined in templates"

Length of output: 1097


Add missing ConvexProviderWithClerk wrapper and tsconfig path alias

  • Wrap the app root (e.g. your entry file or root layout) with ConvexProviderWithClerk so that Authenticated, Unauthenticated and AuthLoading from "convex/react" work correctly.
  • In your project’s tsconfig.json, add:
    "paths": {
      "@{{projectName}}/backend/convex/_generated/api": ["backend/convex/_generated/api"]
    }
    to ensure the import { api } from "@{{projectName}}/backend/convex/_generated/api" in routes/dashboard.tsx.hbs resolves at build time.
🤖 Prompt for AI Agents
In
apps/cli/templates/auth/clerk/convex/web/react/react-router/src/routes/dashboard.tsx.hbs
around lines 1-8, the file imports Authenticated/Unauthenticated/AuthLoading
from "convex/react" but the app root is not wrapped with ConvexProviderWithClerk
and the path alias for the generated Convex API is missing; update the app
entry/root layout to wrap the app with ConvexProviderWithClerk (importing and
using it to provide Convex auth context) so those components work correctly, and
add a tsconfig.json "paths" entry mapping
"@{projectName}/backend/convex/_generated/api" to
"backend/convex/_generated/api" so the import of api resolves at build time.

Comment on lines +10 to +23
export default function Dashboard() {
const privateData = useQuery(api.privateData.get);
const user = useUser();

return (
<>
<Authenticated>
<div>
<h1>Dashboard</h1>
<p>Welcome {user.user?.fullName}</p>
<p>privateData: {privateData?.message}</p>
<UserButton />
</div>
</Authenticated>

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.

🛠️ Refactor suggestion

Avoid executing the Convex query while signed out; add data-loading fallback.

Move the query into an authenticated-only subcomponent to prevent unauthorized calls and to show a proper loading state for privateData.

 export default function Dashboard() {
-  const privateData = useQuery(api.privateData.get);
-  const user = useUser();
+  const { user } = useUser();
+
+  const AuthedContent = () => {
+    const privateData = useQuery(api.privateData.get);
+    if (!privateData) return <div>Loading private data...</div>;
+    return (
+      <div>
+        <h1>Dashboard</h1>
+        <p>Welcome {user?.fullName ?? "there"}</p>
+        <p>privateData: {privateData.message}</p>
+        <UserButton />
+      </div>
+    );
+  };

   return (
     <>
       <Authenticated>
-        <div>
-          <h1>Dashboard</h1>
-          <p>Welcome {user.user?.fullName}</p>
-          <p>privateData: {privateData?.message}</p>
-          <UserButton />
-        </div>
+        <AuthedContent />
       </Authenticated>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export default function Dashboard() {
const privateData = useQuery(api.privateData.get);
const user = useUser();
return (
<>
<Authenticated>
<div>
<h1>Dashboard</h1>
<p>Welcome {user.user?.fullName}</p>
<p>privateData: {privateData?.message}</p>
<UserButton />
</div>
</Authenticated>
export default function Dashboard() {
const { user } = useUser();
const AuthedContent = () => {
const privateData = useQuery(api.privateData.get);
if (!privateData) return <div>Loading private data...</div>;
return (
<div>
<h1>Dashboard</h1>
<p>Welcome {user?.fullName ?? "there"}</p>
<p>privateData: {privateData.message}</p>
<UserButton />
</div>
);
};
return (
<>
<Authenticated>
<AuthedContent />
</Authenticated>
</>
);
}

Comment on lines +16 to +22
import { ConvexReactClient } from "convex/react";
{{#if (eq auth "clerk")}}
import { ClerkProvider, useAuth } from "@clerk/clerk-react";
import { ConvexProviderWithClerk } from "convex/react-clerk";
{{else}}
import { ConvexProvider } from "convex/react";
{{/if}}

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.

💡 Verification agent

🧩 Analysis chain

Ensure deps are conditionally installed for the Clerk + Convex path

These gated imports require template-time dependency gating so non-Clerk projects don’t pull Clerk packages.

Run to verify package scaffolding and .env templates:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Clerk deps should only appear in clerk-auth templates
rg -n --glob 'apps/cli/templates/**/package.json.hbs' '@clerk/clerk-react|convex\/react-clerk' -C2

# Convex dep should be present for convex backend
rg -n --glob 'apps/cli/templates/**/package.json.hbs' '"convex"\s*:'

# Env keys should be scaffolded
rg -n --glob 'apps/cli/templates/**/.env*.hbs' 'VITE_CLERK_PUBLISHABLE_KEY|VITE_CONVEX_URL' -C1

# Docs/README should reference both keys
rg -n --glob 'apps/cli/templates/**/*' 'VITE_CLERK_PUBLISHABLE_KEY|VITE_CONVEX_URL' -C1

Length of output: 250


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Verify Clerk deps appear only in clerk-auth templates
rg -n --glob 'apps/cli/templates/**/package.json.hbs' -e '@clerk/clerk-react' -e 'convex/react-clerk' -C2

# Verify Convex dep is present in all templates
rg -n --glob 'apps/cli/templates/**/package.json.hbs' -e '"convex":' -C2

# Verify .env templates scaffold required keys
rg -n --glob 'apps/cli/templates/**/.env*.hbs' -e 'VITE_CLERK_PUBLISHABLE_KEY' -e 'VITE_CONVEX_URL' -C1

# Verify docs/README reference both env keys
rg -n --glob 'apps/cli/templates/**/*' -e 'VITE_CLERK_PUBLISHABLE_KEY' -e 'VITE_CONVEX_URL' -C1

Length of output: 123


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Listing package.json.hbs templates =="
fd --glob 'package.json.hbs' apps/cli/templates

echo "== Inspecting package.json.hbs for Clerk and Convex deps =="
for f in $(fd --glob 'package.json.hbs' apps/cli/templates); do
  echo "---- $f ----"
  rg -n '"dependencies"' -C1 "$f" || echo "No dependencies block"
  rg -n -e '@clerk/clerk-react' -e 'convex/react-clerk' -C1 "$f" || echo "No Clerk-related deps"
  rg -n '"convex":' -C1 "$f" || echo "No Convex dep"
done

echo "== Listing .env templates =="
fd --glob '.env*.hbs' apps/cli/templates

echo "== Inspecting .env templates for required keys =="
for f in $(fd --glob '.env*.hbs' apps/cli/templates); do
  echo "---- $f ----"
  rg -n -e 'VITE_CLERK_PUBLISHABLE_KEY' -e 'VITE_CONVEX_URL' -C1 "$f" || echo "No env keys"
done

echo "== Searching templates for env key references =="
rg -n -e 'VITE_CLERK_PUBLISHABLE_KEY' -e 'VITE_CONVEX_URL' -C1 apps/cli/templates

Length of output: 9809


Guard Clerk + Convex deps in React‐Router template and scaffold env keys

  • In apps/cli/templates/frontend/react/react-router/package.json.hbs, add
    • "convex": "^<convexVersion>" to dependencies
    • Wrap "@clerk/clerk-react" and "convex/react-clerk" in {{#if (eq auth "clerk")}}…{{/if}} so only Clerk projects install them
  • Add a .env.hbs in the same template dir with:
    VITE_CLERK_PUBLISHABLE_KEY=
    VITE_CONVEX_URL=
    
  • Update README.hbs in that template to document both VITE_CLERK_PUBLISHABLE_KEY and VITE_CONVEX_URL
🤖 Prompt for AI Agents
In apps/cli/templates/frontend/react/react-router/src/root.tsx.hbs lines 16-22
and related template files, the template currently imports Clerk and Convex
Clerk unconditionally and the scaffold lacks Convex dependency and environment
variable scaffolding; update
apps/cli/templates/frontend/react/react-router/package.json.hbs to add "convex":
"^<convexVersion>" to dependencies and wrap "@clerk/clerk-react" and
"convex/react-clerk" entries in {{#if (eq auth "clerk")}}…{{/if}} so those
packages are only added for Clerk-enabled projects; add a new .env.hbs in the
same template directory containing VITE_CLERK_PUBLISHABLE_KEY= and
VITE_CONVEX_URL= placeholders; and update the template README.hbs to document
the two env vars (VITE_CLERK_PUBLISHABLE_KEY and VITE_CONVEX_URL) and their
purposes.

Comment on lines +69 to +88
{{#if (eq auth "clerk")}}
return (
<ClerkProvider publishableKey={import.meta.env.VITE_CLERK_PUBLISHABLE_KEY}>
<ConvexProviderWithClerk client={convex} useAuth={useAuth}>
<ThemeProvider
attribute="class"
defaultTheme="dark"
disableTransitionOnChange
storageKey="vite-ui-theme"
>
<div className="grid grid-rows-[auto_1fr] h-svh">
<Header />
<Outlet />
</div>
<Toaster richColors />
</ThemeProvider>
</ConvexProviderWithClerk>
</ClerkProvider>
);
{{else}}

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.

🛠️ Refactor suggestion

Guard VITE_CLERK_PUBLISHABLE_KEY and pass a validated value to ClerkProvider

Prevents runtime crashes when the key is missing/misnamed.

-  return (
-    <ClerkProvider publishableKey={import.meta.env.VITE_CLERK_PUBLISHABLE_KEY}>
+  const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined;
+  if (!clerkPublishableKey) {
+    throw new Error("VITE_CLERK_PUBLISHABLE_KEY is not set. Add it to your .env file.");
+  }
+  return (
+    <ClerkProvider publishableKey={clerkPublishableKey}>
       <ConvexProviderWithClerk client={convex} useAuth={useAuth}>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{{#if (eq auth "clerk")}}
return (
<ClerkProvider publishableKey={import.meta.env.VITE_CLERK_PUBLISHABLE_KEY}>
<ConvexProviderWithClerk client={convex} useAuth={useAuth}>
<ThemeProvider
attribute="class"
defaultTheme="dark"
disableTransitionOnChange
storageKey="vite-ui-theme"
>
<div className="grid grid-rows-[auto_1fr] h-svh">
<Header />
<Outlet />
</div>
<Toaster richColors />
</ThemeProvider>
</ConvexProviderWithClerk>
</ClerkProvider>
);
{{else}}
{{#if (eq auth "clerk")}}
const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined;
if (!clerkPublishableKey) {
throw new Error("VITE_CLERK_PUBLISHABLE_KEY is not set. Add it to your .env file.");
}
return (
<ClerkProvider publishableKey={clerkPublishableKey}>
<ConvexProviderWithClerk client={convex} useAuth={useAuth}>
<ThemeProvider
attribute="class"
defaultTheme="dark"
disableTransitionOnChange
storageKey="vite-ui-theme"
>
<div className="grid grid-rows-[auto_1fr] h-svh">
<Header />
<Outlet />
</div>
<Toaster richColors />
</ThemeProvider>
</ConvexProviderWithClerk>
</ClerkProvider>
);
{{else}}
🤖 Prompt for AI Agents
In apps/cli/templates/frontend/react/react-router/src/root.tsx.hbs around lines
69 to 88, the ClerkProvider is being passed
import.meta.env.VITE_CLERK_PUBLISHABLE_KEY directly which can be undefined and
cause runtime crashes; guard and validate the value first by reading it into a
local constant, ensure it is a non-empty string (throw or console.error and stop
rendering during dev/build if missing), and only pass the validated
publishableKey to ClerkProvider (or conditionally render an alternative/no-auth
flow) so the app never passes undefined to ClerkProvider.

@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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/web/src/app/(home)/_components/command-section.tsx (1)

24-29: Harden clipboard copy and avoid setState-after-unmount.

Make copy robust (fallback when Clipboard API is unavailable) and clear the timeout.

Apply within this range:

-const copyCommand = (command: string, packageManager: string) => {
-  navigator.clipboard.writeText(command);
-  setCopiedCommand(packageManager);
-  setTimeout(() => setCopiedCommand(null), 2000);
-};
+const copyCommand = async (
+  command: string,
+  pm: "npm" | "pnpm" | "bun",
+) => {
+  try {
+    if (navigator?.clipboard?.writeText) {
+      await navigator.clipboard.writeText(command);
+    } else {
+      const el = document.createElement("textarea");
+      el.value = command;
+      el.style.position = "fixed";
+      el.style.opacity = "0";
+      document.body.appendChild(el);
+      el.focus();
+      el.select();
+      document.execCommand("copy");
+      document.body.removeChild(el);
+    }
+    setCopiedCommand(pm);
+    window.clearTimeout((window as any).__copyTimeout);
+    (window as any).__copyTimeout = window.setTimeout(
+      () => setCopiedCommand(null),
+      2000,
+    );
+  } catch {
+    // optionally surface a toast
+  }
+};

Outside this range, add a proper ref and cleanup (preferred pattern):

// add to imports
import { useCallback, useEffect, useRef, useState } from "react";

// near state
const copyTimeoutRef = useRef<number | null>(null);

// useCallback version of copyCommand uses copyTimeoutRef instead of window.__copyTimeout

useEffect(() => {
  return () => {
    if (copyTimeoutRef.current) window.clearTimeout(copyTimeoutRef.current);
  };
}, []);
apps/web/src/app/(home)/_components/testimonials.tsx (1)

19-28: Fix Next/Image “fill + width/height” conflict in MediaImg

react-tweet may pass width/height; Next/Image errors if combined with fill. Strip them before spreading.

-  MediaImg: (props) => {
+  MediaImg: (props) => {
     if (!props.src || props.src === "") {
       return (
         <div className="flex h-32 w-full items-center justify-center rounded bg-muted" />
       );
     }
-    return (
-      <Image {...props} alt={props.alt || "Media content"} fill unoptimized />
-    );
+    const { width: _w, height: _h, style: _style, ...rest } = props as any;
+    return (
+      <Image
+        {...rest}
+        alt={props.alt || "Media content"}
+        fill
+        sizes="(max-width: 768px) 100vw, 50vw"
+        unoptimized
+      />
+    );
   },
🧹 Nitpick comments (9)
apps/web/src/app/(home)/_components/command-section.tsx (1)

18-22: Tighten types on commands/PM literals.

Freeze literals to keep strong indexing and prevent accidental mutation.

-const commands = {
+const commands = {
   npm: "npx create-better-t-stack@latest",
   pnpm: "pnpm create better-t-stack@latest",
   bun: "bun create better-t-stack@latest",
-};
+} as const;
 
- {(["bun", "pnpm", "npm"] as const).map((pm) => (
+ {(["bun", "pnpm", "npm"] as const).map((pm) => (

Also applies to: 50-51

apps/web/src/app/(home)/analytics/_components/analytics-header.tsx (1)

68-69: Format lastUpdated as an actual UTC timestamp.

Avoid blindly appending “UTC”; format if parsable, otherwise fall back.

-Last updated: {lastUpdated ? `${lastUpdated} UTC` : "UNKNOWN"}
+Last updated: {lastUpdated
+  ? (() => {
+      const d = new Date(lastUpdated);
+      return isNaN(d.getTime())
+        ? lastUpdated
+        : `${d.toLocaleString(undefined, {
+            timeZone: "UTC",
+            year: "numeric",
+            month: "short",
+            day: "2-digit",
+            hour: "2-digit",
+            minute: "2-digit",
+          })} UTC`;
+    })()
+  : "UNKNOWN"}
apps/web/src/app/(home)/_components/sponsors-section.tsx (1)

38-55: Memoize heavy derived lists to prevent repeated recompute on re-renders.

visible/sorted/current/past/special computations are pure; memoize by sponsorsData.

Example:

const sponsors = useMemo(
  () =>
    (sponsorsData ?? []).map((s) => ({
      ...s,
      sponsor: { ...s.sponsor, customLogoUrl: s.sponsor.customLogoUrl || "" },
    })),
  [sponsorsData],
);

const visibleSponsors = useMemo(() => filterVisibleSponsors(sponsors), [sponsors]);
const sortedSponsors = useMemo(() => sortSponsors([...visibleSponsors]), [visibleSponsors]);
const currentSponsors = useMemo(() => filterCurrentSponsors(sortedSponsors), [sortedSponsors]);
const pastSponsors = useMemo(
  () => filterPastSponsors(sortSponsors([...visibleSponsors])),
  [visibleSponsors],
);
const specialSponsors = useMemo(
  () => sortSpecialSponsors(filterSpecialSponsors(currentSponsors)),
  [currentSponsors],
);
apps/web/src/app/(home)/layout.tsx (1)

13-15: Use proper CSSProperties typing for custom CSS variables.

Avoid casting to object; use CSSProperties.

-import type { ReactNode } from "react";
+import type { CSSProperties, ReactNode } from "react";
@@
-        } as object
+        } as CSSProperties
apps/web/src/app/(home)/showcase/_components/showcase-page.tsx (2)

12-15: Guard against undefined query results to avoid .length throws

Even with preloads, being defensive costs nothing and prevents rare edge cases during revalidation.

-  const showcaseProjects = usePreloadedQuery(preloadedShowcase);
+  const showcaseProjects = usePreloadedQuery(preloadedShowcase) ?? [];

58-66: Turn the “Submit via GitHub issues” hint into an actionable link

Improves UX and discoverability.

+import Link from "next/link";
@@
-              <span className="text-muted-foreground">
-                Want to showcase your project? Submit via GitHub issues
-              </span>
+              <span className="text-muted-foreground">
+                Want to showcase your project?{" "}
+                <Link
+                  href="https://github.com/AmanVarshney01/create-better-t-stack/issues/new"
+                  target="_blank"
+                  rel="noopener noreferrer"
+                  className="underline hover:text-primary"
+                >
+                  Submit via GitHub issues
+                </Link>
+              </span>
apps/web/src/app/(home)/analytics/_components/analytics-page.tsx (1)

16-24: Optional: memoize derived metrics to avoid recalculation on re-renders

Minor perf/readability; not critical given current component size.

-export default function AnalyticsPage({
-  data,
-}: {
-  data: AggregatedAnalyticsData | null;
-}) {
-  const totalProjects = data?.summary?.totalProjects || 0;
-  const avgProjectsPerDay = data?.summary?.avgProjectsPerDay || 0;
-  const authEnabledPercent = data?.summary?.authEnabledPercent || 0;
-  const mostPopularFrontend = data?.summary?.mostPopularFrontend || "None";
-  const mostPopularBackend = data?.summary?.mostPopularBackend || "None";
-  const mostPopularORM = data?.summary?.mostPopularORM || "None";
-  const mostPopularAPI = data?.summary?.mostPopularAPI || "None";
-  const mostPopularPackageManager =
-    data?.summary?.mostPopularPackageManager || "npm";
+export default function AnalyticsPage({
+  data,
+}: {
+  data: AggregatedAnalyticsData | null;
+}) {
+  const {
+    totalProjects,
+    avgProjectsPerDay,
+    authEnabledPercent,
+    mostPopularFrontend,
+    mostPopularBackend,
+    mostPopularORM,
+    mostPopularAPI,
+    mostPopularPackageManager,
+  } = (() => {
+    const s = data?.summary;
+    return {
+      totalProjects: s?.totalProjects ?? 0,
+      avgProjectsPerDay: s?.avgProjectsPerDay ?? 0,
+      authEnabledPercent: s?.authEnabledPercent ?? 0,
+      mostPopularFrontend: s?.mostPopularFrontend ?? "None",
+      mostPopularBackend: s?.mostPopularBackend ?? "None",
+      mostPopularORM: s?.mostPopularORM ?? "None",
+      mostPopularAPI: s?.mostPopularAPI ?? "None",
+      mostPopularPackageManager: s?.mostPopularPackageManager ?? "npm",
+    };
+  })();
apps/web/src/app/(home)/_components/testimonials.tsx (2)

59-66: Lazy-load YouTube iframes

Reduces LCP and network cost on initial render.

       <iframe
         src={`https://www.youtube.com/embed/${video.embedId}`}
         title={video.title}
         allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
         allowFullScreen
-        className="absolute inset-0 h-full w-full"
+        loading="lazy"
+        className="absolute inset-0 h-full w-full"
       />

94-97: Consider restoring Suspense fallback around Tweet

If Twitter blocks/slowdowns occur, this prevents layout jank. If you intentionally removed it due to SSR constraints, ignore.

Would you like me to add a lightweight skeleton fallback compatible with react-tweet v3?

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e6f1519 and bff057c.

📒 Files selected for processing (12)
  • apps/web/src/app/(home)/_components/command-section.tsx (1 hunks)
  • apps/web/src/app/(home)/_components/sponsors-section.tsx (3 hunks)
  • apps/web/src/app/(home)/_components/stats-section.tsx (2 hunks)
  • apps/web/src/app/(home)/_components/testimonials.tsx (2 hunks)
  • apps/web/src/app/(home)/analytics/_components/analytics-header.tsx (2 hunks)
  • apps/web/src/app/(home)/analytics/_components/analytics-page.tsx (1 hunks)
  • apps/web/src/app/(home)/analytics/_components/index.ts (0 hunks)
  • apps/web/src/app/(home)/analytics/page.tsx (1 hunks)
  • apps/web/src/app/(home)/layout.tsx (1 hunks)
  • apps/web/src/app/(home)/page.tsx (1 hunks)
  • apps/web/src/app/(home)/showcase/_components/showcase-page.tsx (1 hunks)
  • apps/web/src/app/(home)/showcase/page.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • apps/web/src/app/(home)/analytics/_components/index.ts
✅ Files skipped from review due to trivial changes (1)
  • apps/web/src/app/(home)/_components/stats-section.tsx
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/convex_rules.mdc)

**/*.{ts,tsx}: Use Id from './_generated/dataModel' to type document ids (e.g., Id<'users'>)
Ensure Record key/value types align with validators (e.g., v.record(v.id('users'), v.string()) => Record<Id<'users'>, string>)
Be strict with types for document ids; prefer Id<'table'> over string
Use 'as const' for string literals in discriminated unions
When using Array and Record types, declare with explicit generic types (e.g., const arr: Array = ...)

Files:

  • apps/web/src/app/(home)/_components/command-section.tsx
  • apps/web/src/app/(home)/analytics/page.tsx
  • apps/web/src/app/(home)/showcase/_components/showcase-page.tsx
  • apps/web/src/app/(home)/_components/testimonials.tsx
  • apps/web/src/app/(home)/analytics/_components/analytics-header.tsx
  • apps/web/src/app/(home)/analytics/_components/analytics-page.tsx
  • apps/web/src/app/(home)/layout.tsx
  • apps/web/src/app/(home)/showcase/page.tsx
  • apps/web/src/app/(home)/_components/sponsors-section.tsx
  • apps/web/src/app/(home)/page.tsx
**/*.{js,jsx,ts,tsx,mjs,cjs}

📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)

**/*.{js,jsx,ts,tsx,mjs,cjs}: Do not use dotenv; Bun auto-loads .env
Use Bun.serve() for HTTP/WebSockets; do not use express
Use bun:sqlite for SQLite; do not use better-sqlite3
Use Bun.redis for Redis; do not use ioredis
Use Bun.sql for Postgres; do not use pg or postgres.js
Use built-in WebSocket; do not use ws
Prefer Bun.file over node:fs readFile/writeFile
Use Bun.$ instead of execa for shelling out

Files:

  • apps/web/src/app/(home)/_components/command-section.tsx
  • apps/web/src/app/(home)/analytics/page.tsx
  • apps/web/src/app/(home)/showcase/_components/showcase-page.tsx
  • apps/web/src/app/(home)/_components/testimonials.tsx
  • apps/web/src/app/(home)/analytics/_components/analytics-header.tsx
  • apps/web/src/app/(home)/analytics/_components/analytics-page.tsx
  • apps/web/src/app/(home)/layout.tsx
  • apps/web/src/app/(home)/showcase/page.tsx
  • apps/web/src/app/(home)/_components/sponsors-section.tsx
  • apps/web/src/app/(home)/page.tsx
🧠 Learnings (4)
📚 Learning: 2025-08-24T18:00:39.152Z
Learnt from: CR
PR: AmanVarshney01/create-better-t-stack#0
File: .cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-08-24T18:00:39.152Z
Learning: Applies to convex/**/*.ts : Use query/mutation/action for public API; use internalQuery/internalMutation/internalAction for private functions; do not register via api/internal objects

Applied to files:

  • apps/web/src/app/(home)/_components/sponsors-section.tsx
📚 Learning: 2025-08-24T18:00:39.152Z
Learnt from: CR
PR: AmanVarshney01/create-better-t-stack#0
File: .cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-08-24T18:00:39.152Z
Learning: Applies to convex/**/*.ts : Always use the new Convex function syntax (query/mutation/action/internal*) with args/returns/handler

Applied to files:

  • apps/web/src/app/(home)/_components/sponsors-section.tsx
📚 Learning: 2025-08-24T18:00:39.152Z
Learnt from: CR
PR: AmanVarshney01/create-better-t-stack#0
File: .cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-08-24T18:00:39.152Z
Learning: Applies to convex/**/_generated/api.ts : Use the generated api object to reference public functions

Applied to files:

  • apps/web/src/app/(home)/_components/sponsors-section.tsx
📚 Learning: 2025-08-24T18:00:39.152Z
Learnt from: CR
PR: AmanVarshney01/create-better-t-stack#0
File: .cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-08-24T18:00:39.152Z
Learning: Applies to convex/**/*.ts : Use ctx.runQuery/ctx.runMutation/ctx.runAction instead of calling functions directly; pass a FunctionReference

Applied to files:

  • apps/web/src/app/(home)/_components/sponsors-section.tsx
🧬 Code graph analysis (7)
apps/web/src/app/(home)/analytics/page.tsx (1)
apps/web/src/app/(home)/analytics/_components/analytics-page.tsx (1)
  • AnalyticsPage (11-56)
apps/web/src/app/(home)/showcase/_components/showcase-page.tsx (1)
apps/web/src/app/(home)/showcase/_components/ShowcaseItem.tsx (1)
  • ShowcaseItem (17-121)
apps/web/src/app/(home)/analytics/_components/analytics-page.tsx (3)
apps/web/src/app/(home)/analytics/_components/types.ts (1)
  • AggregatedAnalyticsData (3-51)
apps/web/src/app/(home)/analytics/_components/analytics-header.tsx (1)
  • AnalyticsHeader (6-103)
apps/web/src/app/(home)/analytics/_components/metrics-cards.tsx (1)
  • MetricsCards (14-170)
apps/web/src/app/(home)/layout.tsx (2)
apps/web/src/app/docs/layout.tsx (1)
  • Layout (16-22)
apps/web/src/app/layout.config.tsx (1)
  • baseOptions (74-87)
apps/web/src/app/(home)/showcase/page.tsx (1)
apps/web/src/app/(home)/showcase/_components/showcase-page.tsx (1)
  • ShowcasePage (9-72)
apps/web/src/app/(home)/_components/sponsors-section.tsx (1)
apps/web/src/lib/sponsor-utils.ts (2)
  • filterPastSponsors (186-188)
  • sortSponsors (86-154)
apps/web/src/app/(home)/page.tsx (3)
apps/web/src/app/(home)/_components/stats-section.tsx (1)
  • StatsSection (17-211)
apps/web/src/app/(home)/_components/sponsors-section.tsx (1)
  • SponsorsSection (29-433)
apps/web/src/app/(home)/_components/testimonials.tsx (1)
  • Testimonials (103-282)
🔇 Additional comments (6)
apps/web/src/app/(home)/_components/command-section.tsx (1)

1-1: Client directive is appropriate for clipboard usage.

Good move making this a client component to use navigator.clipboard.

apps/web/src/app/(home)/analytics/_components/analytics-header.tsx (1)

9-12: Props simplification looks good.

Inline props with lastUpdated nullable is fine.

apps/web/src/app/(home)/_components/sponsors-section.tsx (1)

1-3: Client + preloaded query wiring is correct.

Type-only api import and Preloaded usage are on point.

apps/web/src/app/(home)/layout.tsx (1)

1-1: Confirm if this must be a client component.

If HomeLayout supports RSC, drop "use client" to keep the tree server-rendered.

Would you like me to check usage of HomeLayout and suggest the safe conversion?

apps/web/src/app/(home)/showcase/page.tsx (1)

5-9: Server preloading + client consumption is wired correctly.

preloadQuery on the server and passing Preloaded to ShowcasePage aligns with Convex best practices.

apps/web/src/app/(home)/showcase/_components/showcase-page.tsx (1)

52-55: LGTM on list rendering and stable keys

Good use of Convex _id for keys and passing index separately for display-only numbering.

Comment on lines 47 to 53
const visibleSponsors = filterVisibleSponsors(sponsors);
const sortedSponsors = sortSponsors(visibleSponsors);
const currentSponsors = filterCurrentSponsors(sortedSponsors);
const pastSponsors = filterPastSponsors(sortedSponsors);
const pastSponsors = filterPastSponsors(sortSponsors(sponsors));
const specialSponsors = sortSpecialSponsors(
filterSpecialSponsors(currentSponsors),
);

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.

⚠️ Potential issue

Past sponsors should respect visibility and avoid in-place mutation.

sortSponsors mutates its input; also pastSponsors currently includes hidden sponsors.

Apply this diff:

-const visibleSponsors = filterVisibleSponsors(sponsors);
-const sortedSponsors = sortSponsors(visibleSponsors);
+const visibleSponsors = filterVisibleSponsors(sponsors);
+const sortedSponsors = sortSponsors([...visibleSponsors]);
 const currentSponsors = filterCurrentSponsors(sortedSponsors);
-const pastSponsors = filterPastSponsors(sortSponsors(sponsors));
+const pastSponsors = filterPastSponsors(sortSponsors([...visibleSponsors]));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const visibleSponsors = filterVisibleSponsors(sponsors);
const sortedSponsors = sortSponsors(visibleSponsors);
const currentSponsors = filterCurrentSponsors(sortedSponsors);
const pastSponsors = filterPastSponsors(sortedSponsors);
const pastSponsors = filterPastSponsors(sortSponsors(sponsors));
const specialSponsors = sortSpecialSponsors(
filterSpecialSponsors(currentSponsors),
);
const visibleSponsors = filterVisibleSponsors(sponsors);
const sortedSponsors = sortSponsors([...visibleSponsors]);
const currentSponsors = filterCurrentSponsors(sortedSponsors);
const pastSponsors = filterPastSponsors(sortSponsors([...visibleSponsors]));
const specialSponsors = sortSpecialSponsors(
filterSpecialSponsors(currentSponsors),
);
🤖 Prompt for AI Agents
In apps/web/src/app/(home)/_components/sponsors-section.tsx around lines 47-53,
pastSponsors is built from sortSponsors(sponsors) which both ignores visibility
and may mutate the original array; update the logic to derive pastSponsors from
the already-filtered visibleSponsors and avoid in-place mutation by passing a
shallow copy into sortSponsors (e.g. use sortSponsors([...visibleSponsors]) or
otherwise ensure sortSponsors returns a new array); likewise ensure any other
calls to sortSponsors that must not mutate inputs are given a copy (e.g.
sortedSponsors = sortSponsors([...visibleSponsors])) so hidden sponsors are
excluded and originals are not mutated.

Comment on lines +3 to +7
export default async function Analytics() {
const response = await fetch("https://r2.amanv.dev/analytics-data.json");
const analyticsData = await response.json();

const loadAnalyticsData = useCallback(async () => {
try {
const response = await fetch("https://r2.amanv.dev/analytics-data.json");
const analyticsData = await response.json();

setData(analyticsData);
console.log("Loaded aggregated analytics data from R2 bucket");
console.log(`Data generated at: ${analyticsData.generatedAt}`);
} catch (error: unknown) {
console.error("Error loading analytics data:", error);
} finally {
setLoadingLastUpdated(false);
}
}, []);

useEffect(() => {
loadAnalyticsData();
}, [loadAnalyticsData]);

const totalProjects = data?.summary?.totalProjects || 0;
const avgProjectsPerDay = data?.summary?.avgProjectsPerDay || 0;
const authEnabledPercent = data?.summary?.authEnabledPercent || 0;
const mostPopularFrontend = data?.summary?.mostPopularFrontend || "None";
const mostPopularBackend = data?.summary?.mostPopularBackend || "None";
const mostPopularORM = data?.summary?.mostPopularORM || "None";
const mostPopularAPI = data?.summary?.mostPopularAPI || "None";
const mostPopularPackageManager =
data?.summary?.mostPopularPackageManager || "npm";

return (
<div className="mx-auto min-h-svh max-w-[1280px]">
<div className="container mx-auto space-y-8 px-4 py-8 pt-16">
<AnalyticsHeader
totalProjects={totalProjects}
lastUpdated={data?.lastUpdated || null}
loadingLastUpdated={loadingLastUpdated}
/>

<MetricsCards
totalProjects={totalProjects}
avgProjectsPerDay={avgProjectsPerDay}
authEnabledPercent={authEnabledPercent}
mostPopularFrontend={mostPopularFrontend}
mostPopularBackend={mostPopularBackend}
mostPopularORM={mostPopularORM}
mostPopularAPI={mostPopularAPI}
mostPopularPackageManager={mostPopularPackageManager}
/>

<TimelineCharts data={data} />

<StackConfigurationCharts data={data} />

<AddonsExamplesCharts data={data} />

<DevEnvironmentCharts data={data} />
</div>
<Footer />
</div>
);
return <AnalyticsPage data={analyticsData} />;

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.

🛠️ Refactor suggestion

⚠️ Potential issue

Add caching strategy, timeout, and error handling for external fetch

Prevents build-time caching surprises and runtime crashes; surfaces null gracefully to the client page.

+export const revalidate = 1800; // 30 minutes for this route
+import type { AggregatedAnalyticsData } from "./_components/types";
 import AnalyticsPage from "./_components/analytics-page";
 
 export default async function Analytics() {
-  const response = await fetch("https://r2.amanv.dev/analytics-data.json");
-  const analyticsData = await response.json();
+  const controller = new AbortController();
+  const timeout = setTimeout(() => controller.abort(), 5000);
+  let analyticsData: AggregatedAnalyticsData | null = null;
+  try {
+    const response = await fetch("https://r2.amanv.dev/analytics-data.json", {
+      next: { revalidate: 1800 },
+      signal: controller.signal,
+    });
+    if (response.ok) {
+      analyticsData = (await response.json()) as AggregatedAnalyticsData;
+    }
+  } catch {
+    analyticsData = null;
+  } finally {
+    clearTimeout(timeout);
+  }
 
   return <AnalyticsPage data={analyticsData} />;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export default async function Analytics() {
const response = await fetch("https://r2.amanv.dev/analytics-data.json");
const analyticsData = await response.json();
const loadAnalyticsData = useCallback(async () => {
try {
const response = await fetch("https://r2.amanv.dev/analytics-data.json");
const analyticsData = await response.json();
setData(analyticsData);
console.log("Loaded aggregated analytics data from R2 bucket");
console.log(`Data generated at: ${analyticsData.generatedAt}`);
} catch (error: unknown) {
console.error("Error loading analytics data:", error);
} finally {
setLoadingLastUpdated(false);
}
}, []);
useEffect(() => {
loadAnalyticsData();
}, [loadAnalyticsData]);
const totalProjects = data?.summary?.totalProjects || 0;
const avgProjectsPerDay = data?.summary?.avgProjectsPerDay || 0;
const authEnabledPercent = data?.summary?.authEnabledPercent || 0;
const mostPopularFrontend = data?.summary?.mostPopularFrontend || "None";
const mostPopularBackend = data?.summary?.mostPopularBackend || "None";
const mostPopularORM = data?.summary?.mostPopularORM || "None";
const mostPopularAPI = data?.summary?.mostPopularAPI || "None";
const mostPopularPackageManager =
data?.summary?.mostPopularPackageManager || "npm";
return (
<div className="mx-auto min-h-svh max-w-[1280px]">
<div className="container mx-auto space-y-8 px-4 py-8 pt-16">
<AnalyticsHeader
totalProjects={totalProjects}
lastUpdated={data?.lastUpdated || null}
loadingLastUpdated={loadingLastUpdated}
/>
<MetricsCards
totalProjects={totalProjects}
avgProjectsPerDay={avgProjectsPerDay}
authEnabledPercent={authEnabledPercent}
mostPopularFrontend={mostPopularFrontend}
mostPopularBackend={mostPopularBackend}
mostPopularORM={mostPopularORM}
mostPopularAPI={mostPopularAPI}
mostPopularPackageManager={mostPopularPackageManager}
/>
<TimelineCharts data={data} />
<StackConfigurationCharts data={data} />
<AddonsExamplesCharts data={data} />
<DevEnvironmentCharts data={data} />
</div>
<Footer />
</div>
);
return <AnalyticsPage data={analyticsData} />;
export const revalidate = 1800; // 30 minutes for this route
import type { AggregatedAnalyticsData } from "./_components/types";
import AnalyticsPage from "./_components/analytics-page";
export default async function Analytics() {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
let analyticsData: AggregatedAnalyticsData | null = null;
try {
const response = await fetch("https://r2.amanv.dev/analytics-data.json", {
next: { revalidate: 1800 },
signal: controller.signal,
});
if (response.ok) {
analyticsData = (await response.json()) as AggregatedAnalyticsData;
}
} catch {
analyticsData = null;
} finally {
clearTimeout(timeout);
}
return <AnalyticsPage data={analyticsData} />;
}
🤖 Prompt for AI Agents
In apps/web/src/app/(home)/analytics/page.tsx around lines 3 to 7, the external
fetch lacks caching strategy, timeout, and error handling; update the fetch to
include Next.js cache/revalidate options (e.g., explicit revalidate or no-store)
so build/runtime caching is controlled, wrap the fetch in an AbortController to
enforce a short timeout (e.g., 2–5s), check response.ok and throw on non-2xx,
parse JSON inside a try/catch and log the error, and ensure the component
returns a safe fallback (pass null or an empty object to AnalyticsPage) when the
fetch fails so the page can render gracefully instead of crashing. Ensure errors
are handled and surfaced minimally to the client while preserving a clear
fallback UI.

Comment on lines +11 to +17
const preloadedSponsors = await preloadQuery(api.sponsors.getSponsors);
const preloadedTestimonialsTweet = await preloadQuery(
api.testimonials.getTweets,
);
const preloadedTestimonialsVideos = await preloadQuery(
api.testimonials.getVideos,
);

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.

🛠️ Refactor suggestion

Preload Convex queries in parallel to cut TTFB

These are independent; use Promise.all.

-export default async function HomePage() {
-  const preloadedSponsors = await preloadQuery(api.sponsors.getSponsors);
-  const preloadedTestimonialsTweet = await preloadQuery(
-    api.testimonials.getTweets,
-  );
-  const preloadedTestimonialsVideos = await preloadQuery(
-    api.testimonials.getVideos,
-  );
+export default async function HomePage() {
+  const [
+    preloadedSponsors,
+    preloadedTestimonialsTweet,
+    preloadedTestimonialsVideos,
+  ] = await Promise.all([
+    preloadQuery(api.sponsors.getSponsors),
+    preloadQuery(api.testimonials.getTweets),
+    preloadQuery(api.testimonials.getVideos),
+  ]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const preloadedSponsors = await preloadQuery(api.sponsors.getSponsors);
const preloadedTestimonialsTweet = await preloadQuery(
api.testimonials.getTweets,
);
const preloadedTestimonialsVideos = await preloadQuery(
api.testimonials.getVideos,
);
export default async function HomePage() {
const [
preloadedSponsors,
preloadedTestimonialsTweet,
preloadedTestimonialsVideos,
] = await Promise.all([
preloadQuery(api.sponsors.getSponsors),
preloadQuery(api.testimonials.getTweets),
preloadQuery(api.testimonials.getVideos),
]);
// …rest of HomePage implementation…
}
🤖 Prompt for AI Agents
In apps/web/src/app/(home)/page.tsx around lines 11 to 17, the three
preloadQuery calls run sequentially which increases TTFB; run them in parallel
using Promise.all and then destructure the returned array into
preloadedSponsors, preloadedTestimonialsTweet, and preloadedTestimonialsVideos
so the independent network requests execute concurrently and preserve variable
assignments.

Comment on lines +19 to +24
const minimalAnalytics = await fetch(
"https://r2.amanv.dev/analytics-minimal.json",
);

const minimalAnalyticsData = await minimalAnalytics.json();

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.

🛠️ Refactor suggestion

⚠️ Potential issue

Add caching + harden external analytics fetch; coerce shape for StatsSection

Avoids build-time caching surprises and ensures the prop matches the component’s expected shape.

-  const minimalAnalytics = await fetch(
-    "https://r2.amanv.dev/analytics-minimal.json",
-  );
-
-  const minimalAnalyticsData = await minimalAnalytics.json();
+  let minimalAnalyticsData: {
+    totalProjects: number;
+    avgProjectsPerDay: string;
+    lastUpdated: string | null;
+  } = { totalProjects: 0, avgProjectsPerDay: "0.0", lastUpdated: null };
+  try {
+    const res = await fetch("https://r2.amanv.dev/analytics-minimal.json", {
+      next: { revalidate: 1800 },
+    });
+    if (res.ok) {
+      const raw = await res.json();
+      minimalAnalyticsData = {
+        totalProjects: Number(raw?.totalProjects ?? 0),
+        avgProjectsPerDay: String(raw?.avgProjectsPerDay ?? "0.0"),
+        lastUpdated: (raw?.lastUpdated ?? null) as string | null,
+      };
+    }
+  } catch {
+    // keep defaults
+  }
@@
-        <StatsSection analyticsData={minimalAnalyticsData} />
+        <StatsSection analyticsData={minimalAnalyticsData} />

Also applies to: 30-35

🤖 Prompt for AI Agents
In apps/web/src/app/(home)/page.tsx around lines 19-24 (and similarly 30-35),
the external analytics fetch is currently unparameterized and the parsed JSON is
passed directly to StatsSection; update the fetch calls to include explicit
caching/revalidation (e.g. fetch(url, { next: { revalidate: 60 } }) or { cache:
'no-store' } depending on desired behavior) to avoid build-time caching
surprises, wrap the response parsing in a try/catch and validate/coerce the
result into the shape expected by StatsSection (provide safe defaults for
missing fields and ensure types match, e.g. arrays or numbers), and apply the
same changes to the other fetch block at lines 30-35 so the component always
receives a stable, validated prop.

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/cli/templates/frontend/react/tanstack-start/src/router.tsx.hbs (2)

30-36: Fail fast if VITE_CONVEX_URL is missing and tighten the typing

Logging but proceeding will instantiate a client with an invalid URL at runtime.

-  const CONVEX_URL = (import.meta as any).env.VITE_CONVEX_URL!;
-  if (!CONVEX_URL) {
-    console.error("missing envar VITE_CONVEX_URL");
-  }
+  const CONVEX_URL = import.meta.env.VITE_CONVEX_URL as string | undefined;
+  if (!CONVEX_URL) {
+    throw new Error("Missing env var VITE_CONVEX_URL");
+  }

56-61: Avoid double Convex providers when auth=clerk

Root wraps with ConvexProviderWithClerk; wrapping again here causes nested providers. Gate this Wrap.

-      Wrap: ({ children }) => (
-        <ConvexProvider client={convexQueryClient.convexClient}>
-          {children}
-        </ConvexProvider>
-      ),
+      Wrap: ({ children }) => (
+        {{#if (eq auth "clerk")}}
+        <>{children}</>
+        {{else}}
+        <ConvexProvider client={convexQueryClient.convexClient}>
+          {children}
+        </ConvexProvider>
+        {{/if}}
+      ),
🧹 Nitpick comments (4)
apps/cli/src/helpers/core/auth-setup.ts (2)

31-46: Optional: replace branching with a small mapping to reduce duplication.

Map detected frontend → package name and do a single call. Keeps the logic compact and extensible.


23-49: Add warnings for missing clientDir and unsupported frontends in Convex + Clerk path

Add warning logs before the early return in the Convex + Clerk branch to surface when clientDir is missing or when no supported web frontend is detected.

-    if (auth === "clerk" && clientDirExists) {
+    if (auth === "clerk") {
+      if (!clientDirExists) {
+        consola.warn(pc.yellow("Clerk selected with Convex, but apps/web was not found; skipping client dependency install."));
+        return;
+      }
       const hasNextJs = frontend.includes("next");
       const hasTanStackStart = frontend.includes("tanstack-start");
       const hasViteReactOther = frontend.some((f) =>
         ["tanstack-router", "react-router"].includes(f),
       );
+      let installed = false;
       if (hasNextJs) {
         await addPackageDependency({
           dependencies: ["@clerk/nextjs"],
           projectDir: clientDir,
         });
+        installed = true;
       } else if (hasTanStackStart) {
         await addPackageDependency({
           dependencies: ["@clerk/tanstack-react-start"],
           projectDir: clientDir,
         });
+        installed = true;
       } else if (hasViteReactOther) {
         await addPackageDependency({
           dependencies: ["@clerk/clerk-react"],
           projectDir: clientDir,
         });
+        installed = true;
       }
+      if (!installed) {
+        consola.warn(pc.yellow("Clerk with Convex: no supported web frontend detected in config.frontend; skipped client dependency install."));
+      }
     }
     return;
apps/cli/templates/auth/clerk/convex/web/react/tanstack-start/src/server.ts.hbs (1)

15-18: Avoid per-request handler creation; cache the start handler at module scope

This saves an await on every request and matches typical Start/Clerk wiring.

- export default defineHandlerCallback(async (event) => {
- 	const startHandler = await handlerFactory(defaultStreamHandler);
- 	return startHandler(event);
- });
+const startHandlerPromise = handlerFactory(defaultStreamHandler);
+
+export default defineHandlerCallback(async (event) => {
+  const startHandler = await startHandlerPromise;
+  return startHandler(event);
+});
apps/cli/templates/auth/clerk/convex/web/react/tanstack-start/src/routes/dashboard.tsx.hbs (1)

29-31: Minor UX: open sign-in as a modal.

Using a modal improves flow and matches common Clerk examples. (docs.convex.dev)

-				<SignInButton />
+				<SignInButton mode="modal" />
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between bff057c and e4c2b5f.

📒 Files selected for processing (7)
  • apps/cli/src/constants.ts (2 hunks)
  • apps/cli/src/helpers/core/auth-setup.ts (3 hunks)
  • apps/cli/src/helpers/core/env-setup.ts (2 hunks)
  • apps/cli/templates/auth/clerk/convex/web/react/tanstack-start/src/routes/dashboard.tsx.hbs (1 hunks)
  • apps/cli/templates/auth/clerk/convex/web/react/tanstack-start/src/server.ts.hbs (1 hunks)
  • apps/cli/templates/frontend/react/tanstack-start/src/router.tsx.hbs (4 hunks)
  • apps/cli/templates/frontend/react/tanstack-start/src/routes/__root.tsx.hbs (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/cli/src/helpers/core/env-setup.ts
  • apps/cli/src/constants.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/convex_rules.mdc)

**/*.{ts,tsx}: Use Id from './_generated/dataModel' to type document ids (e.g., Id<'users'>)
Ensure Record key/value types align with validators (e.g., v.record(v.id('users'), v.string()) => Record<Id<'users'>, string>)
Be strict with types for document ids; prefer Id<'table'> over string
Use 'as const' for string literals in discriminated unions
When using Array and Record types, declare with explicit generic types (e.g., const arr: Array = ...)

Files:

  • apps/cli/src/helpers/core/auth-setup.ts
**/*.{js,jsx,ts,tsx,mjs,cjs}

📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)

**/*.{js,jsx,ts,tsx,mjs,cjs}: Do not use dotenv; Bun auto-loads .env
Use Bun.serve() for HTTP/WebSockets; do not use express
Use bun:sqlite for SQLite; do not use better-sqlite3
Use Bun.redis for Redis; do not use ioredis
Use Bun.sql for Postgres; do not use pg or postgres.js
Use built-in WebSocket; do not use ws
Prefer Bun.file over node:fs readFile/writeFile
Use Bun.$ instead of execa for shelling out

Files:

  • apps/cli/src/helpers/core/auth-setup.ts
🧠 Learnings (1)
📚 Learning: 2025-08-24T18:00:39.152Z
Learnt from: CR
PR: AmanVarshney01/create-better-t-stack#0
File: .cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-08-24T18:00:39.152Z
Learning: Applies to convex/**/*.ts : Always use the new Convex function syntax (query/mutation/action/internal*) with args/returns/handler

Applied to files:

  • apps/cli/templates/frontend/react/tanstack-start/src/router.tsx.hbs
🧬 Code graph analysis (1)
apps/cli/src/helpers/core/auth-setup.ts (1)
apps/cli/src/utils/add-package-deps.ts (1)
  • addPackageDependency (6-43)
🔇 Additional comments (11)
apps/cli/src/helpers/core/auth-setup.ts (4)

10-12: Guarding on explicit "none" is correct and clearer.

Early exit on !auth || auth === "none" avoids accidental installs. LGTM.


51-56: Confirm product intent: Better-Auth is skipped for Convex backends.

Because of the early return above, Better-Auth never installs when backend === "convex". If that’s the intended matrix (Convex ⇢ Clerk only), consider documenting this in prompts/README to prevent confusion.


71-76: Client-side Better-Auth gating looks right.

Only installs on web clients when auth === "better-auth". Matches the new string union model.


84-95: Native Better-Auth wiring is consistent.

Adds both better-auth and @better-auth/expo to the native app, and @better-auth/expo to server when present. Good separation.

apps/cli/templates/auth/clerk/convex/web/react/tanstack-start/src/server.ts.hbs (1)

1-13: Server handler wiring looks correct

Clerk handler wrapping Start’s handler factory is composed properly.

apps/cli/templates/frontend/react/tanstack-start/src/router.tsx.hbs (1)

89-96: TRPC credentials gating looks consistent with new auth union

Conditionally adding credentials only for better-auth is correct given the new string union.

apps/cli/templates/frontend/react/tanstack-start/src/routes/__root.tsx.hbs (2)

100-121: Provider composition is correct for Clerk + Convex

Ordering (ClerkProvider outside, ConvexProviderWithClerk inside) is appropriate.


87-93: SSR token API usage is correct
Verified that serverHttpClient?.setAuth(token) is the supported method for attaching a Clerk JWT during SSR in @convex-dev/react-query; no changes required.

apps/cli/templates/auth/clerk/convex/web/react/tanstack-start/src/routes/dashboard.tsx.hbs (3)

1-1: Correct SDK import for TanStack React Start.

Using @clerk/tanstack-react-start is consistent with Clerk’s TanStack React Start docs and exposes useUser, SignInButton, and UserButton. (clerk.com)


11-13: Route definition looks good.

createFileRoute("/dashboard")({ component }) matches TanStack Router usage for Start. (clerk.com)


21-35: Providers and handler already set up

  • Server: apps/cli/templates/auth/clerk/convex/web/react/tanstack-start/src/server.ts.hbs uses createClerkHandler
  • Client: Base layout at apps/cli/templates/frontend/react/tanstack-start/src/routes/__root.tsx.hbs wraps the app in <ClerkProvider> and <ConvexProviderWithClerk>
    No further changes required.

@@ -0,0 +1,37 @@
import { SignInButton, UserButton, useUser } from "@clerk/tanstack-react-start";
import { api } from "@{{projectName}}/backend/convex/_generated/api";

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.

💡 Verification agent

🧩 Analysis chain

Verify TS path alias for @{{projectName}}/backend/... resolves in the generated app.

If the alias isn’t defined in the consuming app’s tsconfig, switch to a relative import or add a paths mapping.

Run to confirm:


🏁 Script executed:

#!/bin/bash
# Check for a paths alias that would cover @<projectName>/*
rg -nP -C2 '"paths"\s*:\s*\{' -- tsconfig*.json

# Sanity-check any imports of convex generated API across templates
rg -nP -C2 '_generated/api' apps/cli/templates -g '!**/node_modules/**'

Length of output: 12161


🏁 Script executed:

#!/bin/bash
# Find tsconfig template files under apps/cli/templates
find apps/cli/templates -type f -name 'tsconfig*.json*'
# Search for a "paths" mapping in these tsconfig templates
rg -nP -C2 '"paths"\s*:' -- apps/cli/templates/**/tsconfig*.json*

Length of output: 992


🏁 Script executed:

#!/bin/bash
# Search for a "paths" mapping in the React TanStack Start template tsconfig
rg -nP -C2 '"paths"\s*:' apps/cli/templates/frontend/react/tanstack-start/tsconfig.json.hbs

# Preview the top of the tsconfig to inspect compilerOptions (including baseUrl/paths)
sed -n '1,200p' apps/cli/templates/frontend/react/tanstack-start/tsconfig.json.hbs

Length of output: 1066


🏁 Script executed:

#!/bin/bash
# Inspect tsconfig for the auth/clerk Convex React TanStack-Start template
rg -nP -C2 '"paths"\s*:' apps/cli/templates/auth/clerk/convex/web/react/tanstack-start/tsconfig.json.hbs
sed -n '1,200p' apps/cli/templates/auth/clerk/convex/web/react/tanstack-start/tsconfig.json.hbs

Length of output: 445


Add TS path mapping for @{{projectName}}/backend/* or use a relative import
The tanstack-start template’s tsconfig.json.hbs only defines "@/*": ["./src/*"], so import { api } from "@{{projectName}}/backend/convex/_generated/api" will fail. In apps/cli/templates/auth/clerk/convex/web/react/tanstack-start, update tsconfig.json.hbs under compilerOptions.paths to include:

"paths": {
  "@/*": ["./src/*"],
  "@{{projectName}}/*": ["../backend/*"]
}

—or change the import in src/routes/dashboard.tsx.hbs to a relative path.

🤖 Prompt for AI Agents
In
apps/cli/templates/auth/clerk/convex/web/react/tanstack-start/src/routes/dashboard.tsx.hbs
around line 2, the import uses an aliased path "@{{projectName}}/backend/..."
that is not mapped by the template tsconfig; update the project's
tsconfig.json.hbs (compilerOptions.paths) to add a mapping for
"@{{projectName}}/*" -> "../backend/*" so the import resolves, or alternatively
change the import in this file to a correct relative path to the generated api
(e.g., traverse up to the backend folder) to avoid relying on an unmapped alias.

Comment on lines +15 to +17
function RouteComponent() {
const privateData = useQuery(api.privateData.get);
const user = useUser();

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.

🛠️ Refactor suggestion

Call Convex queries only after auth is ready; move hooks inside an -only child.

This avoids unauthorized query calls and UI flicker. Convex recommends rendering query hooks under <Authenticated> so the Convex auth token is loaded and validated before queries run. (docs.convex.dev)

Apply this diff:

 function RouteComponent() {
-	const privateData = useQuery(api.privateData.get);
-	const user = useUser();
+	// Defer queries & user lookup to <DashboardContent /> rendered under <Authenticated />
 
 	return (
 		<>
 			<Authenticated>
-				<div>
-					<h1>Dashboard</h1>
-					<p>Welcome {user.user?.fullName}</p>
-					<p>privateData: {privateData?.message}</p>
-					<UserButton />
-				</div>
+				<DashboardContent />
 			</Authenticated>

Add this component below the file (outside the selected range):

function DashboardContent() {
	const { user } = useUser();
	const privateData = useQuery(api.privateData.get);

	if (!privateData) return <div>Loading data...</div>;

	return (
		<div>
			<h1>Dashboard</h1>
			<p>Welcome {user?.user?.fullName}</p>
			<p>privateData: {privateData.message}</p>
			<UserButton />
		</div>
	);
}

Also applies to: 21-27

Comment on lines +100 to +121
const context = useRouteContext({ from: Route.id });
return (
<ClerkProvider>
<ConvexProviderWithClerk client={context.convexClient} useAuth={useAuth}>
<html lang="en" className="dark">
<head>
<HeadContent />
</head>
<body>
<div className="grid h-svh grid-rows-[auto_1fr]">
<Header />
{isFetching ? <Loader /> : <Outlet />}
</div>
<Toaster richColors />
<TanStackRouterDevtools position="bottom-left" />
<Scripts />
</body>
</html>
</ConvexProviderWithClerk>
</ClerkProvider>
);
{{else}}

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.

🛠️ Refactor suggestion

Pass Clerk publishable key to ClerkProvider

Explicitly wiring the publishable key avoids implicit env detection pitfalls and clearer error messages.

-    <ClerkProvider>
+    <ClerkProvider publishableKey={import.meta.env.VITE_CLERK_PUBLISHABLE_KEY}>

Optionally guard at build time by asserting the env var in the CLI scaffolding or README.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const context = useRouteContext({ from: Route.id });
return (
<ClerkProvider>
<ConvexProviderWithClerk client={context.convexClient} useAuth={useAuth}>
<html lang="en" className="dark">
<head>
<HeadContent />
</head>
<body>
<div className="grid h-svh grid-rows-[auto_1fr]">
<Header />
{isFetching ? <Loader /> : <Outlet />}
</div>
<Toaster richColors />
<TanStackRouterDevtools position="bottom-left" />
<Scripts />
</body>
</html>
</ConvexProviderWithClerk>
</ClerkProvider>
);
{{else}}
const context = useRouteContext({ from: Route.id });
return (
<ClerkProvider publishableKey={import.meta.env.VITE_CLERK_PUBLISHABLE_KEY}>
<ConvexProviderWithClerk client={context.convexClient} useAuth={useAuth}>
<html lang="en" className="dark">
<head>
<HeadContent />
</head>
<body>
<div className="grid h-svh grid-rows-[auto_1fr]">
<Header />
{isFetching ? <Loader /> : <Outlet />}
</div>
<Toaster richColors />
<TanStackRouterDevtools position="bottom-left" />
<Scripts />
</body>
</html>
</ConvexProviderWithClerk>
</ClerkProvider>
);
{{else}}
🤖 Prompt for AI Agents
In apps/cli/templates/frontend/react/tanstack-start/src/routes/__root.tsx.hbs
around lines 100 to 121, the ClerkProvider is instantiated without an explicit
publishable key; update the component to pass the publishableKey prop (sourced
from the appropriate env/runtime value or the route/context prop) so the app
does not rely on implicit env detection—ensure you read the key from a safe
source (e.g., process.env.CLERK_PUBLISHABLE_KEY or the existing context) and add
a brief build-time assertion or README note in the scaffolding to document/guard
that the env var must be set.

@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: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/cli/templates/auth/clerk/convex/native/base/(auth)/sign-out.tsx.hbs (1)

1-111: File name/content mismatch: this is a Sign-Up screen in a sign-out route

The file path is (auth)/sign-out.tsx.hbs but it implements a sign-up flow (SignUpScreen) and other templates link to /(auth)/sign-up. Rename the file to sign-up.tsx.hbs (and route) to prevent broken navigation and confusion.

🧹 Nitpick comments (12)
apps/cli/templates/auth/clerk/convex/native/base/(auth)/_layout.tsx.hbs (1)

5-12: Gate redirects on Clerk load to avoid flicker/false negatives

Add isLoaded and render nothing until auth state is known.

-export default function AuthRoutesLayout() {
-  const { isSignedIn } = useAuth();
+export default function AuthRoutesLayout() {
+  const { isSignedIn, isLoaded } = useAuth();
 
-  if (isSignedIn) {
+  if (!isLoaded) {
+    return null;
+  }
+
+  if (isSignedIn) {
     return <Redirect href={"/"} />;
   }
 
   return <Stack />;
 }
apps/cli/templates/auth/clerk/convex/native/base/components/sign-out-button.tsx.hbs (3)

1-3: Import React state for UX guard (pending sign-out)

-import { useClerk } from "@clerk/clerk-expo";
+import { useClerk } from "@clerk/clerk-expo";
 import { useRouter } from "expo-router";
 import { Text, TouchableOpacity } from "react-native";
+import React, { useState } from "react";

10-20: Debounce sign-out and handle pending state

-export const SignOutButton = () => {
+export const SignOutButton = () => {
   // Use `useClerk()` to access the `signOut()` function
   const { signOut } = useClerk();
   const router = useRouter();
+  const [pending, setPending] = useState(false);
 
   const handleSignOut = async () => {
     try {
-      await signOut();
+      if (pending) return;
+      setPending(true);
+      await signOut();
       // Redirect to your desired page
       router.replace("/");
     } catch (err) {
       // See https://clerk.com/docs/custom-flows/error-handling
       // for more info on error handling
-      console.error(JSON.stringify(err, null, 2));
+      console.error("Sign out failed");
+    } finally {
+      setPending(false);
     }
   };

22-26: Disable button while signing out

-  return (
-    <TouchableOpacity onPress={handleSignOut}>
+  return (
+    <TouchableOpacity onPress={handleSignOut} disabled={pending}>
       <Text>Sign out</Text>
     </TouchableOpacity>
   );
apps/cli/templates/auth/clerk/convex/native/base/(auth)/sign-in.tsx.hbs (3)

13-39: Prevent double-submit; show minimal pending guard

   // Handle the submission of the sign-in form
   const onSignInPress = async () => {
-    if (!isLoaded) return;
+    if (!isLoaded) return;
+    if (pending) return;
 
     // Start the sign-in process using the email and password provided
     try {
+      setPending(true);
       const signInAttempt = await signIn.create({
         identifier: emailAddress,
         password,
       });
@@
       } else {
         // If the status isn't complete, check why. User might need to
         // complete further steps.
         console.error(JSON.stringify(signInAttempt, null, 2));
       }
     } catch (err) {
       // See https://clerk.com/docs/custom-flows/error-handling
       // for more info on error handling
       console.error(JSON.stringify(err, null, 2));
-    }
+    } finally {
+      setPending(false);
+    }
   };

Add local state:

   const [emailAddress, setEmailAddress] = React.useState("");
   const [password, setPassword] = React.useState("");
+  const [pending, setPending] = React.useState(false);

44-55: Add input hints for better UX and platform autofill

       <TextInput
         autoCapitalize="none"
         value={emailAddress}
         placeholder="Enter email"
+        keyboardType="email-address"
+        autoCorrect={false}
+        autoComplete="email"
+        textContentType="emailAddress"
         onChangeText={(emailAddress) => setEmailAddress(emailAddress)}
       />
       <TextInput
         value={password}
         placeholder="Enter password"
         secureTextEntry={true}
+        textContentType="password"
+        autoComplete="password"
+        onSubmitEditing={onSignInPress}
         onChangeText={(password) => setPassword(password)}
       />

56-58: Disable submit while pending or not loaded

-      <TouchableOpacity onPress={onSignInPress}>
+      <TouchableOpacity onPress={onSignInPress} disabled={!isLoaded || pending}>
         <Text>Continue</Text>
       </TouchableOpacity>
apps/cli/templates/auth/clerk/convex/native/base/(auth)/sign-out.tsx.hbs (3)

15-39: Debounce sign-up; add pending state

   // Handle submission of sign-up form
   const onSignUpPress = async () => {
     if (!isLoaded) return;
 
-    console.log(emailAddress, password);
+    if (pending) return;
 
     // Start sign-up process using email and password provided
     try {
+      setPending(true);
       await signUp.create({
         emailAddress,
         password,
       });
@@
       // and capture OTP code
       setPendingVerification(true);
     } catch (err) {
       // See https://clerk.com/docs/custom-flows/error-handling
       // for more info on error handling
       console.error(JSON.stringify(err, null, 2));
-    }
+    } finally {
+      setPending(false);
+    }
   };

Add local state:

   const [pendingVerification, setPendingVerification] = React.useState(false);
   const [code, setCode] = React.useState("");
+  const [pending, setPending] = React.useState(false);

41-66: Debounce verification; add pending state and finally clause

   // Handle submission of verification form
   const onVerifyPress = async () => {
     if (!isLoaded) return;
+    if (pending) return;
 
     try {
+      setPending(true);
       // Use the code the user provided to attempt verification
       const signUpAttempt = await signUp.attemptEmailAddressVerification({
         code,
       });
@@
       // for more info on error handling
       console.error(JSON.stringify(err, null, 2));
-    }
+    } finally {
+      setPending(false);
+    }
   };

84-109: Improve inputs and disable buttons while pending

       <TextInput
         autoCapitalize="none"
         value={emailAddress}
         placeholder="Enter email"
+        keyboardType="email-address"
+        autoCorrect={false}
+        autoComplete="email"
+        textContentType="emailAddress"
         onChangeText={(email) => setEmailAddress(email)}
       />
       <TextInput
         value={password}
         placeholder="Enter password"
         secureTextEntry={true}
+        textContentType="password"
+        autoComplete="password"
+        onSubmitEditing={onSignUpPress}
         onChangeText={(password) => setPassword(password)}
       />
-      <TouchableOpacity onPress={onSignUpPress}>
+      <TouchableOpacity onPress={onSignUpPress} disabled={!isLoaded || pending}>
         <Text>Continue</Text>
       </TouchableOpacity>
-      <View style={{ display: "flex", flexDirection: "row", gap: 3 }}>
+      <View style={{ display: "flex", flexDirection: "row" }}>
         <Text>Already have an account?</Text>
-        <Link href="/sign-in">
+        <Link href="/sign-in" style={{ marginLeft: 3 }}>
           <Text>Sign in</Text>
         </Link>
       </View>
apps/cli/templates/frontend/native/nativewind/app/(drawer)/index.tsx.hbs (1)

32-39: Align Convex hook usage with alias to avoid conflicts.

If you adopt the aliasing above, update calls here.

-  const { user } = useUser();
-  const healthCheck = useQuery(api.healthCheck.get);
-  const privateData = useQuery(api.privateData.get);
+  const { user } = useUser();
+  const healthCheck = useConvexQuery(api.healthCheck.get);
+  const privateData = useConvexQuery(api.privateData.get);
apps/cli/templates/frontend/native/nativewind/app/_layout.tsx.hbs (1)

81-84: Optional: guard missing publishable key early.

Helpful during template adoption to fail fast with a clear message.

-    <ClerkProvider
-      tokenCache={tokenCache}
-      publishableKey={process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY}
-    >
+    {(() => {
+      if (!process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY) {
+        console.error("Missing EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY");
+      }
+      return (
+        <ClerkProvider
+          tokenCache={tokenCache}
+          publishableKey={process.env.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY!}
+        >
+      );
+    })()}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e4c2b5f and da9f8cd.

📒 Files selected for processing (8)
  • apps/cli/templates/auth/clerk/convex/native/base/(auth)/_layout.tsx.hbs (1 hunks)
  • apps/cli/templates/auth/clerk/convex/native/base/(auth)/sign-in.tsx.hbs (1 hunks)
  • apps/cli/templates/auth/clerk/convex/native/base/(auth)/sign-out.tsx.hbs (1 hunks)
  • apps/cli/templates/auth/clerk/convex/native/base/components/sign-out-button.tsx.hbs (1 hunks)
  • apps/cli/templates/frontend/native/nativewind/app/(drawer)/index.tsx.hbs (3 hunks)
  • apps/cli/templates/frontend/native/nativewind/app/_layout.tsx.hbs (3 hunks)
  • apps/cli/templates/frontend/native/unistyles/app/(drawer)/index.tsx.hbs (3 hunks)
  • apps/cli/templates/frontend/native/unistyles/app/_layout.tsx.hbs (3 hunks)
🔇 Additional comments (7)
apps/cli/templates/auth/clerk/convex/native/base/(auth)/sign-in.tsx.hbs (1)

59-65: Clarify React Native version support or replace gap
The gap style prop requires React Native ≥ 0.71 (or Expo SDK 49); since this template is consumed by downstream projects with unknown RN/Expo versions, either 1) document that generated apps must target RN ≥ 0.71/Expo 49 or 2) avoid gap and use a margin-based fallback (e.g., add marginLeft: 3 on the <Link>).

Likely an incorrect or invalid review comment.

apps/cli/templates/frontend/native/unistyles/app/_layout.tsx.hbs (3)

12-16: Confirm Clerk Expo token cache import path/version.

Some setups expose createTokenCache in "@clerk/clerk-expo" and not a ready-made token-cache module. Verify your targeted @clerk/clerk-expo version supports @clerk/clerk-expo/token-cache; otherwise, switch to createTokenCache + SecureStore.

If needed, here’s the fallback pattern (outside selected lines):

import { ClerkProvider, useAuth, createTokenCache } from "@clerk/clerk-expo";
import * as SecureStore from "expo-secure-store";

const tokenCache = createTokenCache({
  getItem: (key) => SecureStore.getItemAsync(key),
  setItem: (key, value) => SecureStore.setItemAsync(key, value),
});

42-70: Clerk + Convex provider wiring looks correct.

Provider order and props (useAuth, client, tokenCache, publishableKey) align with Convex/Clerk Expo patterns. Screens include (auth) only under Clerk, avoiding route leaks elsewhere.


92-92: Balanced Handlebars blocks.

New inner {{#if (eq auth "clerk")}} branch is properly closed before the outer convex branch continues.

apps/cli/templates/frontend/native/nativewind/app/(drawer)/index.tsx.hbs (1)

13-18: Potential useQuery import collision.

This branch imports useQuery from convex/react while earlier branches may import useQuery from @tanstack/react-query. If the CLI ever allows api (trpc/orpc) together with backend="convex", this will shadow and/or break. Either enforce mutual exclusivity at generation time or alias Convex’s hook.

Optional alias to harden the template:

-import { Authenticated, AuthLoading, Unauthenticated, useQuery } from "convex/react";
+import { Authenticated, AuthLoading, Unauthenticated, useQuery as useConvexQuery } from "convex/react";

And update usage below accordingly (see next comment).

apps/cli/templates/frontend/native/nativewind/app/_layout.tsx.hbs (2)

6-10: Confirm Clerk Expo token cache import path/version.

As with the Unistyles layout, ensure your @clerk/clerk-expo version exposes @clerk/clerk-expo/token-cache; otherwise, switch to createTokenCache + SecureStore.

(See suggested fallback snippet in the other file’s comment.)


80-101: Clerk + Convex provider composition looks good.

Correct wrapper order, props, and addition of the (auth) stack only in the Clerk branch. Theme/StatusBar/gesture setup preserved.

const onSignUpPress = async () => {
if (!isLoaded) return;

console.log(emailAddress, password);

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.

⚠️ Potential issue

Remove plaintext credential logging

-    console.log(emailAddress, password);
+    // Do not log credentials.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.log(emailAddress, password);
// Do not log credentials.
🤖 Prompt for AI Agents
In apps/cli/templates/auth/clerk/convex/native/base/(auth)/sign-out.tsx.hbs
around line 19, remove the console.log(emailAddress, password) that prints
plaintext credentials and replace it with a non-sensitive log or no log at all
(e.g., log only event metadata or a masked/boolean status). Ensure no sensitive
data (passwords, full emails) is output to logs and, if necessary, use a secure
auditing mechanism instead of console.log.

Comment on lines +52 to 53
healthCheck ? "bg-green-500" : "bg-orange-500"
}`}

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.

⚠️ Potential issue

Fix status color logic (currently marks any non-empty string as green).

healthCheck is a string; checking truthiness turns "ERROR" into green. Compare explicitly to "OK".

-                healthCheck ? "bg-green-500" : "bg-orange-500"
+                healthCheck === "OK" ? "bg-green-500" : "bg-orange-500"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
healthCheck ? "bg-green-500" : "bg-orange-500"
}`}
healthCheck === "OK" ? "bg-green-500" : "bg-orange-500"
}`}
🤖 Prompt for AI Agents
In apps/cli/templates/frontend/native/nativewind/app/(drawer)/index.tsx.hbs
around lines 52 to 53, the status color uses truthiness of the string which
treats any non-empty value (e.g., "ERROR") as true; change the conditional to
explicitly compare healthCheck === "OK" (use strict equality) so only the "OK"
string maps to "bg-green-500" and all other values map to "bg-orange-500".

Comment on lines +106 to +123
{{#if (and (eq backend "convex") (eq auth "clerk"))}}
<Authenticated>
<Text>Hello {user?.emailAddresses[0].emailAddress}</Text>
<Text>Private Data: {privateData?.message}</Text>
<SignOutButton />
</Authenticated>
<Unauthenticated>
<Link href="/(auth)/sign-in">
<Text>Sign in</Text>
</Link>
<Link href="/(auth)/sign-up">
<Text>Sign up</Text>
</Link>
</Unauthenticated>
<AuthLoading>
<Text>Loading...</Text>
</AuthLoading>
{{/if}}

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.

⚠️ Potential issue

Avoid possible undefined access on user email.

user?.emailAddresses[0].emailAddress can throw when the array is empty. Use optional chaining (and prefer primaryEmailAddress when present).

-          <Text>Hello {user?.emailAddresses[0].emailAddress}</Text>
+          <Text>
+            Hello {user?.primaryEmailAddress?.emailAddress ?? user?.emailAddresses[0]?.emailAddress}
+          </Text>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{{#if (and (eq backend "convex") (eq auth "clerk"))}}
<Authenticated>
<Text>Hello {user?.emailAddresses[0].emailAddress}</Text>
<Text>Private Data: {privateData?.message}</Text>
<SignOutButton />
</Authenticated>
<Unauthenticated>
<Link href="/(auth)/sign-in">
<Text>Sign in</Text>
</Link>
<Link href="/(auth)/sign-up">
<Text>Sign up</Text>
</Link>
</Unauthenticated>
<AuthLoading>
<Text>Loading...</Text>
</AuthLoading>
{{/if}}
{{#if (and (eq backend "convex") (eq auth "clerk"))}}
<Authenticated>
<Text>
Hello {user?.primaryEmailAddress?.emailAddress ?? user?.emailAddresses[0]?.emailAddress}
</Text>
<Text>Private Data: {privateData?.message}</Text>
<SignOutButton />
</Authenticated>
<Unauthenticated>
<Link href="/(auth)/sign-in">
<Text>Sign in</Text>
</Link>
<Link href="/(auth)/sign-up">
<Text>Sign up</Text>
</Link>
</Unauthenticated>
<AuthLoading>
<Text>Loading...</Text>
</AuthLoading>
{{/if}}
🤖 Prompt for AI Agents
In apps/cli/templates/frontend/native/nativewind/app/(drawer)/index.tsx.hbs
around lines 106 to 123, the template directly accesses
user?.emailAddresses[0].emailAddress which can throw if emailAddresses is empty;
change the displayed email to safely prefer user?.primaryEmailAddress and
otherwise fall back to the first address using optional chaining (e.g. use
user?.primaryEmailAddress ?? user?.emailAddresses?.[0]?.emailAddress), ensuring
you guard for undefined before rendering.

Comment on lines +37 to +40
const privateData = useQuery(api.privateData.get);
{{else}}
const healthCheck = useQuery(api.healthCheck.get);
{{/if}}

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.

🛠️ Refactor suggestion

Don’t call private queries when unauthenticated; skip until user is present

-  const privateData = useQuery(api.privateData.get);
+  // Skip the query until a user exists to avoid unnecessary errors/logs.
+  const privateData = useQuery(api.privateData.get, user ? {} : undefined);

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/cli/templates/frontend/native/unistyles/app/(drawer)/index.tsx.hbs
around lines 37-40, the template unconditionally calls the private data query
when the user is not authenticated; modify the code to avoid executing private
queries until a user exists by adding a conditional enabled flag or conditional
rendering: for example, call useQuery(api.privateData.get, { enabled: !!user })
(or wrap the hook/usage in an if (user) block) so the private query is skipped
when user is falsy, and keep the healthCheck query for the unauthenticated
branch as-is.

Comment on lines +124 to +126
<Text>Hello {user?.emailAddresses[0].emailAddress}</Text>
<Text>Private Data: {privateData?.message}</Text>
<SignOutButton />

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.

⚠️ Potential issue

Optional-chain through arrays to avoid runtime crash when user has no email

-          <Text>Hello {user?.emailAddresses[0].emailAddress}</Text>
+          <Text>
+            Hello {user?.primaryEmailAddress?.emailAddress ?? user?.emailAddresses?.[0]?.emailAddress ?? "there"}
+          </Text>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<Text>Hello {user?.emailAddresses[0].emailAddress}</Text>
<Text>Private Data: {privateData?.message}</Text>
<SignOutButton />
<Text>
Hello {user?.primaryEmailAddress?.emailAddress ?? user?.emailAddresses?.[0]?.emailAddress ?? "there"}
</Text>
<Text>Private Data: {privateData?.message}</Text>
<SignOutButton />
🤖 Prompt for AI Agents
In apps/cli/templates/frontend/native/unistyles/app/(drawer)/index.tsx.hbs
around lines 124 to 126, accessing user.emailAddresses[0].emailAddress can crash
when emailAddresses is empty or undefined; update the JSX to safely
optional-chain through the array (e.g. user?.emailAddresses?.[0]?.emailAddress)
so it renders undefined instead of throwing, leaving the existing
privateData?.message and SignOutButton as-is.

@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

🧹 Nitpick comments (1)
apps/cli/src/constants.ts (1)

46-49: Pin Clerk dependencies to exact versions
Update apps/cli/src/constants.ts to drop the carets and pin these four entries for reproducible CLI scaffolds (they’re referenced by auth-setup and templates):

-  "@clerk/nextjs": "^6.31.5",
-  "@clerk/clerk-react": "^5.45.0",
-  "@clerk/tanstack-react-start": "^0.23.1",
-  "@clerk/clerk-expo": "^2.14.25",
+  "@clerk/nextjs": "6.31.5",
+  "@clerk/clerk-react": "5.45.0",
+  "@clerk/tanstack-react-start": "0.23.1",
+  "@clerk/clerk-expo": "2.14.25",

No peerDependencies in our templates reference these, so no additional changes are needed.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between da9f8cd and 28c5b8e.

📒 Files selected for processing (6)
  • apps/cli/src/constants.ts (2 hunks)
  • apps/cli/src/helpers/core/auth-setup.ts (3 hunks)
  • apps/cli/src/helpers/core/env-setup.ts (3 hunks)
  • apps/cli/src/helpers/core/template-manager.ts (6 hunks)
  • apps/cli/templates/frontend/native/nativewind/package.json.hbs (1 hunks)
  • apps/cli/templates/frontend/native/unistyles/package.json.hbs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/cli/src/helpers/core/auth-setup.ts
  • apps/cli/src/helpers/core/env-setup.ts
  • apps/cli/src/helpers/core/template-manager.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/convex_rules.mdc)

**/*.{ts,tsx}: Use Id from './_generated/dataModel' to type document ids (e.g., Id<'users'>)
Ensure Record key/value types align with validators (e.g., v.record(v.id('users'), v.string()) => Record<Id<'users'>, string>)
Be strict with types for document ids; prefer Id<'table'> over string
Use 'as const' for string literals in discriminated unions
When using Array and Record types, declare with explicit generic types (e.g., const arr: Array = ...)

Files:

  • apps/cli/src/constants.ts
**/*.{js,jsx,ts,tsx,mjs,cjs}

📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)

**/*.{js,jsx,ts,tsx,mjs,cjs}: Do not use dotenv; Bun auto-loads .env
Use Bun.serve() for HTTP/WebSockets; do not use express
Use bun:sqlite for SQLite; do not use better-sqlite3
Use Bun.redis for Redis; do not use ioredis
Use Bun.sql for Postgres; do not use pg or postgres.js
Use built-in WebSocket; do not use ws
Prefer Bun.file over node:fs readFile/writeFile
Use Bun.$ instead of execa for shelling out

Files:

  • apps/cli/src/constants.ts
🔇 Additional comments (4)
apps/cli/templates/frontend/native/nativewind/package.json.hbs (2)

25-25: Good call adding expo-crypto for RN crypto primitives.
This unblocks RNG/digest needs likely introduced by Clerk/Convex on native. No issues spotted with the semver range for Expo SDK 53.


25-25: expo-crypto suffices; no WebCrypto polyfill needed
Searches in apps/cli/templates/frontend/native found no references to jose or crypto.subtle, so expo-crypto alone is adequate.

apps/cli/templates/frontend/native/unistyles/package.json.hbs (2)

24-24: Addition looks correct and consistent with Expo SDK 53.
expo-crypto at ~14.1.5 aligns with the surrounding dependency matrix; no conflicts obvious.


24-24: Double-check ecosystem requirements for Clerk + Convex on RN.
If token/JWT verification or key operations rely on SubtleCrypto, add a proper WebCrypto polyfill; expo-crypto won’t set globalThis.crypto.subtle. Validate before merging to avoid runtime failures.

Use the same script from the sibling template comment to scan for jose/WebCrypto usage and ensure a matching polyfill is present.

Comment thread apps/cli/src/constants.ts
database: "sqlite",
orm: "drizzle",
auth: true,
auth: "better-auth",

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.

💡 Verification agent

🧩 Analysis chain

Good switch to discriminated union default for auth; verify there are no boolean remnants.

Setting auth: "better-auth" with the enclosing as const is correct. Please ensure all CLI types, prompts, and templates no longer treat auth as boolean.

Run to catch leftovers:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# 1) Any stale boolean defaults?
rg -nP --glob '!**/node_modules/**' '\bauth\s*:\s*(true|false)\b' -C2

# 2) Any lingering zod boolean schema?
rg -nP --glob '!**/node_modules/**' 'z\.boolean\(\)' apps/cli/src -C2

# 3) Conditionals still treating `auth` as truthy/falsey checks
rg -nP --glob '!**/node_modules/**' '(if\s*\(|\?\s*).*?\.auth\b(?!\s*===|\s*!==)' apps/cli/src -n -C2

# 4) Confirm new allowed values appear
rg -nP --glob '!**/node_modules/**' '"better-auth"|"clerk"|"none"' -n -C1

Length of output: 164051


Update CLI docs to use string-based auth instead of boolean
In apps/web/content/docs/cli/programmatic-api.mdx (around lines 36, 272, 289), replace all auth: true examples with the appropriate union values ("better-auth" | "clerk" | "none") and update the auth?: boolean declaration to reflect the new Auth enum (auth?: "better-auth" | "clerk" | "none").

🤖 Prompt for AI Agents
In apps/cli/src/constants.ts around line 16, the auth constant is currently set
as a string but the codebase and docs expect an explicit Auth union type; update
the exported type/constant defs and any related declarations so that auth is
typed as the union "better-auth" | "clerk" | "none" (instead of boolean) and
ensure exports and usages reflect that enum; then update the CLI docs examples
in apps/web/content/docs/cli/programmatic-api.mdx (around lines 36, 272, 289) to
replace all occurrences of auth: true with an appropriate string literal from
the union ("better-auth" | "clerk" | "none") and change any type declarations of
auth?: boolean to auth?: "better-auth" | "clerk" | "none".

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/cli/templates/auth/clerk/convex/native/base/app/(auth)/sign-out.tsx.hbs (1)

1-111: File purpose/content mismatch: this “sign-out” route implements sign-up.

The file path indicates a sign-out screen, but it exports SignUpScreen with a full sign-up flow. This will confuse routing and users.

Two options:

  • Rename this file to sign-up.tsx.hbs and add a real sign-out screen separately.
  • Or replace content with an actual sign-out screen. Suggested replacement:
-// (current file implements sign-up)
+import * as React from "react";
+import { Text, View } from "react-native";
+import { useClerk } from "@clerk/clerk-expo";
+import { useRouter } from "expo-router";
+
+export default function SignOutScreen() {
+  const { signOut } = useClerk();
+  const router = useRouter();
+
+  React.useEffect(() => {
+    (async () => {
+      try {
+        await signOut();
+      } catch (err) {
+        console.error(JSON.stringify(err, null, 2));
+      } finally {
+        router.replace("/sign-in");
+      }
+    })();
+  }, [signOut, router]);
+
+  return (
+    <View>
+      <Text>Signing you out…</Text>
+    </View>
+  );
+}
♻️ Duplicate comments (1)
apps/cli/src/utils/config-validation.ts (1)

187-191: Block “better-auth” for Convex; only Clerk or None should be allowed

Add a guard so that when backend === "convex", auth must be "clerk" or "none". This prevents “better-auth” from slipping through.

   if (config.auth === "clerk" && backend !== "convex") {
     exitWithError(
       "Clerk authentication is only supported with the Convex backend. Please use '--backend convex' or choose a different auth provider.",
     );
   }
+
+  if (
+    backend === "convex" &&
+    config.auth &&
+    config.auth !== "clerk" &&
+    config.auth !== "none"
+  ) {
+    exitWithError(
+      "For '--backend convex', only '--auth clerk' or '--auth none' are supported.",
+    );
+  }
🧹 Nitpick comments (8)
apps/cli/src/utils/config-validation.ts (1)

69-79: Deduplicate “auth requires database” checks

Two adjacent checks enforce the same rule; keep one to avoid confusion and double maintenance.

-  if (
-    has("auth") &&
-    has("database") &&
-    cfg.auth !== "none" &&
-    db === "none" &&
-    cfg.backend !== "convex"
-  ) {
-    exitWithError(
-      "Authentication requires a database. Please choose a database or set '--auth none'.",
-    );
-  }
+  // Keep the single, unconditional check below.

Also applies to: 81-85

apps/cli/templates/auth/clerk/convex/native/base/app/(auth)/_layout.tsx.hbs (1)

4-12: Gate on isLoaded to avoid flicker and premature redirects.

Until Clerk finishes loading, isSignedIn can be undefined. Short-circuit on isLoaded before redirecting or rendering.

-export default function AuthRoutesLayout() {
-  const { isSignedIn } = useAuth();
+export default function AuthRoutesLayout() {
+  const { isLoaded, isSignedIn } = useAuth();
 
-  if (isSignedIn) {
+  if (!isLoaded) return null;
+  if (isSignedIn) {
-    return <Redirect href={"/"} />;
+    return <Redirect href="/" />;
   }
 
   return <Stack />;
 }
apps/cli/templates/auth/clerk/convex/native/base/app/(auth)/sign-in.tsx.hbs (2)

59-64: React Native style: avoid gap (inconsistent support); remove redundant display.

Use margins or rowGap (if your RN/Expo version supports it). display: "flex" is default in RN.

-      <View style=\{{ display: "flex", flexDirection: "row", gap: 3 }}>
+      <View style=\{{ flexDirection: "row", alignItems: "center" }}>
         <Text>Don't have an account?</Text>
         <Link href="/sign-up">
-          <Text>Sign up</Text>
+          <Text style=\{{ marginLeft: 8 }}>Sign up</Text>
         </Link>
       </View>

41-58: Small UX hardening: disable submit until ready.

Prevent accidental taps before Clerk is loaded or fields are empty.

-      <TouchableOpacity onPress={onSignInPress}>
+      <TouchableOpacity
+        onPress={onSignInPress}
+        disabled={!isLoaded || !emailAddress || !password}
+      >
         <Text>Continue</Text>
       </TouchableOpacity>
apps/cli/templates/auth/clerk/convex/native/base/app/(auth)/sign-out.tsx.hbs (1)

84-107: RN style: avoid gap; remove redundant display.

Same issue as sign-in. Use margins or supported row/column gap props per RN version.

-      <View style=\{{ display: "flex", flexDirection: "row", gap: 3 }}>
+      <View style=\{{ flexDirection: "row", alignItems: "center" }}>
         <Text>Already have an account?</Text>
-        <Link href="/sign-in">
-          <Text>Sign in</Text>
+        <Link href="/sign-in">
+          <Text style=\{{ marginLeft: 8 }}>Sign in</Text>
         </Link>
       </View>
apps/cli/src/helpers/core/template-manager.ts (3)

425-458: Reuse computed flags; avoid shadowing locals.

hasNativeWind/hasUnistyles are recomputed here, shadowing the earlier values (Lines 381–383). Reuse the existing booleans to reduce drift.

-      const hasNativeWind = context.frontend.includes("native-nativewind");
-      const hasUnistyles = context.frontend.includes("native-unistyles");
       let nativeFrameworkPath = "";
-      if (hasNativeWind) nativeFrameworkPath = "nativewind";
-      else if (hasUnistyles) nativeFrameworkPath = "unistyles";
+      if (hasNativeWind) nativeFrameworkPath = "nativewind";
+      else if (hasUnistyles) nativeFrameworkPath = "unistyles";

517-574: React web provider paths: centralize the framework set.

The list of React frameworks is repeated across functions. Extract a shared constant (e.g., const REACT_FW = new Set([...])) to avoid future drift.


576-611: Native provider paths: LGTM; add guard logs for missing dirs.

Silent skips can confuse users. Consider a small logger when expected provider/native dirs are missing.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 28c5b8e and 39aa67d.

📒 Files selected for processing (6)
  • apps/cli/src/helpers/core/template-manager.ts (7 hunks)
  • apps/cli/src/utils/compatibility-rules.ts (4 hunks)
  • apps/cli/src/utils/config-validation.ts (2 hunks)
  • apps/cli/templates/auth/clerk/convex/native/base/app/(auth)/_layout.tsx.hbs (1 hunks)
  • apps/cli/templates/auth/clerk/convex/native/base/app/(auth)/sign-in.tsx.hbs (1 hunks)
  • apps/cli/templates/auth/clerk/convex/native/base/app/(auth)/sign-out.tsx.hbs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/cli/src/utils/compatibility-rules.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/convex_rules.mdc)

**/*.{ts,tsx}: Use Id from './_generated/dataModel' to type document ids (e.g., Id<'users'>)
Ensure Record key/value types align with validators (e.g., v.record(v.id('users'), v.string()) => Record<Id<'users'>, string>)
Be strict with types for document ids; prefer Id<'table'> over string
Use 'as const' for string literals in discriminated unions
When using Array and Record types, declare with explicit generic types (e.g., const arr: Array = ...)

Files:

  • apps/cli/src/utils/config-validation.ts
  • apps/cli/src/helpers/core/template-manager.ts
**/*.{js,jsx,ts,tsx,mjs,cjs}

📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)

**/*.{js,jsx,ts,tsx,mjs,cjs}: Do not use dotenv; Bun auto-loads .env
Use Bun.serve() for HTTP/WebSockets; do not use express
Use bun:sqlite for SQLite; do not use better-sqlite3
Use Bun.redis for Redis; do not use ioredis
Use Bun.sql for Postgres; do not use pg or postgres.js
Use built-in WebSocket; do not use ws
Prefer Bun.file over node:fs readFile/writeFile
Use Bun.$ instead of execa for shelling out

Files:

  • apps/cli/src/utils/config-validation.ts
  • apps/cli/src/helpers/core/template-manager.ts
🧬 Code graph analysis (2)
apps/cli/src/utils/config-validation.ts (1)
apps/cli/src/utils/errors.ts (1)
  • exitWithError (9-15)
apps/cli/src/helpers/core/template-manager.ts (1)
apps/cli/src/constants.ts (1)
  • PKG_ROOT (8-8)
🔇 Additional comments (4)
apps/cli/src/helpers/core/template-manager.ts (4)

365-365: Early exit for auth: "none" is correct.


462-515: Provider-scoped server templates: good separation; confirm Next-only branch.

Branching server/next only when context.backend === "next" is correct. Ensure other backends (e.g., h3, hono, etc., if supported) either have provider paths or are intentionally omitted.


403-423: All targeted React framework templates are present — no silent no-op risk. Verified that apps/cli/templates/auth/clerk/convex/web/react/{tanstack-router,react-router,tanstack-start,next} all exist; no changes needed.


385-460: No file collisions detected between base Convex backend and Clerk overlay. Verified that the two template directories contain distinct files, so there’s no risk of order-dependent overwrites.

Comment on lines +19 to +21
console.log(emailAddress, password);

// Start sign-up process using email and password provided

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.

⚠️ Potential issue

PII leakage: avoid logging credentials.

console.log(emailAddress, password) leaks sensitive data to device logs.

-    console.log(emailAddress, password);
+    // Avoid logging PII (email/password)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.log(emailAddress, password);
// Start sign-up process using email and password provided
// Avoid logging PII (email/password)
// Start sign-up process using email and password provided
🤖 Prompt for AI Agents
In apps/cli/templates/auth/clerk/convex/native/base/app/(auth)/sign-out.tsx.hbs
around lines 19 to 21, remove the console.log(emailAddress, password) which
exposes sensitive PII; instead delete the log or replace it with a non-sensitive
debug message (e.g., generic "sign-out initiated" or use a conditional telemetry
call that never includes raw credentials) and ensure no other credential
variables are logged or persisted.

@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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (5)
apps/web/scripts/generate-analytics.ts (5)

245-250: Auth enum migration not reflected; metrics will be wrong.

CSV now emits "better-auth" | "clerk" | "none" (was boolean). Current logic collapses everything to enabled/disabled and breaks authEnabledPercent and distributions.

Apply:

-            // Auth
-            const auth =
-              row["*.properties.auth"] === "True" ? "enabled" : "disabled";
-            authCounts[auth] = (authCounts[auth] || 0) + 1;
-            if (auth === "enabled") authEnabledCount++;
+            // Auth (supports enum + legacy booleans)
+            const rawAuth = (row["*.properties.auth"] || "").toLowerCase();
+            let authCategory: "better-auth" | "clerk" | "none";
+            if (rawAuth === "better-auth" || rawAuth === "clerk" || rawAuth === "none") {
+              authCategory = rawAuth as "better-auth" | "clerk" | "none";
+            } else if (rawAuth === "true" || rawAuth === "1" || rawAuth === "enabled") {
+              // Legacy boolean => assume prior default provider
+              authCategory = "better-auth";
+            } else {
+              authCategory = "none";
+            }
+            authCounts[authCategory] = (authCounts[authCategory] || 0) + 1;
+            if (authCategory !== "none") authEnabledCount++;

382-389: Use toLocaleString; toLocaleDateString ignores hour/minute.

Time fields are silently dropped today.

Apply:

-                lastUpdated = mostRecentDate.toLocaleDateString("en-US", {
+                lastUpdated = mostRecentDate.toLocaleString("en-US", {
                   year: "numeric",
                   month: "short",
                   day: "numeric",
                   hour: "2-digit",
                   minute: "2-digit",
                   timeZone: "UTC",
                 });

359-367: Guard empty/invalid CSV before accessing header.

Prevents crash on empty body or malformed first line.

Apply:

-    const lines = csvText.split("\n");
-    const timestampColumn = lines[0]
-      .split(",")
-      .findIndex((header) => header.includes("timestamp"));
+    const lines = (csvText || "").split("\n");
+    let timestampColumn = -1;
+    if (lines[0]) {
+      timestampColumn = lines[0]
+        .split(",")
+        .findIndex((header) => header.includes("timestamp"));
+    }

393-429: Time-series generation crashes when there are zero valid dates.

Add empty-dataset guard; keep output stable.

Apply:

-    // Process time series data
-    const dates = Object.keys(dateCounts).sort();
-    const startDate = new Date(dates[0]);
-    const endDate = new Date(dates[dates.length - 1]);
-    const today = new Date();
-    const actualEndDate = endDate > today ? today : endDate;
-    const daysDiff = Math.ceil(
-      (actualEndDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24),
-    );
-    const maxDays = 60;
-
-    let finalStartDate = startDate;
-    if (daysDiff > maxDays) {
-      finalStartDate = new Date(
-        actualEndDate.getTime() - maxDays * 24 * 60 * 60 * 1000,
-      );
-    }
-
-    const timeSeries: Array<{
-      date: string;
-      displayDate: string;
-      count: number;
-    }> = [];
-    const currentDate = new Date(finalStartDate);
-    while (currentDate <= actualEndDate) {
-      const dateStr = currentDate.toISOString().split("T")[0];
-      timeSeries.push({
-        date: dateStr,
-        displayDate: currentDate.toLocaleDateString("en-US", {
-          month: "short",
-          day: "numeric",
-        }),
-        count: dateCounts[dateStr] || 0,
-      });
-      currentDate.setDate(currentDate.getDate() + 1);
-    }
+    // Process time series data (handle empty dataset)
+    const dates = Object.keys(dateCounts).sort();
+    const timeSeries: Array<{ date: string; displayDate: string; count: number }> = [];
+    if (dates.length > 0) {
+      const startDate = new Date(dates[0]);
+      const endDate = new Date(dates[dates.length - 1]);
+      const today = new Date();
+      const actualEndDate = endDate > today ? today : endDate;
+      const daysDiff = Math.ceil(
+        (actualEndDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24),
+      );
+      const maxDays = 60;
+      let finalStartDate = startDate;
+      if (daysDiff > maxDays) {
+        finalStartDate = new Date(
+          actualEndDate.getTime() - maxDays * 24 * 60 * 60 * 1000,
+        );
+      }
+      const currentDate = new Date(finalStartDate);
+      while (currentDate <= actualEndDate) {
+        const dateStr = currentDate.toISOString().split("T")[0];
+        timeSeries.push({
+          date: dateStr,
+          displayDate: currentDate.toLocaleDateString("en-US", {
+            month: "short",
+            day: "numeric",
+          }),
+          count: dateCounts[dateStr] || 0,
+        });
+        currentDate.setDate(currentDate.getDate() + 1);
+      }
+    }

574-579: Make bucket configurable via env; align with repo env-loading policy.

Avoid hardcoding; Bun/Node load env without dotenv here.

Apply:

-    const BUCKET_NAME = "bucket";
+    const BUCKET_NAME = process.env.R2_BUCKET_NAME ?? "bucket";
♻️ Duplicate comments (3)
apps/web/src/app/(home)/analytics/page.tsx (1)

3-9: Harden server fetch: add route revalidate, timeout, response.ok guard, and null fallback.

Prevents build-time cache surprises and runtime crashes; aligns with the prior bot suggestion (updated host).

+export const revalidate = 1800; // 30 minutes for this route
+import type { AggregatedAnalyticsData } from "./_components/types"; // adjust path to where the type lives
 import AnalyticsPage from "./_components/analytics-page";
 
 export default async function Analytics() {
-	const response = await fetch(
-		"https://r2.better-t-stack.dev/analytics-data.json",
-	);
-	const analyticsData = await response.json();
+	const controller = new AbortController();
+	const timeout = setTimeout(() => controller.abort(), 5000);
+	let analyticsData: AggregatedAnalyticsData | null = null;
+	try {
+		const response = await fetch(
+			"https://r2.better-t-stack.dev/analytics-data.json",
+			{ next: { revalidate }, signal: controller.signal },
+		);
+		if (response.ok) {
+			analyticsData = (await response.json()) as AggregatedAnalyticsData;
+		}
+	} catch {
+		analyticsData = null;
+	} finally {
+		clearTimeout(timeout);
+	}
 
 	return <AnalyticsPage data={analyticsData} />;
 }
apps/cli/src/utils/config-validation.ts (1)

206-210: Future-proof Convex auth constraint: allowlist instead of single disallow

This blocks “better-auth” today but may let future providers slip through. Prefer an allowlist for Convex.

-if (backend === "convex" && config.auth === "better-auth") {
-  exitWithError(
-    "Better-Auth is not compatible with the Convex backend. Please use '--auth clerk' or '--auth none'.",
-  );
-}
+if (
+  backend === "convex" &&
+  config.auth &&
+  config.auth !== "clerk" &&
+  config.auth !== "none"
+) {
+  exitWithError(
+    "For '--backend convex', only '--auth clerk' or '--auth none' are supported.",
+  );
+}
apps/web/src/app/(home)/_components/stack-builder.tsx (1)

1188-1191: Always emit --auth flag (also for Convex).

Auth flag emission remains inside the non-Convex guard, so --auth clerk isn’t emitted for Convex.

-    if (!checkDefault("auth", stackState.auth)) {
-      flags.push(`--auth ${stackState.auth}`);
-    }
@@
-  } else {
-  }
+  } else {
+  }
+
+  // Emit auth flag for any backend when it differs from default.
+  if (!checkDefault("auth", stackState.auth)) {
+    flags.push(`--auth ${stackState.auth}`);
+  }
🧹 Nitpick comments (8)
apps/cli/src/utils/config-validation.ts (2)

81-85: Reuse the computed predicate to avoid drift with the block above

Keep the unconditional check, but reuse the same predicate.

-if (cfg.auth !== "none" && db === "none" && cfg.backend !== "convex") {
+if (needsDbForAuth) {
   exitWithError(
     "Authentication requires a database. Please choose a database or set '--auth none'.",
   );
 }

193-204: Align frontend validation with flag gating for consistency

Elsewhere (Lines 239-253) frontend checks are gated by providedFlags.has("frontend") and use options.frontend. Mirror that here to avoid surprising errors when the frontend wasn’t explicitly set.

-if (backend === "convex" && config.auth === "clerk" && config.frontend) {
-  const incompatibleFrontends = config.frontend.filter((f) =>
+if (
+  backend === "convex" &&
+  config.auth === "clerk" &&
+  providedFlags.has("frontend") &&
+  options.frontend
+) {
+  const incompatibleFrontends = options.frontend.filter((f) =>
     ["nuxt", "svelte", "solid"].includes(f),
   );

Optional: consider deduping the “solid on Convex” rule with the general Convex/frontend check to keep a single source of truth.

apps/web/src/app/(home)/_components/stack-builder.tsx (3)

155-164: Centralize light-mode icon handling; ensure Clerk asset exists.

Inline brand checks tend to drift. Extract a shared whitelist for “-light.svg” brands and reference it here to keep parity and avoid missing assets for new brands.

Add a helper near other constants:

const LIGHT_VARIANT_BRANDS = new Set(["drizzle", "prisma", "express", "clerk"]);

Then constrain this block to:

-  if (
-    theme === "light" &&
-    (icon.includes("drizzle") ||
-      icon.includes("prisma") ||
-      icon.includes("express") ||
-      icon.includes("clerk"))
-  ) {
+  if (theme === "light" && [...LIGHT_VARIANT_BRANDS].some((b) => icon.includes(b))) {
     iconSrc = icon.replace(".svg", "-light.svg");
   }

743-774: Reuse the Clerk compatibility helper to avoid drift.

Replicate the helper use here to keep the compatibility matrix in one place.

-  const hasClerkCompatibleFrontend =
-    nextStack.webFrontend.some((f) =>
-      [
-        "tanstack-router",
-        "react-router",
-        "tanstack-start",
-        "next",
-      ].includes(f),
-    ) ||
-    nextStack.nativeFrontend.some((f) =>
-      ["native-nativewind", "native-unistyles"].includes(f),
-    );
+  const hasClerkCompatibleFrontend = isClerkFrontendCompat(
+    nextStack.webFrontend,
+    nextStack.nativeFrontend,
+  );

213-226: Extract Clerk compatibility logic into a shared helper
The Clerk-frontend check around lines 213–226 and 743–756 in stack-builder.tsx is duplicated. Factor it into a single isClerkFrontendCompat(webFrontend, nativeFrontend) utility (placed alongside other helpers) to keep the logic DRY.

// e.g. in apps/web/src/app/utils.ts
export const isClerkFrontendCompat = (web: string[], native: string[]) =>
  web.some((f) =>
    ["tanstack-router", "react-router", "tanstack-start", "next"].includes(f),
  ) ||
  native.some((f) =>
    ["native-nativewind", "native-unistyles"].includes(f),
  );

Then replace both in-place checks with:

const hasClerkCompatibleFrontend = isClerkFrontendCompat(
  nextStack.webFrontend,
  nextStack.nativeFrontend,
);
apps/web/scripts/generate-analytics.ts (3)

577-596: Prefer Bun.$ over child_process for wrangler invocations.

Conforms to repo guidelines and improves portability/cancellation.

Example (replace execSync usage; add import { $ } from "bun"):

import { $ } from "bun";

// ...
await $`npx wrangler r2 object put ${`${BUCKET_NAME}/${key}`} --file=${tempFilePath} --remote`;
await $`npx wrangler r2 object put ${`${BUCKET_NAME}/${minimalKey}`} --file=${minimalTempFilePath} --remote`;

347-350: Gate noisy distribution logs behind VERBOSE.

Prevents CI noise and log bloat.

Apply:

-          console.log("📊 Platform distribution:", platformCounts);
-          console.log("📊 Backend distribution:", backendCounts);
-          console.log("📊 Database distribution:", databaseCounts);
+          if (process.env.VERBOSE?.toLowerCase() === "true") {
+            console.log("📊 Platform distribution:", platformCounts);
+            console.log("📊 Backend distribution:", backendCounts);
+            console.log("📊 Database distribution:", databaseCounts);
+          }

615-617: Use import.meta.main to detect direct execution.

Safer across .ts/.js and runtimes (Bun/Node ESM).

Apply:

-if (process.argv[1]?.endsWith("generate-analytics.ts")) {
-  await generateAnalyticsData();
-}
+if (import.meta.main) {
+  await generateAnalyticsData();
+}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 39aa67d and 18e52cd.

📒 Files selected for processing (13)
  • apps/cli/src/helpers/core/add-addons.ts (1 hunks)
  • apps/cli/src/helpers/core/add-deployment.ts (1 hunks)
  • apps/cli/src/prompts/auth.ts (1 hunks)
  • apps/cli/src/prompts/config-prompts.ts (4 hunks)
  • apps/cli/src/utils/config-validation.ts (2 hunks)
  • apps/cli/test/cli.smoke.test.ts (70 hunks)
  • apps/web/content/docs/analytics.mdx (1 hunks)
  • apps/web/scripts/generate-analytics.ts (1 hunks)
  • apps/web/src/app/(home)/_components/stack-builder.tsx (8 hunks)
  • apps/web/src/app/(home)/analytics/_components/analytics-header.tsx (3 hunks)
  • apps/web/src/app/(home)/analytics/page.tsx (1 hunks)
  • apps/web/src/app/(home)/page.tsx (1 hunks)
  • apps/web/src/lib/constant.ts (8 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/web/content/docs/analytics.mdx
🚧 Files skipped from review as they are similar to previous changes (4)
  • apps/web/src/app/(home)/page.tsx
  • apps/web/src/app/(home)/analytics/_components/analytics-header.tsx
  • apps/cli/src/prompts/auth.ts
  • apps/web/src/lib/constant.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/convex_rules.mdc)

**/*.{ts,tsx}: Use Id from './_generated/dataModel' to type document ids (e.g., Id<'users'>)
Ensure Record key/value types align with validators (e.g., v.record(v.id('users'), v.string()) => Record<Id<'users'>, string>)
Be strict with types for document ids; prefer Id<'table'> over string
Use 'as const' for string literals in discriminated unions
When using Array and Record types, declare with explicit generic types (e.g., const arr: Array = ...)

Files:

  • apps/cli/src/helpers/core/add-deployment.ts
  • apps/web/scripts/generate-analytics.ts
  • apps/cli/src/helpers/core/add-addons.ts
  • apps/cli/src/utils/config-validation.ts
  • apps/web/src/app/(home)/_components/stack-builder.tsx
  • apps/cli/test/cli.smoke.test.ts
  • apps/cli/src/prompts/config-prompts.ts
  • apps/web/src/app/(home)/analytics/page.tsx
**/*.{js,jsx,ts,tsx,mjs,cjs}

📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)

**/*.{js,jsx,ts,tsx,mjs,cjs}: Do not use dotenv; Bun auto-loads .env
Use Bun.serve() for HTTP/WebSockets; do not use express
Use bun:sqlite for SQLite; do not use better-sqlite3
Use Bun.redis for Redis; do not use ioredis
Use Bun.sql for Postgres; do not use pg or postgres.js
Use built-in WebSocket; do not use ws
Prefer Bun.file over node:fs readFile/writeFile
Use Bun.$ instead of execa for shelling out

Files:

  • apps/cli/src/helpers/core/add-deployment.ts
  • apps/web/scripts/generate-analytics.ts
  • apps/cli/src/helpers/core/add-addons.ts
  • apps/cli/src/utils/config-validation.ts
  • apps/web/src/app/(home)/_components/stack-builder.tsx
  • apps/cli/test/cli.smoke.test.ts
  • apps/cli/src/prompts/config-prompts.ts
  • apps/web/src/app/(home)/analytics/page.tsx
🧬 Code graph analysis (3)
apps/cli/src/utils/config-validation.ts (1)
apps/cli/src/utils/errors.ts (1)
  • exitWithError (9-15)
apps/cli/src/prompts/config-prompts.ts (2)
apps/cli/src/types.ts (1)
  • Auth (86-86)
apps/cli/src/prompts/auth.ts (1)
  • getAuthChoice (6-56)
apps/web/src/app/(home)/analytics/page.tsx (1)
apps/web/src/app/(home)/analytics/_components/analytics-page.tsx (1)
  • AnalyticsPage (11-56)
🔇 Additional comments (23)
apps/web/src/app/(home)/analytics/page.tsx (1)

9-10: Nice server-to-client split.

Clean server prefetch with UI delegated to a client component is the right pattern here.

apps/cli/src/prompts/config-prompts.ts (4)

5-5: Import addition for Auth type is correct.

The import of the Auth type aligns with the new authentication schema migration from boolean to enum values.


42-42: Type signature updated correctly.

The auth field in PromptGroupResults type is properly updated from boolean to Auth to match the new authentication model.


79-84: Function call signature updated appropriately.

The getAuthChoice function call is updated with:

  • Proper type casting of flags.auth to Auth | undefined
  • Addition of results.frontend as the fourth parameter

This aligns with the function signature shown in the relevant code snippets.


139-139: Default auth assignment aligned with new type system.

The assignment result.auth = "none" for the "none" backend path is consistent with the new Auth enum where "none" is a valid string value instead of the previous boolean false.

apps/cli/test/cli.smoke.test.ts (10)

283-283: Test type definitions updated correctly.

The BtsConfig type and assertBtsConfig function parameter are properly updated to expect auth?: string instead of auth?: boolean, aligning with the new authentication type system.

Also applies to: 302-302


448-449: CLI flags updated to use string-based auth values.

The test commands correctly use --auth none instead of boolean flags, and expectations verify auth: "none" string values in the BTS configuration.

Also applies to: 478-478


549-769: New Convex + Clerk test coverage is comprehensive.

The new test suite thoroughly covers Convex + Clerk authentication combinations across:

  • All supported web frontends (tanstack-router, react-router, tanstack-start, next)
  • All supported native frontends (native-nativewind, native-unistyles)
  • Mixed web + native combinations

The test structure correctly validates:

  • Project scaffolding
  • Proper project structure assertions
  • BTS config verification with auth: "clerk"

805-805: Default auth configuration updated correctly.

The default project test properly expects auth: "better-auth" instead of a boolean value, and the minimal configuration test uses auth: "none", both consistent with the new enum-based auth system.

Also applies to: 857-857


828-829: All test cases consistently use string-based auth flags.

Throughout the test file, all CLI commands now use --auth none or --auth better-auth string flags instead of boolean flags, maintaining consistency with the new authentication type system.

Also applies to: 880-881, 969-970, 1013-1014, 1057-1058, 1101-1102, 1145-1146, 1193-1194, 1239-1240, 1285-1286, 1333-1334, 1380-1381, 1427-1428, 1474-1475, 1523-1524, 1569-1570, 1619-1620, 1660-1661, 1702-1703, 1736-1737, 1770-1771, 1805-1806, 1839-1840, 1948-1949, 2028-2029, 2070-2071, 2104-2105, 2141-2142, 2182-2183, 2227-2228, 2270-2271, 2311-2312, 2382-2383, 2423-2424, 2462-2463, 2503-2504, 2544-2545


586-586: Auth value validation in test assertions is correct.

The test assertions properly expect auth: "better-auth" string values in BTS configuration files, aligning with the new authentication model.

Also applies to: 610-610


856-878: New validation test cases for auth combinations.

The added test cases correctly validate incompatible combinations:

  • convex + better-auth (should fail)
  • nuxt + convex + clerk (should fail)
  • svelte + convex + clerk (should fail)

These tests ensure the CLI properly rejects unsupported authentication configurations.

Also applies to: 880-902, 904-926


1722-1722: Test project names improved for clarity.

The invalid combination test project names are updated to be more descriptive:

  • invalid-combo-database-orm
  • invalid-combo-frontend-api
  • invalid-combo-multiple-web
  • invalid-combo-turso-sqlite
  • invalid-combo-runtime-backend
  • invalid-combo-runtime-orm

This improves test readability and debugging.

Also applies to: 1756-1756, 1790-1790, 1825-1825, 2056-2056, 2090-2090


2950-2950: Build test gating updated for better control.

The change from describe.runIf(process.env.WITH_BUILD === "1") to a ternary condition (process.env.WITH_BUILD === "1" ? describe : describe.skip) provides cleaner conditional test execution.


2985-3001: Build matrix expanded for Clerk combinations.

The build test matrix correctly includes new project names for Convex + Clerk combinations:

  • Individual web and native frontend projects
  • Mixed web + native projects like app-convex-clerk-web-native, app-convex-clerk-next-native, app-convex-clerk-start-native

This ensures comprehensive build testing for the new authentication support.

apps/cli/src/utils/config-validation.ts (1)

187-191: LGTM: “Clerk requires Convex” constraint is correct

This enforces the intended coupling cleanly.

apps/web/src/app/(home)/_components/stack-builder.tsx (3)

274-281: Correct: None-backend forces auth='none'.

Switching from boolean to explicit "none" aligns with the new enum and prevents legacy truthy checks. LGTM.


353-368: Good: Non-Convex + database='none' disables auth.

The guard exempts Convex, matching the new Convex path. Messaging and changes array are consistent.


1594-1603: LGTM: Removed auth from boolean toggle path.

Keeps auth explicit and prevents accidental on/off flips from the toggle UX.

apps/cli/src/helpers/core/add-deployment.ts (1)

71-71: Harden auth defaulting: coerce legacy booleans
Ensure any boolean detectedConfig.auth values from old configs map properly before downstream checks:

-      auth: detectedConfig.auth || "none",
+      auth:
+        detectedConfig.auth === true
+          ? "better-auth"
+          : detectedConfig.auth === false || detectedConfig.auth == null
+            ? "none"
+            : detectedConfig.auth,

Verify no other detectedConfig.auth usages remain unnormalized.

apps/web/scripts/generate-analytics.ts (3)

65-65: URL switch LGTM.

New CSV host aligns with PR-wide changes. Nothing else to flag for this line.


65-65: Verification successful: /export.csv returns HTTP/2 200 with text/csv and no r2.amanv.dev references remain.


245-250: Confirm auth CSV field name (generate-analytics.ts:247)
Verify that row["*.properties.auth"] aligns with the current CSV header after the enum change; if the field’s been renamed (e.g. to *.properties.authProvider), update this key accordingly.

addons: input.addons,
examples: detectedConfig.examples || [],
auth: detectedConfig.auth || false,
auth: detectedConfig.auth || "none",

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.

💡 Verification agent

🧩 Analysis chain

Normalize legacy boolean auth to the new string enum to avoid downstream mismatches

If detectedConfig.auth is true, this currently propagates a boolean into ProjectConfig.auth, breaking string comparisons elsewhere. Map booleans to "better-auth"/"none" and pass through valid strings.

-      auth: detectedConfig.auth || "none",
+      auth:
+        detectedConfig.auth === true
+          ? "better-auth"
+          : detectedConfig.auth === false || detectedConfig.auth == null
+            ? "none"
+            : detectedConfig.auth,

Run to spot any remaining boolean usages or boolean fallbacks for auth:


🏁 Script executed:

#!/bin/bash
# Boolean comparisons against auth (should be none)
rg -nP -C2 '\bauth\s*===?\s*(true|false)\b' --type=ts --type=tsx

# Old-style fallbacks like `|| false` when assigning auth
rg -nP -C2 'auth\s*:\s*[^,]*\|\|\s*false' --type=ts --type=tsx

# Types that still declare auth as boolean
rg -nP -C2 '\bauth\s*:\s*boolean\b' --type=ts --type=tsx

# Configs that still store boolean auth
rg -nP -C2 '"auth"\s*:\s*(true|false)'

Length of output: 613


Normalize legacy boolean auth to the new string enum and update docs

  • In apps/cli/src/helpers/core/add-addons.ts, replace the simple fallback with explicit mapping:
-      auth: detectedConfig.auth || "none",
+      auth:
+        detectedConfig.auth === true
+          ? "better-auth"
+          : detectedConfig.auth === false || detectedConfig.auth == null
+            ? "none"
+            : detectedConfig.auth,
  • In apps/web/content/docs/bts-config.mdx, update the example to use the string enum:
-  "auth": true,
+  "auth": "better-auth",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
auth: detectedConfig.auth || "none",
auth:
detectedConfig.auth === true
? "better-auth"
: detectedConfig.auth === false || detectedConfig.auth == null
? "none"
: detectedConfig.auth,

Comment on lines +69 to 79
if (
has("auth") &&
has("database") &&
cfg.auth !== "none" &&
db === "none" &&
cfg.backend !== "convex"
) {
exitWithError(
"Authentication requires a database. Please choose a database or set '--no-auth'.",
"Authentication requires a database. Please choose a database or set '--auth none'.",
);
}

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.

🛠️ Refactor suggestion

Make auth-without-DB check undefined-safe and DRY it

cfg.auth !== "none" is true when cfg.auth is undefined; programmatic callers may get a surprising error. Also, the same condition is repeated below. Introduce a predicate and reuse it.

- if (
-   has("auth") &&
-   has("database") &&
-   cfg.auth !== "none" &&
-   db === "none" &&
-   cfg.backend !== "convex"
- ) {
+ const needsDbForAuth =
+   (cfg.auth && cfg.auth !== "none") && db === "none" && cfg.backend !== "convex";
+
+ if (has("auth") && has("database") && needsDbForAuth) {
   exitWithError(
     "Authentication requires a database. Please choose a database or set '--auth none'.",
   );
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (
has("auth") &&
has("database") &&
cfg.auth !== "none" &&
db === "none" &&
cfg.backend !== "convex"
) {
exitWithError(
"Authentication requires a database. Please choose a database or set '--no-auth'.",
"Authentication requires a database. Please choose a database or set '--auth none'.",
);
}
// before: inline check for auth without DB
const needsDbForAuth =
(cfg.auth && cfg.auth !== "none") && db === "none" && cfg.backend !== "convex";
if (has("auth") && has("database") && needsDbForAuth) {
exitWithError(
"Authentication requires a database. Please choose a database or set '--auth none'.",
);
}
🤖 Prompt for AI Agents
In apps/cli/src/utils/config-validation.ts around lines 69 to 79, the
auth-without-DB check uses cfg.auth !== "none" which is true when cfg.auth is
undefined and the same condition is duplicated; create a single predicate (e.g.
const authEnabled = has("auth") && typeof cfg.auth === "string" && cfg.auth !==
"none") and replace both occurrences with authEnabled so the check is
undefined-safe and DRY.

Comment on lines +65 to 67
const response = await fetch("https://r2.better-t-stack.dev/export.csv");
let csvText = await response.text();

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.

🛠️ Refactor suggestion

Handle non-200/redirect/content-type on fetch.

Avoid parsing HTML/error bodies as CSV and surface clear failures.

Apply:

-    const response = await fetch("https://r2.better-t-stack.dev/export.csv");
-    let csvText = await response.text();
+    const res = await fetch("https://r2.better-t-stack.dev/export.csv", { redirect: "follow" });
+    if (!res.ok) {
+      throw new Error(`Failed to fetch CSV: ${res.status} ${res.statusText}`);
+    }
+    const contentType = res.headers.get("content-type") || "";
+    if (!contentType.includes("text/csv")) {
+      console.warn(`Unexpected content-type for analytics CSV: ${contentType}`);
+    }
+    let csvText = await res.text();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const response = await fetch("https://r2.better-t-stack.dev/export.csv");
let csvText = await response.text();
const res = await fetch("https://r2.better-t-stack.dev/export.csv", { redirect: "follow" });
if (!res.ok) {
throw new Error(`Failed to fetch CSV: ${res.status} ${res.statusText}`);
}
const contentType = res.headers.get("content-type") || "";
if (!contentType.includes("text/csv")) {
console.warn(`Unexpected content-type for analytics CSV: ${contentType}`);
}
let csvText = await res.text();
🤖 Prompt for AI Agents
In apps/web/scripts/generate-analytics.ts around lines 65 to 67, the fetch
response is assumed to be CSV without checking status or content-type; update
the code to verify response.ok (status 200-299) and validate the Content-Type
header contains "text/csv" (or application/csv) before calling response.text();
if not ok or content-type mismatches, read the body as text for diagnostics and
throw a clear error that includes status, statusText, URL and a snippet of the
body to avoid accidentally parsing HTML/error pages as CSV.

Comment on lines +776 to +792
if (nextStack.backend === "convex" && nextStack.auth === "better-auth") {
notes.auth.notes.push(
"Better-Auth is not compatible with Convex backend. Auth will be set to 'None'.",
);
notes.backend.notes.push(
"Convex backend only supports Clerk auth or no auth. Auth will be disabled.",
);
notes.auth.hasIssue = true;
notes.backend.hasIssue = true;
nextStack.auth = "none";
changed = true;
changes.push({
category: "auth",
message:
"Auth set to 'None' (Better-Auth not compatible with Convex)",
});
}

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.

🛠️ Refactor suggestion

Convex + better-auth: coerce to 'clerk' instead of disabling auth.

Per the PR objective, Convex supports Clerk or None. When users pick “better-auth” with Convex, promote to Clerk rather than turning auth off.

- if (nextStack.backend === "convex" && nextStack.auth === "better-auth") {
-   notes.auth.notes.push(
-     "Better-Auth is not compatible with Convex backend. Auth will be set to 'None'.",
-   );
-   notes.backend.notes.push(
-     "Convex backend only supports Clerk auth or no auth. Auth will be disabled.",
-   );
-   notes.auth.hasIssue = true;
-   notes.backend.hasIssue = true;
-   nextStack.auth = "none";
-   changed = true;
-   changes.push({
-     category: "auth",
-     message:
-       "Auth set to 'None' (Better-Auth not compatible with Convex)",
-   });
- }
+ if (nextStack.backend === "convex" && nextStack.auth === "better-auth") {
+   notes.auth.notes.push(
+     "Better-Auth is not compatible with Convex. 'Clerk' will be selected.",
+   );
+   notes.auth.hasIssue = true;
+   nextStack.auth = "clerk";
+   changed = true;
+   changes.push({
+     category: "auth",
+     message: "Auth set to 'Clerk' (Convex supports Clerk or None)",
+   });
+ }

Note: The earlier Convex override (Lines 223–225) will still set auth to 'none' if frontends are incompatible with Clerk, which is desirable.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (nextStack.backend === "convex" && nextStack.auth === "better-auth") {
notes.auth.notes.push(
"Better-Auth is not compatible with Convex backend. Auth will be set to 'None'.",
);
notes.backend.notes.push(
"Convex backend only supports Clerk auth or no auth. Auth will be disabled.",
);
notes.auth.hasIssue = true;
notes.backend.hasIssue = true;
nextStack.auth = "none";
changed = true;
changes.push({
category: "auth",
message:
"Auth set to 'None' (Better-Auth not compatible with Convex)",
});
}
if (nextStack.backend === "convex" && nextStack.auth === "better-auth") {
notes.auth.notes.push(
"Better-Auth is not compatible with Convex. 'Clerk' will be selected.",
);
notes.auth.hasIssue = true;
nextStack.auth = "clerk";
changed = true;
changes.push({
category: "auth",
message: "Auth set to 'Clerk' (Convex supports Clerk or None)",
});
}
🤖 Prompt for AI Agents
In apps/web/src/app/(home)/_components/stack-builder.tsx around lines 776 to
792, the current logic coerces nextStack.auth to "none" when backend is "convex"
and auth is "better-auth"; instead, set nextStack.auth = "clerk" and update the
user-facing notes and change entry to reflect promotion to Clerk (e.g., change
messages to indicate Better-Auth is not compatible and auth is promoted to
Clerk), leaving notes.auth.hasIssue/notes.backend.hasIssue as appropriate;
adjust the changes.push message to say "Auth set to 'Clerk' (Better-Auth not
compatible with Convex)" so users see the correct automatic promotion.

@AmanVarshney01
AmanVarshney01 merged commit 54bcdf1 into main Aug 28, 2025
@AmanVarshney01
AmanVarshney01 deleted the add-clerk-convex branch August 28, 2025 18:51

@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: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (6)
apps/web/content/docs/cli/programmatic-api.mdx (1)

137-138: Fix CreateInput type: auth is no longer boolean.

Update the type to the new provider union to avoid misleading users.

-  auth?: boolean;                   // Include authentication
+  auth?: "better-auth" | "clerk" | "none"; // Authentication provider
apps/cli/src/prompts/frontend.ts (2)

3-11: Type auth as the concrete union.

Avoid string to keep compile-time safety aligned with isFrontendAllowedWithBackend.

-import type { Backend, Frontend } from "../types";
+import type { Auth, Backend, Frontend } from "../types";
@@
-export async function getFrontendChoice(
+export async function getFrontendChoice(
   frontendOptions?: Frontend[],
   backend?: Backend,
-  auth?: string,
+  auth?: Auth,
 ): Promise<Frontend[]> {

75-83: Guard select initialValue against filtered-out defaults.

If the default isn’t in webOptions, Clack may ignore it or confuse users. Use the first available option.

-    const webFramework = await select<Frontend>({
+    const webFramework = await select<Frontend>({
       message: "Choose web",
       options: webOptions,
-      initialValue: DEFAULT_CONFIG.frontend[0],
+      initialValue:
+        webOptions.find((o) => o.value === DEFAULT_CONFIG.frontend[0])?.value ??
+        webOptions[0]?.value,
     });
apps/cli/test/cli.smoke.test.ts (3)

3-3: Replace execa with Bun.$ per repo guidelines

Tests shell out a lot; switch to Bun.$ (supports stdio inherit, nothrow, AbortSignal timeout). This removes the execa dep and aligns with “Use Bun.$ instead of execa”.

Apply:

-import { execa } from "execa";
+import { $ } from "bun";
-const buildProc = execa("bun", ["run", "build"], {
-  cwd: join(__dirname, ".."),
-  env: {
-    ...process.env,
-    CI: "true",
-    NODE_ENV: "production",
-  },
-});
-buildProc.stdout?.pipe(process.stdout);
-buildProc.stderr?.pipe(process.stderr);
-const { exitCode } = await buildProc;
+const { exitCode } = await $({
+  cwd: join(__dirname, ".."),
+  env: { ...process.env, CI: "true", NODE_ENV: "production" },
+  stdio: "inherit",
+})`bun run build`.nothrow();
-const runInstall = async (pm: "bun" | "pnpm" | "npm", cwd: string) => {
-  if (pm === "bun")
-    return execa("bun", ["install"], { cwd, stdio: "inherit" });
-  if (pm === "pnpm")
-    return execa("pnpm", ["install", "--no-frozen-lockfile"], {
-      cwd,
-      stdio: "inherit",
-    });
-  return execa("npm", ["install", "--no-audit", "--no-fund"], {
-    cwd,
-    stdio: "inherit",
-  });
-};
+const runInstall = async (pm: "bun" | "pnpm" | "npm", cwd: string) => {
+  if (pm === "bun") return $({ cwd, stdio: "inherit" })`bun install`.nothrow();
+  if (pm === "pnpm")
+    return $({ cwd, stdio: "inherit" })`pnpm install --no-frozen-lockfile`.nothrow();
+  return $({ cwd, stdio: "inherit" })`npm install --no-audit --no-fund`.nothrow();
+};
-const runScript = async (
-  pm: "bun" | "pnpm" | "npm",
-  cwd: string,
-  script: string,
-  extraArgs: string[] = [],
-  timeout?: number,
-) => {
-  const base = pm === "bun" ? ["run", script] : ["run", script];
-  const cmd = pm === "bun" ? "bun" : pm;
-  return execa(cmd, [...base, ...extraArgs], {
-    cwd,
-    timeout,
-    env: { ...process.env, NODE_ENV: "production", CI: "true" },
-    stdio: "inherit",
-  });
-};
+const runScript = async (
+  pm: "bun" | "pnpm" | "npm",
+  cwd: string,
+  script: string,
+  extraArgs: string[] = [],
+  timeout?: number,
+) => {
+  const signal = timeout ? AbortSignal.timeout(timeout) : undefined;
+  return $({
+    cwd,
+    stdio: "inherit",
+    env: { ...process.env, NODE_ENV: "production", CI: "true" },
+    signal,
+  })`${pm} run ${script} ${extraArgs}`.nothrow();
+};

Also applies to: 385-396, 3069-3081, 3083-3099


3051-3068: Bug: missing await in detectPackageManager causes promise misuse

readBtsConfig is async; accessing bts.packageManager without await always yields undefined.

-const bts = readBtsConfig(projectDir) as { packageManager?: string };
+const bts = (await readBtsConfig(projectDir)) as { packageManager?: string };

531-546: Await async assertion helpers
All invocations of assertScaffoldedProject, assertProjectStructure and assertBtsConfig in apps/cli/test/cli.smoke.test.ts must be prefixed with await to prevent racey, false-positive tests. For example:

- assertScaffoldedProject(projectDir);
+ await assertScaffoldedProject(projectDir);
- assertProjectStructure(projectDir, { /* ... */ });
+ await assertProjectStructure(projectDir, { /* ... */ });
- assertBtsConfig(projectDir, { /* ... */ });
+ await assertBtsConfig(projectDir, { /* ... */ });
♻️ Duplicate comments (2)
apps/cli/src/helpers/core/create-readme.ts (1)

465-468: Authentication feature now shown for Convex+Clerk too — thank you.
This addresses the earlier suppression with !isConvex.

apps/cli/src/utils/compatibility-rules.ts (1)

163-170: Allow Clerk with Convex — good fix.

Condition now skips pushing --auth when auth === "clerk". Matches the intent from the earlier review.

🧹 Nitpick comments (17)
apps/cli/src/helpers/core/post-installation.ts (1)

419-421: Tighten wording: template name isn’t strictly required; clarify issuer field.

Avoid implying the JWT template must be named exactly "convex" and clarify that the issuer is the Clerk JWT Issuer/Frontend API domain.

Apply this diff:

 return `${pc.bold("Clerk Authentication Setup:")}\n${pc.cyan("1.")} Sign up for Clerk at ${pc.underline("https://clerk.com/sign-up")}\n${pc.cyan("2.")} Create a new application in Clerk Dashboard\n-${pc.cyan("3.")} Create a JWT template named ${pc.bold("'convex'")} (exact name required)\n-${pc.cyan("4.")} Copy your Clerk Frontend API URL (Issuer URL)\n+${pc.cyan("3.")} Create a JWT template (e.g., ${pc.bold("'convex'")})\n+${pc.cyan("4.")} Copy your Clerk JWT Issuer (Frontend API) domain\n ${pc.cyan("5.")} Set environment variables:\n${pc.dim("   •")} CLERK_JWT_ISSUER_DOMAIN in Convex Dashboard\n${pc.dim("   •")} CLERK_PUBLISHABLE_KEY in apps/*/.env\n ${pc.cyan("6.")} Follow the complete guide: ${pc.underline("https://docs.convex.dev/auth/clerk")}\n${pc.yellow("NOTE:")} Use Convex's <Authenticated> components instead of Clerk's <SignedIn>`;

Please verify against current Convex + Clerk docs whether any additional env (e.g., secret key) is needed for your chosen flows (web/native).

apps/cli/src/helpers/core/create-readme.ts (2)

491-491: Unused _auth param — keep or remove.
If there’s no near-term use, remove the parameter (and its call site) to reduce noise; otherwise leave as underscore-prefixed.


590-590: Unused _auth param — same note as above.

apps/web/content/docs/compatibility.mdx (3)

8-8: Clarify Convex rule wording for precision.

-- **Convex backend**: Sets database, ORM, and API to `none`; auth to `clerk` (if compatible frontends) or `none`
+- **Convex backend**: Sets database, ORM, and API to `none`; sets `auth` to `clerk` (when the selected frontend supports Clerk) or to `none`.

12-12: Tighten “Database none” rule; spell out exception precisely.

-- **Database `none`**: Disables ORM and Better-Auth (but allows Clerk with Convex)
+- **Database `none`**: Disables ORM and Better‑Auth; allows `auth: "clerk"` only when `backend: "convex"` and the chosen frontend supports Clerk.

15-15: Make the auth: clerk constraint explicit and consistent with others.

-- **Auth `clerk`**: Only available with Convex backend and compatible frontends
+- **Auth `clerk`**: Available only with `backend: "convex"` and compatible frontends.
apps/web/content/docs/index.mdx (1)

122-122: Convex + React + Clerk section looks good; add env var callout.

   </Tab>
 </Tabs>

+> Note: Clerk requires `CLERK_PUBLISHABLE_KEY` and `CLERK_SECRET_KEY`. See the Authentication guide for setup steps.

Also applies to: 129-131, 137-139, 145-147

apps/web/content/docs/cli/options.mdx (1)

234-238: Clarify defaults and coercion behavior.

Document what happens when --auth is omitted, especially with Convex.

 **Note:** 
 - `better-auth` requires both a database and backend framework
- - `clerk` is only available with Convex backend
- - Authentication is automatically set to `none` when using `--backend none` or `--database none` (unless using Convex)
+ - `clerk` is only available with Convex backend
+ - If `--auth` is omitted:
+   - Defaults to `better-auth` when both `--backend` and `--database` are not `none` and backend is not `convex`
+   - With `--backend convex`, it defaults to `clerk` when the selected frontend supports Clerk; otherwise `none`
+ - Authentication is automatically set to `none` when `--backend none` or `--database none` (except the Convex + Clerk case above)
apps/web/content/docs/project-structure.mdx (1)

339-342: Clarify Clerk is Convex-only in “Key Details”.

Add a short qualifier to avoid implying Clerk works with non-Convex stacks here.

-  - `clerk`: Clerk provider setup and authentication components
+  - `clerk` (Convex only): Clerk provider setup and authentication components
apps/cli/src/utils/compatibility-rules.ts (1)

219-226: Tighten typing for auth and make incompatible list as const.

Use the concrete union type to prevent drift; minor perf/readability cleanup.

-export function isFrontendAllowedWithBackend(
-  frontend: Frontend,
-  backend?: ProjectConfig["backend"],
-  auth?: string,
-) {
+export function isFrontendAllowedWithBackend(
+  frontend: Frontend,
+  backend?: ProjectConfig["backend"],
+  auth?: ProjectConfig["auth"],
+) {
@@
-  if (auth === "clerk" && backend === "convex") {
-    const incompatibleFrontends = ["nuxt", "svelte", "solid"];
+  if (auth === "clerk" && backend === "convex") {
+    const incompatibleFrontends = ["nuxt", "svelte", "solid"] as const;
     if (incompatibleFrontends.includes(frontend)) return false;
   }
apps/web/content/docs/cli/compatibility.mdx (1)

163-174: Tighten wording; small grammar/style pass.

Minor clarity and concision improvements.

-### Better-Auth Requirements
-Better-Auth authentication requires:
+### Better-Auth requirements
+Better-Auth requires:
@@
-### Clerk Requirements
-Clerk authentication requires:
+### Clerk requirements
+Clerk requires:
@@
-- Not compatible with Nuxt, Svelte, or Solid
+- Incompatible with Nuxt, Svelte, and Solid
apps/cli/src/prompts/config-prompts.ts (2)

80-86: Casting flags.auth is fine; consider importing Auth in the call site to avoid inline import.

Minor readability nit.

-        getAuthChoice(
-          flags.auth as import("../types").Auth | undefined,
+        getAuthChoice(
+          flags.auth as Auth | undefined,
           results.database !== "none",
           results.backend,
           results.frontend,
         ),

126-133: Convex preset doesn’t set auth; align with docs or set a default.

Either: (a) keep prompts-driven choice and update docs to say “defaults to Clerk,” or (b) set result.auth here based on frontend compatibility.

   if (result.backend === "convex") {
     result.runtime = "none";
     result.database = "none";
     result.orm = "none";
     result.api = "none";
     result.dbSetup = "none";
     result.examples = ["todo"];
+    // Optional: default auth for Convex
+    // If all selected frontends are compatible with Clerk, prefer Clerk; else none.
+    // import { isFrontendAllowedWithBackend } from "../utils/compatibility-rules";
+    // if (!flags.auth) {
+    //   const allClerkOk = result.frontend.every((f) =>
+    //     isFrontendAllowedWithBackend(f, "convex", "clerk"),
+    //   );
+    //   result.auth = (allClerkOk ? "clerk" : "none") as Auth;
+    // }
   }
apps/cli/test/cli.smoke.test.ts (4)

3083-3093: Minor: redundant ternary

The base array is identical on both branches.

-const base = pm === "bun" ? ["run", script] : ["run", script];
+const base = ["run", script];

(Note: if you adopt Bun.$ per earlier suggestion, this block will be replaced entirely.)


283-283: Strengthen type for auth to the known union

Prevents drift and improves IDE help.

-  auth: string;
+  auth: "none" | "better-auth" | "clerk";
-  auth?: string;
+  auth?: "none" | "better-auth" | "clerk";

Also applies to: 302-302


1911-1911: Typo in test id

“svlete” -> “svelte”. Harmless but noisy in CI logs.

-  "invalid-combo-svlete-convex-clerk",
+  "invalid-combo-svelte-convex-clerk",

10-34: Global chdir in tests can be racy

process.chdir is global; parallel tests or future concurrency may flake. Prefer passing cwd via your CLI’s options or serialize suites.

If CLI can’t accept cwd, consider wrapping suites with single-threaded runner or use a mutex.

Also applies to: 45-73

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 18e52cd and 6846bd9.

📒 Files selected for processing (16)
  • apps/cli/src/helpers/core/command-handlers.ts (2 hunks)
  • apps/cli/src/helpers/core/create-readme.ts (9 hunks)
  • apps/cli/src/helpers/core/post-installation.ts (4 hunks)
  • apps/cli/src/prompts/config-prompts.ts (5 hunks)
  • apps/cli/src/prompts/frontend.ts (2 hunks)
  • apps/cli/src/utils/compatibility-rules.ts (4 hunks)
  • apps/cli/src/utils/config-validation.ts (2 hunks)
  • apps/cli/test/cli.smoke.test.ts (74 hunks)
  • apps/web/content/docs/bts-config.mdx (1 hunks)
  • apps/web/content/docs/cli/compatibility.mdx (3 hunks)
  • apps/web/content/docs/cli/index.mdx (1 hunks)
  • apps/web/content/docs/cli/options.mdx (2 hunks)
  • apps/web/content/docs/cli/programmatic-api.mdx (4 hunks)
  • apps/web/content/docs/compatibility.mdx (1 hunks)
  • apps/web/content/docs/index.mdx (7 hunks)
  • apps/web/content/docs/project-structure.mdx (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/web/content/docs/cli/index.mdx
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/cli/src/helpers/core/command-handlers.ts
  • apps/cli/src/utils/config-validation.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/convex_rules.mdc)

**/*.{ts,tsx}: Use Id from './_generated/dataModel' to type document ids (e.g., Id<'users'>)
Ensure Record key/value types align with validators (e.g., v.record(v.id('users'), v.string()) => Record<Id<'users'>, string>)
Be strict with types for document ids; prefer Id<'table'> over string
Use 'as const' for string literals in discriminated unions
When using Array and Record types, declare with explicit generic types (e.g., const arr: Array = ...)

Files:

  • apps/cli/src/helpers/core/post-installation.ts
  • apps/cli/src/prompts/config-prompts.ts
  • apps/cli/src/prompts/frontend.ts
  • apps/cli/src/utils/compatibility-rules.ts
  • apps/cli/src/helpers/core/create-readme.ts
  • apps/cli/test/cli.smoke.test.ts
**/*.{js,jsx,ts,tsx,mjs,cjs}

📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)

**/*.{js,jsx,ts,tsx,mjs,cjs}: Do not use dotenv; Bun auto-loads .env
Use Bun.serve() for HTTP/WebSockets; do not use express
Use bun:sqlite for SQLite; do not use better-sqlite3
Use Bun.redis for Redis; do not use ioredis
Use Bun.sql for Postgres; do not use pg or postgres.js
Use built-in WebSocket; do not use ws
Prefer Bun.file over node:fs readFile/writeFile
Use Bun.$ instead of execa for shelling out

Files:

  • apps/cli/src/helpers/core/post-installation.ts
  • apps/cli/src/prompts/config-prompts.ts
  • apps/cli/src/prompts/frontend.ts
  • apps/cli/src/utils/compatibility-rules.ts
  • apps/cli/src/helpers/core/create-readme.ts
  • apps/cli/test/cli.smoke.test.ts
🧬 Code graph analysis (2)
apps/cli/src/prompts/frontend.ts (1)
apps/cli/src/utils/compatibility-rules.ts (1)
  • isFrontendAllowedWithBackend (216-229)
apps/cli/src/utils/compatibility-rules.ts (1)
apps/cli/src/types.ts (1)
  • ProjectConfig (164-183)
🪛 LanguageTool
apps/web/content/docs/compatibility.mdx

[grammar] ~8-~8: There might be a mistake here.
Context: ...to clerk (if compatible frontends) or none - Backend none: Forces API, ORM, datab...

(QB_NEW_EN)


[grammar] ~9-~9: There might be a mistake here.
Context: ...and runtime to none; disables examples - Frontend none: Backend-only project;...

(QB_NEW_EN)


[grammar] ~10-~10: There might be a mistake here.
Context: ...ject; PWA/Tauri/examples may be disabled - API none: No tRPC/oRPC setup; use fr...

(QB_NEW_EN)


[grammar] ~11-~11: There might be a mistake here.
Context: ...PC/oRPC setup; use framework-native APIs - Database none: Disables ORM and Bett...

(QB_NEW_EN)


[grammar] ~12-~12: There might be a mistake here.
Context: ...tter-Auth (but allows Clerk with Convex) - ORM none: No ORM setup; manage DB ma...

(QB_NEW_EN)


[grammar] ~13-~13: There might be a mistake here.
Context: ...one**: No ORM setup; manage DB manually - **Runtime none`**: Only with Convex backe...

(QB_NEW_EN)


[grammar] ~14-~14: There might be a mistake here.
Context: ... with Convex backend or when backend is none - Auth clerk: Only available with Conv...

(QB_NEW_EN)

apps/web/content/docs/cli/options.mdx

[grammar] ~224-~224: There might be a mistake here.
Context: ...h: Better-Auth authentication (default) - clerk`: Clerk authentication (only with Convex...

(QB_NEW_EN)


[grammar] ~225-~225: There might be a mistake here.
Context: ...uthentication (only with Convex backend) - none: No authentication ```bash create-bett...

(QB_NEW_EN)

apps/web/content/docs/cli/compatibility.mdx

[style] ~70-~70: Consider using “incompatible” to avoid wordiness.
Context: ...rameworks). Nuxt, Svelte, and Solid are not compatible with Clerk. #### No Backend When using...

(NOT_ABLE_PREMIUM)


[grammar] ~72-~72: There might be a mistake here.
Context: ... compatible with Clerk. #### No Backend When using --backend none, the followi...

(QB_NEW_EN)


[grammar] ~163-~163: There might be a mistake here.
Context: ...quirements ### Better-Auth Requirements Better-Auth authentication requires: - A...

(QB_NEW_EN)


[grammar] ~164-~164: There might be a mistake here.
Context: ...nts Better-Auth authentication requires: - A backend framework (cannot be none) -...

(QB_NEW_EN)


[grammar] ~165-~165: There might be a mistake here.
Context: ...- A backend framework (cannot be none) - A database (cannot be none) - An ORM (...

(QB_NEW_EN)


[grammar] ~166-~166: There might be a mistake here.
Context: ... none) - A database (cannot be none) - An ORM (cannot be none) ### Clerk Req...

(QB_NEW_EN)


[grammar] ~169-~169: There might be a mistake here.
Context: ...annot be none) ### Clerk Requirements Clerk authentication requires: - Convex ...

(QB_NEW_EN)


[grammar] ~170-~170: There might be a mistake here.
Context: ...uirements Clerk authentication requires: - Convex backend (--backend convex) - Co...

(QB_NEW_EN)


[grammar] ~171-~171: There might be a mistake here.
Context: ...s: - Convex backend (--backend convex) - Compatible frontends (React frameworks, ...

(QB_NEW_EN)


[grammar] ~172-~172: There might be a mistake here.
Context: ...t.js, TanStack Start, native frameworks) - Not compatible with Nuxt, Svelte, or Sol...

(QB_NEW_EN)


[style] ~173-~173: Consider using “incompatible” to avoid wordiness.
Context: ...s, TanStack Start, native frameworks) - Not compatible with Nuxt, Svelte, or Solid ```bash # ...

(NOT_ABLE_PREMIUM)

apps/web/content/docs/project-structure.mdx

[grammar] ~339-~339: There might be a mistake here.
Context: ... authentication setup based on provider: - better-auth: src/lib/auth.ts on server and login/...

(QB_NEW_EN)


[grammar] ~340-~340: There might be a mistake here.
Context: ...ver and login/dashboard pages on web app - clerk: Clerk provider setup and authenticatio...

(QB_NEW_EN)


[grammar] ~341-~341: There might be a mistake here.
Context: ...ider setup and authentication components - ORM/DB: Drizzle/Prisma/Mongoose files ...

(QB_NEW_EN)

apps/web/content/docs/index.mdx

[grammar] ~124-~124: There might be a mistake here.
Context: ...k <Tabs items={['bun', 'pnpm', 'npm']}> ```bash bun cr...

(QB_NEW_EN)


[grammar] ~260-~260: There might be a mistake here.
Context: ...one - --auth: better-auth, clerk, none - --addons: turborepo, pwa, tauri, biome, husky, s...

(QB_NEW_EN)

🔇 Additional comments (23)
apps/cli/src/helpers/core/post-installation.ts (1)

190-191: LGTM — appending the consolidated Clerk section here is the right place.

Once the inline block is removed, this keeps provider-specific guidance grouped with the other add-on sections.

apps/cli/src/helpers/core/create-readme.ts (5)

7-7: Type import for Auth looks correct.


143-144: Plumbing auth into project structure generation is correct.


267-268: Signature updated to accept Auth — good.


345-346: Features list now typed with Auth — good.


102-106: Tweak Convex + Clerk guide copy
The URL https://docs.convex.dev/auth/clerk is still valid—apply the proposed diff.

- Follow the prompts to create a new Convex project and connect it to your application.${
-        auth === "clerk"
-          ? " See [Convex + Clerk guide](https://docs.convex.dev/auth/clerk) for auth setup."
-          : ""
-      }`
+ Follow the prompts to create a new Convex project and connect it to your application.${
+        auth === "clerk"
+          ? " See the Convex + Clerk guide for authentication setup: https://docs.convex.dev/auth/clerk"
+          : ""
+      }`
apps/web/content/docs/cli/programmatic-api.mdx (3)

36-36: Docs aligned with new auth provider model.

The Quick Start example correctly uses auth: "better-auth".


289-289: Prompt-handling example updated; LGTM.

auth: "better-auth" matches the new API.


261-261: Approve code changes
No stale boolean or negated auth flags found in the docs.

apps/web/content/docs/bts-config.mdx (1)

40-40: Config snippet matches new auth semantics.

"auth": "better-auth" is correct for BTS config.

apps/web/content/docs/index.mdx (3)

94-94: Default stack examples updated with --auth better-auth.

Consistent across bun/pnpm/npm. Good.

Also applies to: 105-105, 116-116


199-199: Mobile (Expo) examples: auth provider switch acknowledged.

--auth better-auth aligns with new model.

Also applies to: 209-209, 219-219


260-260: Flags cheat sheet correctly lists auth providers.

No further changes needed.

apps/web/content/docs/cli/options.mdx (2)

220-232: Provider-based --auth option reads well.

Clear breakdown of allowed values.


323-324: No residual auth flags detected
Executed a repo-wide sweep for deprecated --no-auth, unsupported --auth values, and auth: true|false with PCRE2-enabled ripgrep; no occurrences found.

apps/web/content/docs/project-structure.mdx (1)

259-265: Schema update LGTM.

Auth union and web/server deploy enums look correct and consistent with the CLI changes.

apps/cli/src/utils/compatibility-rules.ts (3)

146-146: Correct default for backend=none.

Setting auth to the string "none" matches the new Auth type.


182-184: Backend=none auth guard LGTM.

Correctly flags any non-none auth.


156-180: []

apps/web/content/docs/cli/compatibility.mdx (2)

75-82: “No Backend” preset text LGTM.

Accurately reflects the code path setting auth: "none".


221-226: Great actionable fixes section.

The Better-Auth/Clerk split examples are clear.

apps/cli/src/prompts/config-prompts.ts (2)

61-63: Pass-through of auth to frontend prompt LGTM.

Keeps frontend gating consistent with auth/backend combos.


135-143: Backend=none preset sets auth: "none" — good.

Matches Compatibility docs.

Comment on lines +327 to +332
if (auth === "clerk") {
structure.push(
"│ ├── convex/ # Convex functions and schema",
"│ └── .env.local # Convex environment variables",
);
}

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.

🛠️ Refactor suggestion

Always show convex/ dir; gate .env.local by Clerk; fix tree connectors.
Currently the convex/ folder is only shown when Clerk is selected, which is confusing because it exists for Convex regardless of auth. Also, connectors (├──/└──) should adapt based on whether .env.local is added.

Apply this diff:

-    if (auth === "clerk") {
-      structure.push(
-        "│       ├── convex/    # Convex functions and schema",
-        "│       └── .env.local # Convex environment variables",
-      );
-    }
+    {
+      const hasClerkEnv = auth === "clerk";
+      structure.push(
+        `│       ${hasClerkEnv ? "├──" : "└──"} convex/    # Convex functions and schema`,
+      );
+      if (hasClerkEnv) {
+        structure.push("│       └── .env.local # Convex environment variables");
+      }
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (auth === "clerk") {
structure.push(
"│ ├── convex/ # Convex functions and schema",
"│ └── .env.local # Convex environment variables",
);
}
{
const hasClerkEnv = auth === "clerk";
structure.push(
`│ ${hasClerkEnv ? "├──" : "└──"} convex/ # Convex functions and schema`,
);
if (hasClerkEnv) {
structure.push("│ └── .env.local # Convex environment variables");
}
}
🤖 Prompt for AI Agents
In apps/cli/src/helpers/core/create-readme.ts around lines 327 to 332, always
include the "convex/" tree entry (it exists regardless of auth) and only include
the ".env.local" entry when auth === "clerk"; ensure the tree connector
characters adapt so that if .env.local is added it uses "├──" for convex and
"└──" for .env.local, otherwise convex uses "└──". Update the logic that builds
the structure array to unconditionally push the convex line and conditionally
push the .env.local line with the appropriate connector based on whether auth is
"clerk".

Comment on lines +72 to +73
const clerkInstructions =
isConvex && config.auth === "clerk" ? getClerkInstructions() : "";

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.

🛠️ Refactor suggestion

Deduplicate Clerk instructions; keep a single source of truth.

You compute clerkInstructions and also print a separate Clerk section inside the Convex flow. This causes duplicate guidance and confusing step numbering. Recommend keeping the consolidated getClerkInstructions() section and removing the inline block below (Lines 125–132).

🤖 Prompt for AI Agents
In apps/cli/src/helpers/core/post-installation.ts around lines 72-73, you assign
clerkInstructions via getClerkInstructions() but then duplicate the same Clerk
guidance inline in the Convex flow later; remove the inline Clerk block at lines
125–132 so only the consolidated clerkInstructions (from getClerkInstructions())
is printed, and adjust any step numbering or surrounding text to account for the
removed block to avoid duplicate guidance and confusing numbering.

Comment on lines +125 to +132
if (config.auth === "clerk") {
output += `${pc.cyan(`${stepCounter++}.`)} ${pc.bold("Clerk Setup:")}\n${pc.dim(
" Follow the Convex + Clerk guide to configure authentication:",
)}\n${pc.cyan(" ")}${pc.underline("https://docs.convex.dev/auth/clerk")}\n\n`;
output += `${pc.cyan(`${stepCounter++}.`)} ${pc.bold("Required Environment Variables:")}\n`;
output += `${pc.dim(" •")} Set CLERK_JWT_ISSUER_DOMAIN in Convex Dashboard\n`;
output += `${pc.dim(" •")} Set CLERK_PUBLISHABLE_KEY in apps/*/.env\n`;
}

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.

⚠️ Potential issue

Remove inline Clerk steps to avoid duplication in “Next steps”.

These lines duplicate the content appended via clerkInstructions and also inflate stepCounter. Drop this inline block and rely on the consolidated section appended later.

Apply this diff:

-    if (config.auth === "clerk") {
-      output += `${pc.cyan(`${stepCounter++}.`)} ${pc.bold("Clerk Setup:")}\n${pc.dim(
-        "   Follow the Convex + Clerk guide to configure authentication:",
-      )}\n${pc.cyan("   ")}${pc.underline("https://docs.convex.dev/auth/clerk")}\n\n`;
-      output += `${pc.cyan(`${stepCounter++}.`)} ${pc.bold("Required Environment Variables:")}\n`;
-      output += `${pc.dim("   •")} Set CLERK_JWT_ISSUER_DOMAIN in Convex Dashboard\n`;
-      output += `${pc.dim("   •")} Set CLERK_PUBLISHABLE_KEY in apps/*/.env\n`;
-    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (config.auth === "clerk") {
output += `${pc.cyan(`${stepCounter++}.`)} ${pc.bold("Clerk Setup:")}\n${pc.dim(
" Follow the Convex + Clerk guide to configure authentication:",
)}\n${pc.cyan(" ")}${pc.underline("https://docs.convex.dev/auth/clerk")}\n\n`;
output += `${pc.cyan(`${stepCounter++}.`)} ${pc.bold("Required Environment Variables:")}\n`;
output += `${pc.dim(" •")} Set CLERK_JWT_ISSUER_DOMAIN in Convex Dashboard\n`;
output += `${pc.dim(" •")} Set CLERK_PUBLISHABLE_KEY in apps/*/.env\n`;
}
🤖 Prompt for AI Agents
In apps/cli/src/helpers/core/post-installation.ts around lines 125 to 132,
remove the inline Clerk instructions block (the three output += additions that
print "Clerk Setup" and "Required Environment Variables") because it duplicates
clerkInstructions and incorrectly increments stepCounter; delete that entire if
(config.auth === "clerk") { ... } block and ensure you do not increment
stepCounter for this removed section so the consolidated clerkInstructions
appended later remains the single source of Clerk content and numbering remains
correct.

Comment on lines +62 to +71
- `--auth clerk` (if compatible frontends selected, otherwise `none`)
- `--database none` (Convex provides database)
- `--orm none` (Convex provides data layer)
- `--api none` (Convex provides API)
- `--runtime none` (Convex manages runtime)
- `--db-setup none` (Convex manages hosting)
- `--examples todo` (Todo example works with Convex)

**Note:** Convex supports Clerk authentication with compatible frontends (React frameworks, Next.js, TanStack Start, and native frameworks). Nuxt, Svelte, and Solid are not compatible with Clerk.

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.

💡 Verification agent

🧩 Analysis chain

Docs likely overstate auto-setting --auth clerk for Convex.

Current code doesn’t set auth automatically in presets; selection flows through prompts. Rephrase to “defaults” or implement the auto-set in code.

-- `--auth clerk` (if compatible frontends selected, otherwise `none`)
+Defaults to Clerk when using Convex (if compatible frontends are selected), otherwise `none`.

If you want true auto-setting, I can provide a patch in gatherConfig to set result.auth after frontend selection.


🏁 Script executed:

#!/bin/bash
set -e

# Locate gatherConfig function definitions across TypeScript files
rg -n "gatherConfig" --type ts

# Search for where 'auth' is assigned or defaulted in CLI config gathering
rg -nP "auth" -C3 --type ts

# Search for any preset-specific logic (e.g., 'convex') in the config gathering code
rg -nP "(preset|Convex)" -C3 --type ts

Length of output: 225424


Clarify --auth behavior for Convex
Update the snippet in apps/web/content/docs/cli/compatibility.mdx to reflect that Clerk is the prompt default, not an automatic flag:

- `--auth clerk` (if compatible frontends selected, otherwise `none`)
+ Defaults to Clerk (prompt default) when using Convex with compatible frontends; otherwise `none`.

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 LanguageTool

[style] ~70-~70: Consider using “incompatible” to avoid wordiness.
Context: ...rameworks). Nuxt, Svelte, and Solid are not compatible with Clerk. #### No Backend When using...

(NOT_ABLE_PREMIUM)

🤖 Prompt for AI Agents
In apps/web/content/docs/cli/compatibility.mdx around lines 62 to 71, the
snippet incorrectly implies that `--auth clerk` is automatically applied for
Convex; change the text to clarify that Clerk is the CLI prompt default when a
compatible frontend is detected (so the flag is suggested, not auto-applied),
e.g. replace the line to indicate “--auth clerk (CLI prompt default when
compatible frontends selected; otherwise none or user must opt-in)”, and adjust
any surrounding wording so it explicitly states the CLI only suggests Clerk
rather than enabling it automatically.

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