Skip to content

init stack cli project-id and publishable-client-key args#888

Merged
BilalG1 merged 6 commits intodevfrom
init-stack-more-args
Sep 11, 2025
Merged

init stack cli project-id and publishable-client-key args#888
BilalG1 merged 6 commits intodevfrom
init-stack-more-args

Conversation

@BilalG1
Copy link
Contributor

@BilalG1 BilalG1 commented Sep 10, 2025


Important

Add CLI options for project ID and publishable client key, update initialization process, and modify documentation to reflect changes.

  • CLI Options:
    • Added --project-id and --publishable-client-key options to index.ts for CLI setup.
  • Initialization:
    • Updated writeEnvVars() in index.ts to include project ID and publishable client key in .env.local.
    • Modified writeStackAppFile() in index.ts to handle new CLI options.
  • Documentation:
    • Updated references from stack.ts to stack/client.ts and stack/server.ts in multiple .mdx files.
    • Added examples for using project ID and publishable client key in setup.mdx and example-pages.mdx.
  • Testing:
    • Added test-run-keys-next and test-run-keys-js scripts in package.json for testing new CLI options.

This description was created by Ellipsis for b204910. You can customize this summary. It will automatically update as commits are pushed.


Review by RecurseML

🔍 Review performed on bd14f6b..92c332a

✨ No bugs found, your code is sparkling clean

✅ Files analyzed, no issues (2)

packages/init-stack/src/index.ts
apps/dashboard/src/app/(main)/(protected)/(outside-dashboard)/new-project/page-client.tsx

⏭️ Files skipped (trigger manually) (1)
Locations Trigger Analysis
packages/init-stack/package.json Analyze

Need help? Join our Discord

Summary by CodeRabbit

  • New Features

    • Init tool accepts project ID and publishable client key; generated projects include those values in client/server outputs and env hints.
    • Next.js projects now generate both client and server app artifacts using a standardized client/server layout.
  • UI

    • Removed the vertical divider on the New Project page for a cleaner preview/form layout.
  • Documentation

    • Updated docs and examples to reference the new client/server file split.
  • Chores

    • Added key-based test-run scripts for Next.js and JS.

@vercel
Copy link

vercel bot commented Sep 10, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
stack-backend Ready Ready Preview Comment Sep 11, 2025 1:47am
stack-dashboard Ready Ready Preview Comment Sep 11, 2025 1:47am
stack-demo Ready Ready Preview Comment Sep 11, 2025 1:47am
stack-docs Ready Ready Preview Comment Sep 11, 2025 1:47am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 10, 2025

Note

Other AI code review bot(s) detected

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

Walkthrough

Renames the single generated Stack app into separate server/client files and updates imports/docs accordingly; removes a vertical Separator in the dashboard New Project page; extends packages/init-stack with two key-based test scripts and CLI options to emit project and publishable-client keys and generate stack/server and stack/client artifacts.

Changes

