Skip to content

init emails docs #848

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Aug 21, 2025
Merged

init emails docs #848

merged 10 commits into from
Aug 21, 2025

Conversation

madster456
Copy link
Collaborator

@madster456 madster456 commented Aug 18, 2025

Updates existing docs to include emails endpoints, and adds new docs for emails in general docs, as well as SDK docs.


Important

Introduces server-side email sending API and updates documentation to include comprehensive guides and SDK references for email functionality.

  • Behavior:
    • Introduces sendEmail API in route.tsx for sending emails with HTML or templates.
    • Handles errors like missing user IDs and schema errors.
  • Documentation:
    • Adds concepts/emails.mdx detailing email types, sending methods, and configuration.
    • Updates docs-platform.yml and meta.json to include email documentation.
    • Adds sdk/types/email.mdx for SendEmailOptions type reference.
  • UI/Style:
    • Adds badge style for sendEmailOptions in method-layout.tsx.

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


Summary by CodeRabbit

  • New Features

    • Introduced server-side email sending API with templates, theming, variables, and notification categories.
  • Documentation

    • Added comprehensive Emails concept guide and SDK references (sendEmail, SendEmailOptions).
    • Extended SDK index and platform navigation to include Email docs for Next/React/JS.
    • Added an “Emails” functional tag to API docs and route metadata.
  • Style

    • Added a distinct badge style for SendEmailOptions in the docs UI.

Copy link

vercel bot commented Aug 18, 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 Aug 21, 2025 5:05pm
stack-dashboard Ready Ready Preview Comment Aug 21, 2025 5:05pm
stack-demo Ready Ready Preview Comment Aug 21, 2025 5:05pm
stack-docs Ready Ready Preview 3 resolved Aug 21, 2025 5:05pm

Copy link
Contributor

coderabbitai bot commented Aug 18, 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

Adds an "Emails" capability: backend route metadata gets tags: ["Emails"] and imports reorganized; documentation pages, SDK types, and templates for SendEmailOptions and StackServerApp.sendEmail are added; docs generator and UI styling are updated to recognize "Emails"/sendemailoptions.

Changes

Cohort / File(s) Summary
Backend API metadata
apps/backend/src/app/api/latest/emails/send-email/route.tsx
Reorganized error-related imports and added tags: ["Emails"] to the POST route metadata; no handler, validation, or control-flow changes.
Docs platform config
docs/docs-platform.yml
Added concepts/emails.mdx and sdk/types/email.mdx entries scoped to platforms ["next","react","js"].
Docs generator tags
docs/scripts/generate-functional-api-docs.mjs
Inserted "Emails" into FUNCTIONAL_TAGS so the generator includes the Emails functional group when present in OpenAPI.
Docs UI styling
docs/src/components/ui/method-layout.tsx
Added sendemailoptions case to getTypeStyle, mapping it to a rose-themed badge style.
Concepts docs & meta
docs/templates/concepts/emails.mdx, docs/templates/meta.json
Added new Emails concept page and registered it in the Concepts meta ordering.
SDK reference: types & API
docs/templates/sdk/objects/stack-app.mdx, docs/templates/sdk/types/email.mdx, docs/templates/sdk/meta.json, docs/templates/sdk/index.mdx
Documented StackServerApp.sendEmail(options): Promise<Result<void, KnownErrors>>, added SendEmailOptions type page, and updated SDK meta/index to include Email section and type reference.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Dev as Developer (Server)
  participant App as StackServerApp
  participant Tmpl as Template Engine
  participant SMTP as Email Server

  Dev->>App: sendEmail(options)
  alt templateId provided
    App->>Tmpl: Render(templateId, variables, themeId)
    Tmpl-->>App: HTML content
  else html provided
    App-->>App: Use provided HTML
  end
  App->>SMTP: Send(email payload)
  SMTP-->>App: Delivery result
  App-->>Dev: Result<void, KnownErrors>
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I nibble docs and stitch the thread,
New tags and templates pink and red.
I hop through code, a gentle shove—
SendEmail sings and servers love. ✉️🐇

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch docs_email-docs

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 @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai 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:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai 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 @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @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.

This comment was marked as outdated.

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 adds comprehensive documentation for Stack Auth's email functionality across the platform. The changes introduce email-related documentation in three main areas:

Backend API Documentation: Adds a new /emails/send-email endpoint that allows sending emails to multiple users with either custom HTML content or template-based rendering. The endpoint includes validation for mutually exclusive parameters, notification category handling, unsubscribe link generation, and per-user error tracking.

General Documentation: Creates a new concepts/emails.mdx page that explains Stack Auth's email system, including email sending via the sendEmail method, templates, themes, notification categories, and configuration options. The documentation covers both shared and custom SMTP configurations.

SDK Documentation: Adds comprehensive SDK reference documentation including a new types/email.mdx file that documents the SendEmailOptions interface, and updates to stack-app.mdx to document the sendEmail method on StackServerApp instances.

