init script: add projectId and pck to next client app#911
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Other AI code review bot(s) detectedCodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review. WalkthroughIntroduces an interactive-question subsystem with an --on-question mode, replaces the old --agent-mode flag in scripts, propagates mode-driven behavior through CLI flows (project-path, package-manager, prompts), expands bun detection, and switches generated Next.js wiring to client-oriented env and app imports. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Dev as Developer (CLI)
participant CLI as init-stack CLI
participant Resolver as OnQuestionResolver
participant FS as FileSystem/Env
participant PM as Package Manager Detector
participant Generator as Code Generator (Next/JS)
Dev->>CLI: run init-stack (flags, --on-question)
CLI->>Resolver: resolveOnQuestionMode(flags, env)
CLI->>FS: inspect project path, package.json, lockfiles
FS-->>PM: report lockfiles (bun.lock / bun.lockb / package-lock / pnpm-lock / yarn.lock)
PM-->>Resolver: deterministic or ambiguous manager
Resolver-->>CLI: decision (prompt / guess / error)
alt decision = error (non-interactive)
CLI-->>Dev: throw UnansweredQuestionError / UserError (re-run guidance)
else decision = guess/default
CLI->>Generator: generate client wiring (stackClientApp, nextClientOptions with NEXT_PUBLIC_*)
Generator-->>FS: write files (layout, app, env wiring)
CLI->>PM: select install command (npm/yarn/pnpm/bun) per resolved mode
CLI-->>Dev: finish (files written / instructions)
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
🧰 Additional context used📓 Path-based instructions (1)**/*.{ts,tsx,js,jsx}📄 CodeRabbit inference engine (AGENTS.md)
Files:
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
🔇 Additional comments (5)
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. Comment |
There was a problem hiding this comment.
Greptile Summary
This PR enhances the Stack initialization script to properly support Next.js client-side applications. The main changes include:
-
Next.js Client Configuration: Adds a new
nextClientOptionssection that conditionally includesprojectIdandpublishableClientKeyparameters when initializing Next.js client apps. These values are passed via command-line arguments and use Next.js environment variable fallback patterns (process.env.NEXT_PUBLIC_STACK_PROJECT_ID ?? 'fallback'). -
Layout File Import Fix: Corrects the import statement in the layout file to use
stackClientAppinstead ofstackServerApp, which is critical for client-side functionality. -
Bun Lock File Detection: Updates the lock file detection to support both
bun.lockbandbun.lockformats for better Bun version compatibility.
The implementation follows Next.js conventions for public environment variables and ensures that client-side Stack applications are properly configured during project initialization. The environment variable fallback pattern allows for flexible configuration while providing sensible defaults from the command-line arguments.
Confidence score: 4/5
- This PR appears safe to merge with good implementation of Next.js patterns and proper client/server separation
- Score reflects solid implementation but limited context on edge cases and testing coverage for the init script
- Pay close attention to the client app import fix in the layout file as using server app on client would cause runtime errors
1 file reviewed, 1 comment
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/init-stack/src/index.ts (1)
626-635: Apply the same safe-quoting in JS client/server pathsSame risk exists here; JSON.stringify the fallbacks so user input can’t break codegen.
- const publishableClientKeyWrite = clientOrServer === "server" - ? `process.env.STACK_PUBLISHABLE_CLIENT_KEY ${publishableClientKeyFromArgs ? `|| '${publishableClientKeyFromArgs}'` : ""}` - : `'${publishableClientKeyFromArgs ?? 'INSERT_YOUR_PUBLISHABLE_CLIENT_KEY_HERE'}'`; + const publishableClientKeyWrite = clientOrServer === "server" + ? `process.env.STACK_PUBLISHABLE_CLIENT_KEY${publishableClientKeyFromArgs ? ` || ${JSON.stringify(publishableClientKeyFromArgs)}` : ""}` + : `${JSON.stringify(publishableClientKeyFromArgs ?? 'INSERT_YOUR_PUBLISHABLE_CLIENT_KEY_HERE')}`; @@ - `${projectIdFromArgs ? `${indentation}projectId: '${projectIdFromArgs}',` : ""}`, + `${projectIdFromArgs ? `${indentation}projectId: ${JSON.stringify(projectIdFromArgs)},` : ""}`,
🧹 Nitpick comments (1)
packages/init-stack/src/index.ts (1)
856-857: Optional: add newlines/indentation for cleaner diffs and readabilityThis keeps the DOM identical but makes the injected wrapper easier to read.
- const insertOpen = "<StackProvider app={stackClientApp}><StackTheme>"; - const insertClose = "</StackTheme></StackProvider>"; + const insertOpen = `\n${indentation}<StackProvider app={stackClientApp}>\n${indentation}${indentation}<StackTheme>\n`; + const insertClose = `\n${indentation}${indentation}</StackTheme>\n${indentation}</StackProvider>\n`;Please also confirm the intended order is Provider outside Theme.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
-
packages/init-stack/src/index.ts(5 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (AGENTS.md)
Prefer ES6 Map over Record when representing key–value collections
Files:
packages/init-stack/src/index.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Security Check
🔇 Additional comments (4)
packages/init-stack/src/index.ts (4)
656-656: Object assembly reads cleanThe ${jsOptions}${nextClientOptions} concatenation is syntactically safe given the trailing commas in each injected line.
829-829: Switch to client app import in root layout — LGTMCorrectly targets the client app and pairs with the provider usage below.
946-946: Bun lockfile detection broadened — LGTMCovers both bun.lockb and bun.lock.
637-646: Escape CLI-provided values in nextClientOptions to avoid broken code/injectionUse JSON.stringify so quotes/newlines in args don’t break the generated object literal.
- projectIdFromArgs ? `${indentation}projectId: process.env.NEXT_PUBLIC_STACK_PROJECT_ID ?? '${projectIdFromArgs}',` : "", - publishableClientKeyFromArgs ? `${indentation}publishableClientKey: process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY ?? '${publishableClientKeyFromArgs}',` : "", + projectIdFromArgs ? `${indentation}projectId: process.env.NEXT_PUBLIC_STACK_PROJECT_ID ?? ${JSON.stringify(projectIdFromArgs)},` : "", + publishableClientKeyFromArgs ? `${indentation}publishableClientKey: process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY ?? ${JSON.stringify(publishableClientKeyFromArgs)},` : "",
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/init-stack/src/index.ts (1)
572-586: Escape values written into .env to avoid breaking the fileIf projectId/pck contain quotes or newlines, .env.local can be malformed. Escape before writing.
Apply this diff:
- `NEXT_PUBLIC_STACK_PROJECT_ID="${projectIdFromArgs ?? ""}"\n` + - `NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY="${publishableClientKeyFromArgs ?? ""}"\n` + + `NEXT_PUBLIC_STACK_PROJECT_ID="${escapeEnvValue(projectIdFromArgs ?? "")}"\n` + + `NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY="${escapeEnvValue(publishableClientKeyFromArgs ?? "")}"\n` + ... - `NEXT_PUBLIC_STACK_PROJECT_ID="${projectIdFromArgs ?? ""}"\n` + - `NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY="${publishableClientKeyFromArgs ?? ""}"\n` + + `NEXT_PUBLIC_STACK_PROJECT_ID="${escapeEnvValue(projectIdFromArgs ?? "")}"\n` + + `NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY="${escapeEnvValue(publishableClientKeyFromArgs ?? "")}"\n` +Add this helper (outside the shown range):
function escapeEnvValue(v: string): string { return v.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n"); }
🧹 Nitpick comments (4)
packages/init-stack/src/index.ts (4)
36-53: Non-interactive env detection could include more CI signalsOptional: consider adding TF_BUILD, GITLAB_CI, BUILDKITE, and JENKINS_URL for broader CI coverage.
865-865: Layout import switched to client app: correctImporting stackClientApp for layout usage matches the client-provider strategy.
Also consider making getUpdatedLayout idempotent (skip if StackProvider/stackClientApp already present) to allow safe re-runs without duplicate imports/wrappers.
948-953: Project path resolution in "guess" mode could try auto-discoveryOptional: in "guess", attempt to locate a package.json in common locations (./, ./app, ./packages/*) before failing. Keeps the “guess” spirit.
996-999: Package manager guessing defaultReturning npm in "guess" is fine. Optional enhancement: consider using npm_config_user_agent to infer the runner when multiple lockfiles are absent.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
packages/init-stack/package.json(1 hunks)packages/init-stack/src/index.ts(13 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (AGENTS.md)
Prefer ES6 Map over Record when representing key–value collections
Files:
packages/init-stack/src/index.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
- GitHub Check: all-good
- GitHub Check: docker
- GitHub Check: restart-dev-and-test
- GitHub Check: build (22.x)
- GitHub Check: build (22.x)
- GitHub Check: setup-tests
- GitHub Check: lint_and_build (latest)
- GitHub Check: Security Check
🔇 Additional comments (12)
packages/init-stack/package.json (1)
21-31: Scripts: switch to --on-question error looks goodDeterministic CI runs via --on-question error across all test scripts make sense and align with the new CLI behavior.
packages/init-stack/src/index.ts (11)
27-32: UserError class: clear separation of user vs system errorsGood choice to standardize user-facing failures without noisy stack traces.
55-64: on-question mode resolution LGTMSane defaults (error in CI, ask locally) and strict validation via UserError.
87-87: CLI flag: --on-questionFlag wiring and default “default” mode look consistent with resolver.
105-106: Resolved once, used everywhereSingle source of truth for onQuestionMode is clean.
296-297: Package names are safely quoted before shell executionPrevents shell interpretation/globbing; good hardening.
471-476: Type inference flow for on-question is sound
- guess → fallback to "js"
- error → explicit guidance
892-894: Provider insertion order is appropriateWrapper order … looks right.
789-797: Non-interactive ready-checkBypassing the confirm prompt unless on "ask" mode is consistent with the new model.
807-810: Server/client selection under on-question
- guess → both
- error → explicit guidance
Good UX.
985-985: Bun lockfile detectionCovers both bun.lockb and bun.lock. Nice.
672-681: Quote/escape injected literals in generated client optionsUnescaped quotes in projectId/pck will break the generated TS. Use JSON.stringify for safe embedding.
Apply this diff:
- projectIdFromArgs ? `${indentation}projectId: process.env.NEXT_PUBLIC_STACK_PROJECT_ID ?? '${projectIdFromArgs}',` : "", - publishableClientKeyFromArgs ? `${indentation}publishableClientKey: process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY ?? '${publishableClientKeyFromArgs}',` : "", + projectIdFromArgs ? `${indentation}projectId: process.env.NEXT_PUBLIC_STACK_PROJECT_ID ?? ${JSON.stringify(projectIdFromArgs)},` : "", + publishableClientKeyFromArgs ? `${indentation}publishableClientKey: process.env.NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY ?? ${JSON.stringify(publishableClientKeyFromArgs)},` : "",
Apply suggested changes
|
You have run out of free Bugbot PR reviews for this billing cycle. This will reset on October 10. To receive reviews on all of your PRs, visit the Cursor dashboard to activate Pro and start your 14-day free trial. |
There was a problem hiding this comment.
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)
packages/init-stack/src/index.ts (1)
796-829: Reintroduce the missinggetServerOrClientOrBothmethodThe block that starts with
if (onQuestionMode === "error") { … }is now outside of any method. This deletesSteps.getServerOrClientOrBoth, trips the TypeScript parser (see the CI failure on Line 808), and breaks the CLI. Please restore the method declaration and fold the newonQuestionlogic into it.- if (onQuestionMode === "error") { - throw new UnansweredQuestionError("Ambiguous installation type. Re-run with --server, --client, or both"); - } - if (isServer) return ["server"]; - if (isClient) return ["client"]; - - if (onQuestionMode === "guess") return ["server", "client"]; - if (onQuestionMode === "error") { - throw new UserError("Ambiguous installation type. Re-run with --server, --client, or both."); - } - - return (await inquirer.prompt([ - { - type: "list", - name: "type", - message: "Do you want to use Stack Auth on the server, or on the client?", - choices: [ - { name: "Client (eg. Vite, HTML)", value: ["client"] }, - { name: "Server (eg. Node.js)", value: ["server"] }, - { name: "Both", value: ["server", "client"] } - ] - } - ])).type; - }, + async getServerOrClientOrBoth(): Promise<("server" | "client")[]> { + if (isServer && isClient) return ["server", "client"]; + if (isServer) return ["server"]; + if (isClient) return ["client"]; + + if (onQuestionMode === "guess") { + return ["server", "client"]; + } + if (onQuestionMode === "error") { + throw new UnansweredQuestionError("Ambiguous installation type. Re-run with --server, --client, or both"); + } + + return (await inquirer.prompt([ + { + type: "list", + name: "type", + message: "Do you want to use Stack Auth on the server, or on the client?", + choices: [ + { name: "Client (eg. Vite, HTML)", value: ["client"] }, + { name: "Server (eg. Node.js)", value: ["server"] }, + { name: "Both", value: ["server", "client"] } + ] + } + ])).type; + },
🧹 Nitpick comments (1)
packages/init-stack/package.json (1)
28-31: Consider wiring keyed flows into the aggregate test-runThe new
test-run-keys-*scripts won’t execute duringpnpm run test-run, so regressions in the projectId/publishableClientKey path could slip by. Consider appending these scripts (or an equivalent smoke test) to the aggregate runner so that the keyed scenario stays covered in CI.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
packages/init-stack/package.json(1 hunks)packages/init-stack/src/index.ts(12 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (AGENTS.md)
Prefer ES6 Map over Record when representing key–value collections
Files:
packages/init-stack/src/index.ts
🪛 GitHub Actions: Runs E2E API Tests with external source of truth
packages/init-stack/src/index.ts
[error] 808-808: ESBuild: Expected ')' but found '===' at src/index.ts:808. TS1005: ',' expected.
🪛 GitHub Actions: Runs E2E API Tests
packages/init-stack/src/index.ts
[error] 808-808: Esbuild/TypeScript parse error: Expected ")" but found "===" at src/index.ts:808. TS1005: "," expected.
🪛 GitHub Actions: Run setup tests
packages/init-stack/src/index.ts
[error] 808-808: TS1005: ',' expected. Build failed: Esbuild/TS parsing error - 'if (onQuestionMode === "error") {' line 808 indicates a syntax issue (likely an extra closing parenthesis).
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: docker
- GitHub Check: docker
- GitHub Check: restart-dev-and-test
- GitHub Check: all-good
- GitHub Check: Security Check
🔇 Additional comments (1)
packages/init-stack/package.json (1)
21-31: Deterministic CLI runs via--on-question errorNice call switching the scripted runs over to
--on-question error; this lines up with the new prompt controller and keeps CI from hanging on interactive questions.
High-level PR Summary
This PR enhances the initialization script for Stack Auth by adding support for
projectIdandpublishableClientKey(pck) parameters when initializing a Next.js client application. The changes include: 1) Adding logic to pass these parameters from environment variables or directly from arguments to the Next.js client configuration, 2) Updating the layout template to use the client-side Stack app instead of the server-side app in the provider component, and 3) Improving Bun lock file detection by checking for bothbun.lockbandbun.lockformats. These changes ensure proper configuration of Next.js client applications with the required Stack Auth credentials.⏱️ Estimated Review Time: 5-15 minutes
💡 Review Order Suggestion
packages/init-stack/src/index.tsImportant
Enhances Stack Auth init script with
projectIdandpublishableClientKeysupport, updates Next.js layout, and improves Bun detection.projectIdandpublishableClientKeysupport to Next.js client configuration inindex.ts.getUpdatedLayout().promptPackageManager().--on-questionoption to control interactive prompts inindex.ts.--on-question errorinpackage.json.This description was created by
for 67a98f5. You can customize this summary. It will automatically update as commits are pushed.
Review by RecurseML
🔍 Review performed on 7a0bf86..0b443e4
✨ No bugs found, your code is sparkling clean
✅ Files analyzed, no issues (1)
•
packages/init-stack/src/index.tsSummary by CodeRabbit