Cohort / File(s) Summary
Dashboard UI tweak
apps/dashboard/src/app/(main)/(protected)/(outside-dashboard)/new-project/page-client.tsx
Removed the vertical Separator between the left form column and right preview column. No changes to form state, validation, submission, or routing.
Projects / Next.js setup page
apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/(overview)/setup-page.tsx
Updated instructions and example imports to reference stack/client (client) and stack/server (server) paths instead of the single stack.ts.
Init-stack package scripts
packages/init-stack/package.json
Added test-run-keys-next and test-run-keys-js scripts to run key-based, non-interactive init-stack flows for Next.js and JS templates; preserved existing test-run-next.
Init-stack CLI and generators
packages/init-stack/src/index.ts
Added CLI options --project-id and --publishable-client-key; env templates now populate NEXT_PUBLIC_STACK_PROJECT_ID and NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY from args; writeStackAppFile now accepts `("server"
Docs — getting-started & customization & examples
docs/templates/... (e.g., getting-started/*, customization/*, concepts/oauth.mdx, page-examples/*)
Documentation and code-sample updates to split references from stack.ts into stack/server.ts and/or stack/client.ts; updated example imports and code-block titles. No logic changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant CI as User / CI
  participant CLI as init-stack CLI
  participant Parser as Arg Parser
  participant Steps as Steps (Generators)
  participant FS as Filesystem

  CI->>CLI: run init-stack [--next|--js] --project-id X --publishable-client-key Y
  CLI->>Parser: parse args
  Parser-->>CLI: {projectId, publishableClientKey, target}

  CLI->>Steps: getServerOrClientOrBoth()
  Steps-->>CLI: ["server","client"] or subset

  loop per target
    CLI->>Steps: writeStackAppFile(options, "server"|"client")
    Steps->>Steps: determine publishableClientKey emission (env var vs literal/placeholder)
    Steps->>FS: write files to stack/server or stack/client
    FS-->>Steps: success
  end

  CLI->>Steps: generate env templates
  Steps->>FS: write NEXT_PUBLIC_* values from args (or blank)
  FS-->>CLI: finished
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • N2D4

Pre-merge checks (3 passed)

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The current title accurately and concisely summarizes the primary change—adding project-id and publishable-client-key CLI arguments to the init-stack CLI—and directly reflects the PR objectives and modified files, so a reviewer scanning history will understand the main intent.
Description Check ✅ Passed The PR description includes the repository template header and provides a clear, structured summary of the changes (CLI options, env updates, stack app generation, docs updates, and test scripts) and includes the RecurseML review, which makes it sufficiently detailed for reviewers to understand scope and impacts.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

Poem

I nudge the pane where columns met,
A seam erased — a tidy set.
Keys in paw, I stitch the stacks,
Client, server — no more cracks.
Env winds hum IDs bright and true. 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch init-stack-more-args

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

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

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Summary

This PR enhances the init-stack CLI tool by adding two new command-line arguments: --project-id and --publishable-client-key. These arguments allow developers to pre-configure Stack Auth credentials during project initialization, eliminating the need for manual copy-pasting from the dashboard afterward.

The changes span three files:

  1. CLI Implementation (packages/init-stack/src/index.ts): Adds argument parsing for the new options, modifies environment variable writing to use provided values, and updates Stack app file generation to embed the credentials directly
  2. Testing Infrastructure (packages/init-stack/package.json): Introduces two test scripts (test-run-keys-next and test-run-keys-js) to validate the new functionality in both Next.js and SvelteKit environments
  3. UI Cleanup (apps/dashboard/src/app/(main)/(protected)/(outside-dashboard)/new-project/page-client.tsx): Removes a vertical separator component from the new project creation page for cleaner visual layout

The implementation handles different project types appropriately - for Next.js projects, credentials are written to .env.local files, while for vanilla JavaScript projects, they're embedded directly in the Stack app configuration files. When no arguments are provided, the tool falls back to placeholder text as before, maintaining backward compatibility.

Confidence score: 2/5

  • This PR has a critical bug that will cause immediate issues in production
  • Score lowered due to duplicate client-side Stack app file generation on line 202 in index.ts, which will overwrite previous configurations
  • Pay close attention to packages/init-stack/src/index.ts line 202 where duplicate file generation occurs

3 files reviewed, 3 comments

Edit Code Review Bot Settings | Greptile

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (2)
packages/init-stack/src/index.ts (2)

601-604: Sanitize publishable key before embedding in generated code

Direct interpolation can break code generation or enable code injection if the key contains quotes/newlines. Use JSON.stringify. (Same concern noted previously.)

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

615-617: Sanitize projectId before embedding

Same issue: wrap with JSON.stringify. (Previously flagged.)

- type === "js" && projectIdFromArgs ? `\n${indentation}projectId: '${projectIdFromArgs}',` : ""}${
+ type === "js" && projectIdFromArgs ? `\n${indentation}projectId: ${JSON.stringify(projectIdFromArgs)},` : ""}${
🧹 Nitpick comments (3)
packages/init-stack/package.json (1)

27-29: Keyed test-run scripts added — consider cross-shell quoting for --import-alias

Looks good functionally. Minor: single quotes around --import-alias can break on Windows shells. Prefer no quotes or double quotes.

Apply this diff if you want a safer default:

-    "test-run-next": "rimraf test-run-output && npx -y create-next-app@latest test-run-output --app --ts --no-src-dir --tailwind --use-npm --eslint --import-alias '##@#/*' --turbopack && STACK_DISABLE_INTERACTIVE=true pnpm run init-stack:local test-run-output",
+    "test-run-next": "rimraf test-run-output && npx -y create-next-app@latest test-run-output --app --ts --no-src-dir --tailwind --use-npm --eslint --import-alias \"##@#/*\" --turbopack && STACK_DISABLE_INTERACTIVE=true pnpm run init-stack:local test-run-output",
packages/init-stack/src/index.ts (2)

519-526: Quote .env values to avoid breakage with special characters

If args contain spaces/newlines/quotes, the generated .env can break parsing. Quote via JSON.stringify.

Apply this diff in both branches:

-          `NEXT_PUBLIC_STACK_PROJECT_ID=${projectIdFromArgs ?? ""}\n` +
-          `NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY=${publishableClientKeyFromArgs ?? ""}\n` +
+          `NEXT_PUBLIC_STACK_PROJECT_ID=${projectIdFromArgs !== undefined ? ${"JSON.stringify(projectIdFromArgs)"} : ""}\n` +
+          `NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY=${publishableClientKeyFromArgs !== undefined ? ${"JSON.stringify(publishableClientKeyFromArgs)"} : ""}\n` +

578-582: Avoid unnecessary type assertion

Map the union without casting.

-    const clientOrServerCap = {
-      client: "Client",
-      server: "Server",
-    }[clientOrServer as string] ?? throwErr("unknown clientOrServer " + clientOrServer);
+    const clientOrServerCap = ({ client: "Client", server: "Server" } as const)[clientOrServer];
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bd14f6b and 471888c.

📒 Files selected for processing (3)
  • apps/dashboard/src/app/(main)/(protected)/(outside-dashboard)/new-project/page-client.tsx (0 hunks)
  • packages/init-stack/package.json (1 hunks)
  • packages/init-stack/src/index.ts (8 hunks)
💤 Files with no reviewable changes (1)
  • apps/dashboard/src/app/(main)/(protected)/(outside-dashboard)/new-project/page-client.tsx
🧰 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
🧬 Code graph analysis (1)
packages/init-stack/src/index.ts (1)
packages/stack-shared/src/utils/errors.tsx (1)
  • throwErr (10-19)
⏰ 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). (9)
  • GitHub Check: docker
  • GitHub Check: all-good
  • GitHub Check: lint_and_build (latest)
  • GitHub Check: build (22.x)
  • GitHub Check: restart-dev-and-test
  • GitHub Check: build (22.x)
  • GitHub Check: docker
  • GitHub Check: setup-tests
  • GitHub Check: Security Check
🔇 Additional comments (4)
packages/init-stack/src/index.ts (4)

45-47: CLI args for project-id and publishable-client-key — LGTM

Names, Commander parsing, and help text are consistent.


63-64: Options mapping — LGTM

Commander camelCase access (projectId, publishableClientKey) is correct.


202-204: Double generation in Next.js: confirm intent

Generating both client and server Stack apps for Next is a product decision. If intentional, ensure all imports use the new locations (see import-path fix below).


694-709: Client/server selection API — LGTM

Clear return type and arg handling.

@BilalG1 BilalG1 requested a review from N2D4 September 10, 2025 18:56
@BilalG1 BilalG1 removed their assignment Sep 10, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

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)

608-613: Next client file incorrectly marked server-only

The template always adds import "server-only" for Next, which will crash if this is a client file. Gate it on server only.

Apply:

-${type === "next" ? `import "server-only";` : ""}
+${type === "next" && clientOrServer === "server" ? `import "server-only";` : ""}

If you keep the Next client file, also switch tokenStore to "cookie" (not "nextjs-cookie") for the client variant.

♻️ Duplicate comments (3)
packages/init-stack/src/index.ts (3)

601-604: Code injection/broken syntax risk when embedding keys — use JSON.stringify

Directly interpolating publishableClientKeyFromArgs into generated code can break on quotes and enables code injection. Use JSON.stringify for safe literal emission (server fallback and client literal).

Apply:

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

615-617: Use JSON.stringify for projectId to avoid broken code and injection

Embedding projectIdFromArgs in quotes will break if the value contains quotes; JSON.stringify fixes this and prevents injection.

-type === "js" && projectIdFromArgs ? `\n${indentation}projectId: '${projectIdFromArgs}',` : ""}${
+type === "js" && projectIdFromArgs ? `\n${indentation}projectId: ${JSON.stringify(projectIdFromArgs)},` : ""}${

639-643: Make the server app import path robust for src/ and non-src projects

Hardcoding "../../../stack/server" fails in projects without a src/ folder (it should be "../../stack/server"). Compute the relative path dynamically.

Apply:

     const handlerPath = handlerPathWithoutExtension + "." + handlerFileExtension;
     const handlerContent = await readFile(handlerPath);
+    const serverAppImportRel = path
+      .relative(path.dirname(handlerPath), path.join(projectInfo.srcPath, "stack", "server"))
+      .split(path.sep).join("/");
@@
-    laterWriteFileIfNotExists(
+    laterWriteFileIfNotExists(
       handlerPath,
-      `import { StackHandler } from "@stackframe/stack";\nimport { stackServerApp } from "../../../stack/server";\n\nexport default function Handler(props${
+      `import { StackHandler } from "@stackframe/stack";\nimport { stackServerApp } from "${serverAppImportRel}";\n\nexport default function Handler(props${
         handlerFileExtension.includes("ts") ? ": unknown" : ""
       }) {\n${projectInfo.indentation}return <StackHandler fullPage app={stackServerApp} routeProps={props} />;\n}\n`
     );
🧹 Nitpick comments (2)
packages/init-stack/src/index.ts (2)

519-526: .env authoring: quote or validate values

If projectId/publishable key include characters like spaces, #, or newlines, the .env can be corrupted. Either:

  • Quote values (dotenv supports quoted strings), or
  • Validate against a safe charset and fallback to empty string with a warning.

Example (quoting):

-`NEXT_PUBLIC_STACK_PROJECT_ID=${projectIdFromArgs ?? ""}\n` +
-`NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY=${publishableClientKeyFromArgs ?? ""}\n` +
+`NEXT_PUBLIC_STACK_PROJECT_ID="${projectIdFromArgs ?? ""}"\n` +
+`NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY="${publishableClientKeyFromArgs ?? ""}"\n` +

575-583: Simplify mapping; also consider legacy stack.ts detection

  • Nit: no need for the string cast or map. A ternary is simpler and type-safe.
  • Optional: migrating from the legacy single file (stack.ts) won’t be detected now that paths moved to stack/server|client. Consider checking for a legacy file and bailing with a migration hint.

Proposed simplification:

-const clientOrServerCap = {
-  client: "Client",
-  server: "Server",
-}[clientOrServer as string] ?? throwErr("unknown clientOrServer " + clientOrServer);
+const clientOrServerCap = clientOrServer === "client" ? "Client" : "Server";
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 471888c and cf8f1bd.

📒 Files selected for processing (1)
  • packages/init-stack/src/index.ts (10 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
🧬 Code graph analysis (1)
packages/init-stack/src/index.ts (1)
packages/stack-shared/src/utils/errors.tsx (1)
  • throwErr (10-19)
⏰ 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). (9)
  • GitHub Check: lint_and_build (latest)
  • GitHub Check: build (22.x)
  • GitHub Check: all-good
  • GitHub Check: build (22.x)
  • GitHub Check: restart-dev-and-test
  • GitHub Check: docker
  • GitHub Check: docker
  • GitHub Check: setup-tests
  • GitHub Check: Security Check
🔇 Additional comments (5)
packages/init-stack/src/index.ts (5)

45-47: CLI: New args look good

Flags are well named and documented. Commander will expose them as options.projectId/options.publishableClientKey, which you use below.


63-65: Arg plumbing verified

Reading options into projectIdFromArgs/publishableClientKeyFromArgs is correct.


694-709: Typed return for getServerOrClientOrBoth is solid

Tightening the return type to Array<"server" | "client"> improves downstream safety.


752-753: Import path fix in layout is correct

Switching to ../stack/server matches the new file layout.


202-203: ```shell
#!/bin/bash
set -euo pipefail

echo "=== packages/init-stack/src/index.ts (lines 1-240) ==="
sed -n '1,240p' packages/init-stack/src/index.ts || true
echo

echo "=== packages/init-stack/src/index.ts (lines 560-620) ==="
sed -n '560,620p' packages/init-stack/src/index.ts || true
echo

echo "=== search: writeStackAppFile ==="
rg -n -C3 "writeStackAppFile" packages || true
echo

echo "=== search: Steps.writeStackAppFile ==="
rg -n -C3 "Steps.writeStackAppFile" packages || true
echo

echo "=== search: definition/occurrences of Steps (class/const/export) ==="
rg -n -C3 "class Steps" packages || true
rg -n -C3 "export const Steps" packages || true
rg -n -C3 "const Steps" packages || true
echo

echo "=== search: import "server-only" or server-only ==="
rg -n -C3 'server-only' packages || true
echo

echo "=== search: @StackFrame references ==="
rg -n -C3 '@StackFrame' packages || true
echo

echo "=== search: StackClientApp symbol ==="
rg -n -C3 'StackClientApp' packages || true
echo

echo "=== search: tokenStore ==="
rg -n -C3 'tokenStore' packages || true
echo

echo "=== show packages/init-stack/package.json (if present) ==="
sed -n '1,240p' packages/init-stack/package.json || true
echo

echo "=== search: template files under packages/init-stack ==="
rg -n -C3 'template|templates|writeStackAppFile' packages/init-stack || true
echo

echo "=== done ==="


</blockquote></details>

</blockquote></details>

</details>

<!-- This is an auto-generated comment by CodeRabbit for review status -->

Copy link
Contributor

@N2D4 N2D4 left a comment

Choose a reason for hiding this comment

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

Can you also update the docs? In particular the Getting Started guide, and all the imports of the old stack.ts file

@github-actions github-actions bot assigned BilalG1 and unassigned N2D4 Sep 11, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (2)
packages/init-stack/src/index.ts (2)

601-604: Sanitize injected values in generated code

Avoid raw string interpolation; use JSON.stringify for safe escaping.

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

615-616: Also sanitize projectId in generated JS app file

Use JSON.stringify to prevent quote breaks.

-type === "js" && projectIdFromArgs ? `\n${indentation}projectId: '${projectIdFromArgs}',` : ""}${
+type === "js" && projectIdFromArgs ? `\n${indentation}projectId: ${JSON.stringify(projectIdFromArgs)},` : ""}${
🧹 Nitpick comments (3)
docs/templates/getting-started/setup.mdx (1)

54-54: Punctuation nit

Add a period for consistency with the preceding bullets.

-      - `stack/client.ts`: This file contains the `stackClientApp` which you can use to access Stack from Client Components
+      - `stack/client.ts`: This file contains the `stackClientApp` which you can use to access Stack from Client Components.
packages/init-stack/src/index.ts (2)

519-526: Escape quotes when writing .env.local to avoid malformed values

If an ID/key contains ", the generated .env.local will break. Escape double quotes in both branches.

-          `NEXT_PUBLIC_STACK_PROJECT_ID="${projectIdFromArgs ?? ""}"\n` +
-          `NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY="${publishableClientKeyFromArgs ?? ""}"\n` +
+          `NEXT_PUBLIC_STACK_PROJECT_ID="${(projectIdFromArgs ?? "").replaceAll('"', '\\"')}"\n` +
+          `NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY="${(publishableClientKeyFromArgs ?? "").replaceAll('"', '\\"')}"\n` +
-          `NEXT_PUBLIC_STACK_PROJECT_ID="${projectIdFromArgs ?? ""}"\n` +
-          `NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY="${publishableClientKeyFromArgs ?? ""}"\n` +
+          `NEXT_PUBLIC_STACK_PROJECT_ID="${(projectIdFromArgs ?? "").replaceAll('"', '\\"')}"\n` +
+          `NEXT_PUBLIC_STACK_PUBLISHABLE_CLIENT_KEY="${(publishableClientKeyFromArgs ?? "").replaceAll('"', '\\"')}"\n` +

593-594: Error message mentions only .ts; generalize extension

Projects may use .js, .tsx, etc.

-          `A file at the path ${stackAppPath} already exists. Stack uses the stack/${clientOrServer}.ts file to initialize the Stack SDK. Please remove the existing file and try again.`
+          `A file at the path ${stackAppPath} already exists. Stack uses the stack/${clientOrServer}.* file to initialize the Stack SDK. Please remove the existing file and try again.`
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cf8f1bd and b204910.

📒 Files selected for processing (9)
  • apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/(overview)/setup-page.tsx (3 hunks)
  • docs/templates/concepts/oauth.mdx (1 hunks)
  • docs/templates/customization/custom-pages.mdx (2 hunks)
  • docs/templates/customization/page-examples/forgot-password.mdx (1 hunks)
  • docs/templates/customization/page-examples/password-reset.mdx (1 hunks)
  • docs/templates/getting-started/example-pages.mdx (6 hunks)
  • docs/templates/getting-started/setup.mdx (4 hunks)
  • docs/templates/getting-started/users.mdx (1 hunks)
  • packages/init-stack/src/index.ts (9 hunks)
✅ Files skipped from review due to trivial changes (6)
  • docs/templates/customization/page-examples/password-reset.mdx
  • docs/templates/concepts/oauth.mdx
  • docs/templates/customization/custom-pages.mdx
  • docs/templates/customization/page-examples/forgot-password.mdx
  • docs/templates/getting-started/example-pages.mdx
  • apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/(overview)/setup-page.tsx
🧰 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
🧬 Code graph analysis (1)
packages/init-stack/src/index.ts (1)
packages/stack-shared/src/utils/errors.tsx (1)
  • throwErr (10-19)
⏰ 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). (3)
  • GitHub Check: build (22.x)
  • GitHub Check: all-good
  • GitHub Check: Security Check
🔇 Additional comments (6)
docs/templates/getting-started/setup.mdx (1)

205-223: LGTM on React client app setup

The stack/client.ts creation and usage in App.tsx look correct and consistent with the new split.

Also applies to: 235-235

packages/init-stack/src/index.ts (5)

45-47: CLI options addition looks good

New --project-id and --publishable-client-key flags are clearly named and documented.


575-583: Good: split client/server file generation and pathing

stack/client and stack/server targets are clear and match the docs.


640-643: LGTM: fixed server import path in Next handler

"../../../stack/server" is correct relative to app/handler/[...stack]/page.*.


694-709: Typed return is good

Narrowing getServerOrClientOrBoth() to Array<"server" | "client"> improves type safety.


752-752: LGTM: updated layout import to server path

import { stackServerApp } from "../stack/server"; aligns with the new split and src/app layout.

## Server Component basics

Since `useUser()` is a stateful hook, you can't use it on server components. Instead, you can import `stackServerApp` from `stack.ts` and call `getUser()`:
Since `useUser()` is a stateful hook, you can't use it on server components. Instead, you can import `stackServerApp` from `stack/client.ts` and call `getUser()`:
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix import location: use stack/server.ts for server components

Importing stackServerApp from stack/client.ts is incorrect for Server Components.

Apply:

-Since `useUser()` is a stateful hook, you can't use it on server components. Instead, you can import `stackServerApp` from `stack/client.ts` and call `getUser()`:
+Since `useUser()` is a stateful hook, you can't use it on server components. Instead, import `stackServerApp` from `stack/server.ts` and call `getUser()`:

Also update the snippet’s import to:

import { stackServerApp } from "@/stack/server";
🤖 Prompt for AI Agents
In docs/templates/getting-started/users.mdx around line 33, the example
incorrectly imports stackServerApp from stack/client.ts for a Server Component;
change the import to use the server-side entry by updating the snippet to import
stackServerApp from "@/stack/server" so the example shows the correct
server-side import for calling getUser() in Server Components.

@BilalG1 BilalG1 merged commit 0c4958a into dev Sep 11, 2025
24 of 26 checks passed
@BilalG1 BilalG1 deleted the init-stack-more-args branch September 11, 2025 17:10
@coderabbitai coderabbitai bot mentioned this pull request Oct 10, 2025
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.

2 participants