Infrastructure Updates: Updates documentation generation scripts and navigation files to properly categorize and expose email-related documentation, including adding 'Emails' to the functional API tags and updating meta.json files for proper navigation structure.

The email system integrates with Stack Auth's existing user management, supporting notification preferences, template rendering with variables, and both HTML and template-based email sending approaches. The documentation follows established patterns in the Stack Auth docs using MDX with custom components for interactive API documentation.

Confidence score: 2/5

  • This PR has significant documentation inconsistencies and potential security issues that require careful review before merging
  • Score lowered due to API naming mismatches between documentation and implementation, plus a prototype pollution vulnerability in the backend route
  • Pay close attention to docs/templates/concepts/emails.mdx, docs/templates/sdk/types/email.mdx, and apps/backend/src/app/api/latest/emails/send-email/route.tsx

Context used:

Rule - Use Map<A, B> instead of plain objects when using dynamic keys to avoid prototype pollution vulnerabilities. (link)

10 files reviewed, 2 comments

Edit Code Review Bot Settings | Greptile

Copy link

recurseml bot commented Aug 18, 2025

Review by RecurseML

🔍 Review performed on 2c237ef..dc15780

✨ No bugs found, your code is sparkling clean

✅ Files analyzed, no issues (2)

apps/backend/src/app/api/latest/emails/send-email/route.tsx
docs/src/components/ui/method-layout.tsx

⏭️ Files skipped (low suspicion) (8)

docs/docs-platform.yml
docs/scripts/generate-functional-api-docs.mjs
docs/templates/concepts/emails.mdx
docs/templates/meta.json
docs/templates/sdk/index.mdx
docs/templates/sdk/meta.json
docs/templates/sdk/objects/stack-app.mdx
docs/templates/sdk/types/email.mdx

Need help? Join our Discord

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

🧹 Nitpick comments (8)
docs/templates/concepts/emails.mdx (4)

170-170: Fix stray double semicolon in import

There’s an extra semicolon in the import statement.

Apply this diff:

-import { stackServerApp } from '@stackframe/stack';;
+import { stackServerApp } from '@stackframe/stack';

105-105: Grammar: add article “a”

Minor grammar improvement in the “Password Reset” bullet.

Apply this diff:

-- **Password Reset**: `password_reset` - Sent when users request password reset
+- **Password Reset**: `password_reset` - Sent when users request a password reset

68-68: Prefer unknown over any for template variables

Using unknown is safer and aligns with TS best practices in docs.

Apply this diff:

-  variables?: Record<string, any>;      // Template variables
+  variables?: Record<string, unknown>;  // Template variables

172-176: Undefined variable in example (userId)

The snippet uses userId without defining it. Add a line to resolve/derive it for clarity.

Apply this diff:

 export async function inviteUser(email: string) {
-  const result = await stackServerApp.sendEmail({
+  // Resolve the user ID before sending (e.g., create or look up by email)
+  const userId = await getUserIdByEmail(email); // implement accordingly
+
+  const result = await stackServerApp.sendEmail({
     userIds: [userId], // Get user ID first
docs/docs-platform.yml (2)

113-116: Remove trailing spaces (YAML lint error)

YAMLlint flags trailing spaces at Line 113. Trim to keep CI green.

   - path: concepts/backend-integration.mdx
     platforms: ["next", "react", "js", "python"]
-  
+
   - path: concepts/emails.mdx
     platforms: ["next", "react", "js"]  # No Python (server-side email functionality)

233-236: Remove trailing spaces (YAML lint error)

YAMLlint flags trailing spaces at Line 233. Trim the blank line.

   - path: sdk/types/user.mdx
     platforms: ["next", "react", "js"]  # No Python
-  
+
   - path: sdk/types/email.mdx
     platforms: ["next", "react", "js"]  # No Python
docs/templates/sdk/types/email.mdx (1)

6-10: Minor wording/spacing nit

There appears to be a double space before “On this page:” per linter context. Use a single space after the preceding sentence to avoid visual glitches in some renderers.

docs/templates/sdk/objects/stack-app.mdx (1)

832-867: Examples/readme quality: consider showing success handling

Optional: add a quick success branch to the examples to mirror other sections (e.g., log success) for parity and clarity.

📜 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 2c237ef and dc15780.

📒 Files selected for processing (10)
  • apps/backend/src/app/api/latest/emails/send-email/route.tsx (2 hunks)
  • docs/docs-platform.yml (2 hunks)
  • docs/scripts/generate-functional-api-docs.mjs (1 hunks)
  • docs/src/components/ui/method-layout.tsx (1 hunks)
  • docs/templates/concepts/emails.mdx (1 hunks)
  • docs/templates/meta.json (1 hunks)
  • docs/templates/sdk/index.mdx (1 hunks)
  • docs/templates/sdk/meta.json (1 hunks)
  • docs/templates/sdk/objects/stack-app.mdx (2 hunks)
  • docs/templates/sdk/types/email.mdx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
apps/backend/src/app/api/latest/**/*

📄 CodeRabbit Inference Engine (CLAUDE.md)

apps/backend/src/app/api/latest/**/*: Main API routes are located in /apps/backend/src/app/api/latest
The project uses a custom route handler system in the backend for consistent API responses

Files:

  • apps/backend/src/app/api/latest/emails/send-email/route.tsx
🪛 LanguageTool
docs/templates/concepts/emails.mdx

[grammar] ~12-~12: There might be a mistake here.
Context: ... to users via the sendEmail method on StackServerApp - Email Templates: Use predefined email ...

(QB_NEW_EN)


[grammar] ~105-~105: There might be a mistake here.
Context: ...t**: password_reset - Sent when users request password reset - Magic Link: `magic...

(QB_NEW_EN)


[grammar] ~130-~130: There might be a mistake here.
Context: ...type - Configure the following settings: - Host: Your SMTP server hostname (e.g.,...

(QB_NEW_EN)


[grammar] ~131-~131: There might be a mistake here.
Context: ...hostname (e.g., smtp.yourprovider.com) - Port: SMTP port (typically 587 for TLS...

(QB_NEW_EN)


[grammar] ~132-~132: There might be a mistake here.
Context: ...t (typically 587 for TLS or 465 for SSL) - Username: Your SMTP username - **Pas...

(QB_NEW_EN)


[grammar] ~133-~133: There might be a mistake here.
Context: ...SL) - Username: Your SMTP username - Password: Your SMTP password - **Sen...

(QB_NEW_EN)


[grammar] ~134-~134: There might be a mistake here.
Context: ...ame - Password: Your SMTP password - Sender Email: The email address emails...

(QB_NEW_EN)


[grammar] ~135-~135: There might be a mistake here.
Context: ...e email address emails will be sent from - Sender Name: The display name for your...

(QB_NEW_EN)

docs/templates/sdk/types/email.mdx

[grammar] ~8-~8: There might be a mistake here.
Context: .../../concepts/emails.mdx). On this page: - SendEmailOptions -...

(QB_NEW_EN)

docs/templates/sdk/objects/stack-app.mdx

[grammar] ~845-~845: There might be a mistake here.
Context: ...', }); if (result.status === 'error') { console.error('Failed to send email:', r...

(QB_NEW_EN)

🪛 YAMLlint (1.37.1)
docs/docs-platform.yml

[error] 113-113: trailing spaces

(trailing-spaces)


[error] 233-233: trailing spaces

(trailing-spaces)

⏰ 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). (10)
  • GitHub Check: build (22.x)
  • GitHub Check: lint_and_build (latest)
  • GitHub Check: restart-dev-and-test
  • GitHub Check: setup-tests
  • GitHub Check: docker
  • GitHub Check: claude-review
  • GitHub Check: all-good
  • GitHub Check: docker
  • GitHub Check: build (22.x)
  • GitHub Check: Security Check
🔇 Additional comments (6)
docs/templates/meta.json (1)

17-18: Emails concept added to navigation: LGTM

The new "concepts/emails" entry is correctly placed and aligns with the new concepts page. No JSON issues spotted.

docs/src/components/ui/method-layout.tsx (1)

379-381: New badge style for SendEmailOptions: LGTM

The lowercase switch case matches the internal toLowerCase normalization, so "SendEmailOptions" will resolve correctly. Styling is consistent with existing patterns.

docs/scripts/generate-functional-api-docs.mjs (1)

16-16: Functional tag “Emails” added: LGTM

This enables generation of an Emails section when the OpenAPI tag exists. Slug/folder mapping will default to "emails" via existing helpers; no special-case needed.

apps/backend/src/app/api/latest/emails/send-email/route.tsx (1)

6-10: Import consolidation and OpenAPI tag: LGTM

  • Consolidated imports for StatusError/throwErr are fine and non-breaking.
  • Adding metadata.tags = ["Emails"] correctly exposes the route under the new functional category for docs generation.

Also applies to: 18-22

docs/templates/sdk/meta.json (1)

17-18: Add types/email entry — looks good

New SDK type page wired into meta; aligns with other changes introducing SendEmailOptions.

docs/templates/sdk/objects/stack-app.mdx (1)

528-538: New method in TOC — good addition

Adding sendEmail to the StackServerApp TOC aligns with the new API surface.

Copy link

claude bot commented Aug 18, 2025

Claude finished @madster456's task —— View job


PR Review - Email Documentation

I've completed a comprehensive review of this email documentation PR. Here's my analysis:

  • Read and analyze all changed files
  • Review email API endpoint implementation
  • Check documentation quality and consistency
  • Look for security concerns and best practices
  • Assess potential bugs or issues
  • Provide comprehensive feedback

Overall Assessment

This is a well-structured PR that adds comprehensive email documentation to Stack Auth. The implementation follows good practices and the documentation is thorough and user-friendly.

📋 Detailed Review

API Implementation (apps/backend/src/app/api/latest/emails/send-email/route.tsx)

✅ Strengths:

  • Comprehensive input validation using Yup schemas
  • Proper error handling with specific error types (RequiresCustomEmailServer, SchemaError, etc.)
  • Security checks (custom email server requirement, notification preferences)
  • Good separation of concerns with helper functions
  • Proper async/await usage and error boundaries

🔍 Observations:

  • Line 175: Generic catch block in email sending - could benefit from more specific error handling
  • Lines 58-63: Good mutual exclusion validation between html and template_id/variables
  • Lines 107-127: Smart double-rendering approach for template-based notification categories
  • Lines 135-150: Proper unsubscribe link generation with verification codes

Documentation Quality

📚 Concepts Documentation (docs/templates/concepts/emails.mdx):

  • Comprehensive coverage of email system features
  • Clear examples for both HTML and template-based emails
  • Good organization with practical use cases
  • Proper error handling examples
  • Includes production setup guidance

📖 SDK Documentation (docs/templates/sdk/types/email.mdx):

  • Detailed type documentation with interactive components
  • Good use of collapsible sections for each property
  • Clear examples for each option
  • Consistent formatting and structure

🔧 StackApp Methods (docs/templates/sdk/objects/stack-app.mdx):

  • Well-documented sendEmail method with clear examples
  • Proper error handling documentation
  • Good use of tabs for different scenarios

Configuration Updates

✅ Build System:

  • docs/scripts/generate-functional-api-docs.mjs: Proper addition of "Emails" to functional tags
  • docs/docs-platform.yml: Correct platform targeting (excludes Python appropriately)
  • Navigation structure updates are consistent

✅ UI Components:

  • docs/src/components/ui/method-layout.tsx: Good addition of rose color scheme for SendEmailOptions type
  • Maintains consistency with existing color patterns

🔒 Security Review

✅ Security Measures Identified:

  • Requires custom email server for production use (line 55-57)
  • Validates user existence before sending (lines 84-87)
  • Respects user notification preferences (lines 129-133)
  • Proper unsubscribe link generation with verification codes
  • Input sanitization through Yup schema validation

✅ No Security Concerns Found:

  • No hardcoded secrets or credentials
  • Proper access control with server-side authentication
  • No client-side exposure of sensitive operations

Performance Considerations

✅ Good Practices:

  • Batch processing of multiple users
  • Efficient database queries with proper includes
  • Template rendering optimization with Map-based lookups
  • Proper error handling that doesn't block other users

💡 Minor Optimization Opportunity:

  • Lines 92-178: Sequential user processing could potentially be parallelized for better performance with large user lists

🧪 Test Coverage

ℹ️ Observation:

  • This PR adds primarily documentation and a small API endpoint enhancement
  • No new test files were added, which is appropriate for documentation-focused changes
  • The API endpoint appears to build on existing, likely tested functionality

📝 Documentation Standards

✅ Excellent Documentation Quality:

  • Clear, actionable examples
  • Proper error handling guidance
  • Consistent formatting and structure
  • Good use of interactive components
  • Appropriate cross-references between sections

🎯 Recommendations

  1. Consider adding more specific error logging in the email sending catch block (line 175) for better debugging
  2. The documentation is comprehensive and well-structured - no changes needed
  3. Security implementation is solid - no concerns identified

🌟 Conclusion

This is a high-quality PR that successfully adds email functionality documentation to Stack Auth. The implementation is secure, well-documented, and follows established patterns. The documentation is user-friendly and comprehensive, providing clear guidance for both basic and advanced use cases.

Approval Recommended


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

♻️ Duplicate comments (1)
docs/templates/concepts/emails.mdx (1)

172-176: Undefined variable in example: userId.

The example references userId without defining it, which will mislead readers.

Apply one of these minimal fixes:

  • Keep the function signature and use a placeholder, plus a clarifying comment:
 export async function inviteUser(email: string) {
   const result = await stackServerApp.sendEmail({
-    userIds: [userId], // Get user ID first
+    userIds: [/* userId */], // Look up the user's ID from the email before calling sendEmail
     templateId: 'invitation-template',
     subject: 'You\'re invited!',
     variables: {
       inviteUrl: 'https://yourapp.com/invite/token123',
     },
   });
  • Or change the function to accept a userId directly:
-export async function inviteUser(email: string) {
+export async function inviteUser(userId: string) {
   const result = await stackServerApp.sendEmail({
-    userIds: [userId], // Get user ID first
+    userIds: [userId],
     templateId: 'invitation-template',
     subject: 'You\'re invited!',
     variables: {
       inviteUrl: 'https://yourapp.com/invite/token123',
     },
   });

If helpful, I can add a fuller snippet that resolves userId from an email using listUsers({ query: email }) with basic guards.

🧹 Nitpick comments (6)
docs/templates/sdk/types/email.mdx (4)

15-17: Call out constraints at the type-level (mutual exclusivity and requirement).

Make the html vs templateId rules explicit up-front to prevent misuse.

 Options for sending emails via the `sendEmail` method on `StackServerApp`.
 
+<Info type="warning">
+Exactly one of <code>html</code> or <code>templateId</code> must be provided. Do not provide both.
+When <code>templateId</code> is provided, you can pass <code>variables</code>. If <code>html</code> is provided, <code>variables</code> are ignored.
+</Info>

19-27: Prefer unknown over any for variables type.

Avoids losing type-safety while still allowing flexible payloads.

 <ClickableTableOfContents code={`type SendEmailOptions = {
   userIds: string[];  //$stack-link-to:#sendemailoptionsuserids
   themeId?: string | null | false;  //$stack-link-to:#sendemailoptionsthemeid
   subject?: string;  //$stack-link-to:#sendemailoptionssubject
   notificationCategoryName?: string;  //$stack-link-to:#sendemailoptionsnotificationcategoryname
   html?: string;  //$stack-link-to:#sendemailoptionshtml
   templateId?: string;  //$stack-link-to:#sendemailoptionstemplateid
-  variables?: Record<string, any>;  //$stack-link-to:#sendemailoptionsvariables
+  variables?: Record<string, unknown>;  //$stack-link-to:#sendemailoptionsvariables
 };`} />

55-71: Clarify themeId semantics (false vs null).

“null for no theme, false for default theme” is easy to misread. Please confirm the intended behavior and consider rephrasing with a short table or explicit examples (what happens when omitted/undefined).


183-185: Align snippet with safer typing (unknown).

Mirror the top-level type recommendation in the property snippet.

-        variables?: Record<string, any>
+        variables?: Record<string, unknown>
docs/templates/sdk/objects/stack-app.mdx (1)

803-873: Add constraints note, narrow KnownErrors, and make example logging consistent.

  • Add a short constraints note to prevent passing both html and templateId.
  • Narrow the KnownErrors in the signature to the three listed errors for clarity.
  • Log error.message (or error.code) like other examples for consistency.
 <CollapsibleMethodSection method="sendEmail" signature="[options]" appType="StackServerApp" defaultOpen={false}>
 
 <MethodLayout>
   <MethodContent>
 
     Send custom emails to users. You can send either custom HTML emails or use predefined templates with variables.
 
     **Parameters:**
     - `options` ([SendEmailOptions](../types/email#sendemailoptions)) - Email configuration and content
+
+    <Info type="warning">
+    Exactly one of <code>html</code> or <code>templateId</code> must be provided. Do not provide both.
+    When <code>templateId</code> is provided, you can pass <code>variables</code>. If <code>html</code> is provided, <code>variables</code> are ignored.
+    </Info>
 
     **Returns:** `Promise<Result<void, KnownErrors>>`
 
     The method returns a `Result` object that can contain specific error types:
@@
 <AsideSection title="Signature">
 
 ```typescript
-declare function sendEmail(options: SendEmailOptions): Promise<Result<void, KnownErrors>>;
+declare function sendEmail(
+  options: SendEmailOptions
+): Promise<Result<
+  void,
+  | KnownErrors["RequiresCustomEmailServer"]
+  | KnownErrors["SchemaError"]
+  | KnownErrors["UserIdDoesNotExist"]
+>>;
@@ if (result.status === 'error') { - console.error('Failed to send email:', result.error); + console.error('Failed to send email:', result.error.message); } @@ if (result.status === 'error') { - console.error('Failed to send email:', result.error); + console.error('Failed to send email:', result.error.message); } ```
docs/templates/concepts/emails.mdx (1)

24-24: Standardize import path for consistency.

Elsewhere you import from '@stackframe/stack'. Using a relative './stack' here may confuse readers.

-import { stackServerApp } from './stack';
+import { stackServerApp } from '@stackframe/stack';
📜 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 dc15780 and f939a59.

📒 Files selected for processing (4)
  • docs/templates/concepts/emails.mdx (1 hunks)
  • docs/templates/sdk/index.mdx (1 hunks)
  • docs/templates/sdk/objects/stack-app.mdx (2 hunks)
  • docs/templates/sdk/types/email.mdx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/templates/sdk/index.mdx
🧰 Additional context used
🪛 LanguageTool
docs/templates/concepts/emails.mdx

[grammar] ~12-~12: There might be a mistake here.
Context: ... to users via the sendEmail method on StackServerApp - Email Templates: Use predefined email ...

(QB_NEW_EN)


[grammar] ~105-~105: There might be a mistake here.
Context: ...t**: password_reset - Sent when users request password reset - Magic Link: `magic...

(QB_NEW_EN)


[grammar] ~130-~130: There might be a mistake here.
Context: ...type - Configure the following settings: - Host: Your SMTP server hostname (e.g.,...

(QB_NEW_EN)


[grammar] ~131-~131: There might be a mistake here.
Context: ...hostname (e.g., smtp.yourprovider.com) - Port: SMTP port (typically 587 for TLS...

(QB_NEW_EN)


[grammar] ~132-~132: There might be a mistake here.
Context: ...t (typically 587 for TLS or 465 for SSL) - Username: Your SMTP username - **Pas...

(QB_NEW_EN)


[grammar] ~133-~133: There might be a mistake here.
Context: ...SL) - Username: Your SMTP username - Password: Your SMTP password - **Sen...

(QB_NEW_EN)


[grammar] ~134-~134: There might be a mistake here.
Context: ...ame - Password: Your SMTP password - Sender Email: The email address emails...

(QB_NEW_EN)


[grammar] ~135-~135: There might be a mistake here.
Context: ...e email address emails will be sent from - Sender Name: The display name for your...

(QB_NEW_EN)

docs/templates/sdk/objects/stack-app.mdx

[grammar] ~845-~845: There might be a mistake here.
Context: ...', }); if (result.status === 'error') { console.error('Failed to send email:', r...

(QB_NEW_EN)

docs/templates/sdk/types/email.mdx

[grammar] ~8-~8: There might be a mistake here.
Context: .../../concepts/emails.mdx). On this page: - SendEmailOptions --...

(QB_NEW_EN)

⏰ 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). (10)
  • GitHub Check: build (22.x)
  • GitHub Check: build (22.x)
  • GitHub Check: all-good
  • GitHub Check: docker
  • GitHub Check: setup-tests
  • GitHub Check: docker
  • GitHub Check: restart-dev-and-test
  • GitHub Check: claude-review
  • GitHub Check: lint_and_build (latest)
  • GitHub Check: Security Check
🔇 Additional comments (3)
docs/templates/sdk/types/email.mdx (1)

8-10: Anchor sweep passed – no remaining typos found

I ran a grep across docs/templates/sdk and confirmed that every reference to SendEmailOptions consistently uses the #sendemailoptions slug (no instances of sendemaildoptions or other misspellings).

Verified locations:

  • docs/templates/sdk/types/email.mdx
  • docs/templates/sdk/index.mdx
  • docs/templates/sdk/objects/stack-app.mdx
  • docs/src/components/ui/method-layout.tsx

No further changes needed.

docs/templates/sdk/objects/stack-app.mdx (2)

528-537: TOC entry for sendEmail looks good.

Anchor and method signature mapping are consistent with the section below.


810-812: Link to SendEmailOptions fixed.

The parameter now links to ../types/email#sendemailoptions (correct slug). Thanks for addressing the earlier broken anchor.

Copy link

claude bot commented Aug 19, 2025

Claude finished @madster456's task —— View job


PR Review - Email Documentation

I've completed a comprehensive review of this email documentation PR. Here's my analysis:

  • Read and analyze all changed files
  • Review email API endpoint implementation
  • Check documentation quality and consistency
  • Look for security concerns and best practices
  • Assess potential bugs or issues
  • Provide comprehensive feedback

Overall Assessment

This is a well-structured PR that adds comprehensive email documentation to Stack Auth. The implementation follows good practices and the documentation is thorough and user-friendly.

📋 Detailed Review

API Implementation (apps/backend/src/app/api/latest/emails/send-email/route.tsx)

✅ Strengths:

  • Comprehensive input validation using Yup schemas
  • Proper error handling with specific error types (RequiresCustomEmailServer, SchemaError, etc.)
  • Security checks (custom email server requirement, notification preferences)
  • Good separation of concerns with helper functions
  • Proper async/await usage and error boundaries

🔍 Observations:

  • Line 175: Generic catch block in email sending - could benefit from more specific error handling
  • Lines 58-63: Good mutual exclusion validation between html and template_id/variables
  • Lines 107-127: Smart double-rendering approach for template-based notification categories
  • Lines 135-150: Proper unsubscribe link generation with verification codes

Documentation Quality

📚 Concepts Documentation (docs/templates/concepts/emails.mdx):

  • Comprehensive coverage of email system features
  • Clear examples for both HTML and template-based emails
  • Good organization with practical use cases
  • Proper error handling examples
  • Includes production setup guidance

📖 SDK Documentation (docs/templates/sdk/types/email.mdx):

  • Detailed type documentation with interactive components
  • Good use of collapsible sections for each property
  • Clear examples for each option
  • Consistent formatting and structure

🔧 StackApp Methods (docs/templates/sdk/objects/stack-app.mdx):

  • Well-documented sendEmail method with clear examples
  • Proper error handling documentation
  • Good use of tabs for different scenarios

Configuration Updates

✅ Build System:

  • docs/scripts/generate-functional-api-docs.mjs: Proper addition of "Emails" to functional tags
  • docs/docs-platform.yml: Correct platform targeting (excludes Python appropriately)
  • Navigation structure updates are consistent

✅ UI Components:

  • docs/src/components/ui/method-layout.tsx: Good addition of rose color scheme for SendEmailOptions type
  • Maintains consistency with existing color patterns

🔒 Security Review

✅ Security Measures Identified:

  • Requires custom email server for production use (line 55-57)
  • Validates user existence before sending (lines 84-87)
  • Respects user notification preferences (lines 129-133)
  • Proper unsubscribe link generation with verification codes
  • Input sanitization through Yup schema validation

✅ No Security Concerns Found:

  • No hardcoded secrets or credentials
  • Proper access control with server-side authentication
  • No client-side exposure of sensitive operations

Performance Considerations

✅ Good Practices:

  • Batch processing of multiple users
  • Efficient database queries with proper includes
  • Template rendering optimization with Map-based lookups
  • Proper error handling that doesn't block other users

💡 Minor Optimization Opportunity:

  • Lines 92-178: Sequential user processing could potentially be parallelized for better performance with large user lists

🧪 Test Coverage

ℹ️ Observation:

  • This PR adds primarily documentation and a small API endpoint enhancement
  • No new test files were added, which is appropriate for documentation-focused changes
  • The API endpoint appears to build on existing, likely tested functionality

📝 Documentation Standards

✅ Excellent Documentation Quality:

  • Clear, actionable examples
  • Proper error handling guidance
  • Consistent formatting and structure
  • Good use of interactive components
  • Appropriate cross-references between sections

🎯 Recommendations

  1. Consider adding more specific error logging in the email sending catch block (line 175) for better debugging
  2. The documentation is comprehensive and well-structured - no changes needed
  3. Security implementation is solid - no concerns identified

🌟 Conclusion

This is a high-quality PR that successfully adds email functionality documentation to Stack Auth. The implementation is secure, well-documented, and follows established patterns. The documentation is user-friendly and comprehensive, providing clear guidance for both basic and advanced use cases.

Approval Recommended


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.

Left some comments on Vercel, rest looks good!

@N2D4 N2D4 removed their assignment Aug 20, 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

♻️ Duplicate comments (1)
docs/templates/concepts/emails.mdx (1)

183-191: Example bug: userId is undefined in sendEmail payload.

Pass a userId (or show a lookup) before calling sendEmail. Easiest fix: accept userId in the function signature. This was flagged previously as well.

-export async function inviteUser(email: string) {
+export async function inviteUser(userId: string) {
   const result = await stackServerApp.sendEmail({
-    userIds: [userId], // Get user ID first
+    userIds: [userId],
     templateId: 'invitation-template',
     subject: 'You\'re invited!',
     variables: {
       inviteUrl: 'https://yourapp.com/invite/token123',
     },
   });

If you intend to accept an email, add a brief preceding step/comment to resolve userId from that email via your Users API, then pass it here.

🧹 Nitpick comments (7)
docs/templates/concepts/emails.mdx (7)

6-6: Grammar fix: clarify subject and agreement.

"provides emails that allows" → "provides an email system that allows".

-Stack Auth provides emails that allows you to send custom emails to your users. The system supports both custom HTML emails and template-based emails with theming.
+Stack Auth provides an email system that allows you to send custom emails to your users. The system supports both custom HTML emails and template-based emails with theming.

35-35: Make imports consistent and canonical.

Two examples use different import sources. Prefer the package import for consistency unless this page intentionally demonstrates a local helper. If not intentional, align them.

-import { stackServerApp } from './stack';
+import { stackServerApp } from '@stackframe/stack';

If you do intend to show a local helper, add a short note explaining that './stack' re-exports a configured instance.

Also applies to: 181-181


54-65: Template example: avoid implying subject is required when using template.

If templates provide their own subject (common), including subject here may confuse readers about precedence. Either remove it or add a note that it overrides the template subject.

 const result = await stackServerApp.sendEmail({
   userIds: ['user-id'],
   templateId: 'welcome-template',
-  subject: 'Welcome to our platform!',
   variables: {
     userName: 'John Doe',
     activationUrl: 'https://yourapp.com/activate/token123',
     supportEmail: 'support@yourapp.com',
   },
 });

69-69: Explain themeId semantics (false vs null).

You document themeId?: string | null | false but not what null/false mean. Add a one-liner to prevent ambiguity.

-The `sendEmail` method accepts the following options:
+The `sendEmail` method accepts the following options:
+Note: set `themeId` to `false` to disable theming, or to `null` to use the project's default theme.

71-81: Avoid duplicating SDK types in Concepts; link to the single source of truth.

Inlining SendEmailOptions risks drift versus the SDK docs (this PR also adds docs/templates/sdk/types/email.mdx). Replace this block with a link/reference to the SDK type.

-```typescript
-type SendEmailOptions = {
-  userIds: string[];                    // Array of user IDs to send to
-  themeId?: string | null | false;      // Theme to apply (optional)
-  subject?: string;                     // Email subject
-  notificationCategoryName?: string;    // Notification category for user preferences
-  html?: string;                        // Custom HTML content
-  templateId?: string;                  // Template ID to use
-  variables?: Record<string, any>;      // Template variables
-};
-```
+See the SDK type reference for the authoritative shape: [SendEmailOptions](/sdk/types/email).

173-176: Grammar: singular subject.

"Emails integrates" → "The email system integrates".

-Emails integrates seamlessly with Stack Auth's React components. Email verification, password reset, and other authentication emails are automatically sent when users interact with the provided components.
+The email system integrates seamlessly with Stack Auth's React components. Email verification, password reset, and other authentication emails are automatically sent when users interact with the provided components.

21-27: Minor style: terminate bullets with periods for consistency.

Optional polish to improve readability and satisfy grammar linters.

-- **Email Sending**: Send custom emails to users via the `sendEmail` method on `StackServerApp`
-- **Email Templates**: Use predefined email templates for common authentication flows
-- **Email Themes**: Apply consistent styling to your emails
-- **Notification Categories**: Allow users to control which emails they receive
+- **Email Sending**: Send custom emails to users via the `sendEmail` method on `StackServerApp`.
+- **Email Templates**: Use predefined email templates for common authentication flows.
+- **Email Themes**: Apply consistent styling to your emails.
+- **Notification Categories**: Allow users to control which emails they receive.
📜 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 f939a59 and 2edeb57.

📒 Files selected for processing (1)
  • docs/templates/concepts/emails.mdx (1 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/templates/concepts/emails.mdx

[grammar] ~23-~23: There might be a mistake here.
Context: ... to users via the sendEmail method on StackServerApp - Email Templates: Use predefined email ...

(QB_NEW_EN)


[grammar] ~24-~24: There might be a mistake here.
Context: ...emplates for common authentication flows - Email Themes: Apply consistent styling...

(QB_NEW_EN)


[grammar] ~25-~25: There might be a mistake here.
Context: ... Apply consistent styling to your emails - Notification Categories: Allow users t...

(QB_NEW_EN)


[grammar] ~115-~115: There might be a mistake here.
Context: ...nt when users need to verify their email - Password Reset: password_reset - Sen...

(QB_NEW_EN)


[grammar] ~116-~116: There might be a mistake here.
Context: ...- Sent when users request password reset - Magic Link: magic_link - Sent for pa...

(QB_NEW_EN)


[grammar] ~117-~117: There might be a mistake here.
Context: ...- Sent for passwordless authentication - **Team Invitation**:team_invitation` - S...

(QB_NEW_EN)


[grammar] ~118-~118: There might be a mistake here.
Context: ...- Sent when users are invited to teams - **Sign-in Invitation**:sign_in_invitatio...

(QB_NEW_EN)


[grammar] ~141-~141: There might be a mistake here.
Context: ...type - Configure the following settings: - Host: Your SMTP server hostname (e.g.,...

(QB_NEW_EN)


[grammar] ~142-~142: There might be a mistake here.
Context: ...hostname (e.g., smtp.yourprovider.com) - Port: SMTP port (typically 587 for TLS...

(QB_NEW_EN)


[grammar] ~143-~143: There might be a mistake here.
Context: ...t (typically 587 for TLS or 465 for SSL) - Username: Your SMTP username - **Pas...

(QB_NEW_EN)


[grammar] ~144-~144: There might be a mistake here.
Context: ...SL) - Username: Your SMTP username - Password: Your SMTP password - **Sen...

(QB_NEW_EN)


[grammar] ~145-~145: There might be a mistake here.
Context: ...ame - Password: Your SMTP password - Sender Email: The email address emails...

(QB_NEW_EN)


[grammar] ~146-~146: There might be a mistake here.
Context: ...e email address emails will be sent from - Sender Name: The display name for your...

(QB_NEW_EN)

⏰ 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). (6)
  • GitHub Check: build (22.x)
  • GitHub Check: setup-tests
  • GitHub Check: docker
  • GitHub Check: restart-dev-and-test
  • GitHub Check: build (22.x)
  • GitHub Check: Security Check
🔇 Additional comments (1)
docs/templates/concepts/emails.mdx (1)

83-107: Nice, concrete error-handling example.

Clear mapping of error codes with a concise switch improves developer experience.

@madster456 madster456 merged commit 4b06bca into dev Aug 21, 2025
18 of 19 checks passed
@madster456 madster456 deleted the docs_email-docs branch August 21, 2025 17:05
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