stack/docs-mintlify/guides/apps/emails/overview.mdx
BilalG1 c14a9dd3d0
feat(hexclave): PR 5 — internal symbol/path/package renames + brand strings (#1547)
## Stack Auth → Hexclave rename — PR 5 (internal symbols, paths,
packages, brand strings)

PR 5 finishes the **internal / non-wire** half of the Stack→Hexclave
rename. It only touches things where nothing outside the repo depends on
the exact name: internal symbols, file/dir names, the
`@stackframe/template` package, and residual brand strings. Plan +
progress are in `HEXCLAVE-RENAME-PR5-PLAN.md`.

Every step was verified green (`pnpm typecheck` + `pnpm lint`, 28/28)
and committed as its own checkpoint, then a fan-out of review agents
audited all commits and the findings were fixed.

### What changed
- **Internal symbols** (`@hexclave/shared`, `packages/template`, apps):
`stack*`/`Stack*` → `hexclave*`/`Hexclave*` — incl.
`stackGlobalsSymbol`, the `_Stack*AppImpl` classes,
`stackAppInternalsSymbol`, `StackContext`, `getStackStripe`, etc. The
`stack*App` local-variable convention
(`stackServerApp`/`stackClientApp`/…) was renamed across 175
source/example/doc files.
- **File renames**: `hexclave-handler/provider/context.tsx`,
`backend/hexclave.tsx`, `internal-tool/hexclave.ts`,
`hexclave-app-internals.ts`.
- **Directory renames**: `lib/hexclave-app`, `hexclave-companion`,
`[...hexclave]` route segment, `skills/hexclave`,
`dashboard/src/hexclave`, and the package dirs
**`packages/{next,shared,ui,sc,cli}`** (dropping the `stack-` prefix to
match the `@hexclave/*` npm names).
- **Packages**: `@stackframe/template` → `@hexclave/template`; **deleted
`packages/init-stack`** (onboarding lives in `@hexclave/cli init`; the
published npm package is untouched).
- **Brand strings**: reworded `Stack Auth`/`Stack dashboard` prose in
code + docs-mintlify, renamed `hexclave-app.mdx`/`use-hexclave-app.mdx`
with redirects, regenerated OpenAPI, updated coupled e2e assertions;
`doctor`/`init` now prefer `hexclave.config.ts`.

### Intentionally kept (verified, not oversights)
Wire/compat identifiers (`x-stack-*` headers, `stack-*` cookies,
`STACK_*` env names, `*.stack-auth.com`, `stackauth_`, `ask_stack_auth`,
query params), public `Stack*` SDK aliases, crypto/JWT/vault
domain-separation tags, `*-brand-sentinel`s, the
`Symbol.for("StackAuth--…")` string, `_stack_sync_metadata`, Postgres
`stackframe` / docker image names, the `stack-auth-logo*.svg` (used by
the rebrand modal), and `migration.mdx` / "formerly known as Stack Auth"
notes. False positives (Phosphor `StackIcon`/`StackSimple`, `TanStack`,
`OrbStack`, `stackable`/`Stacked` charts) left alone.

### Review pass
Six review agents audited all commits. Found + fixed one real bug — a
build script (`bundle-type-definitions.ts`) hardcoded the old
`lib/stack-app` glob path (not an import, so typecheck/lint were blind),
silently emptying the dashboard AI type bundle — plus stale comments, a
dead CI env var, and stale `.gitignore`/`.dockerignore` entries.
Cross-cutting audit confirmed **zero wire-compat identifiers were
accidentally renamed**.

### ⚠️ Verification note
`typecheck` + `lint` are fully green locally. The **e2e suite was not
run** (needs a live backend+DB), so the brand-string assertion +
OpenAPI-regen changes are verified by grep/codegen only — please let CI
exercise e2e to confirm.

### Base-branch note
This branch was forked from the local-only `cl/friendly-lewin-72293f`
(not on origin, no separate PR), so this PR against `dev` also carries
that branch's ~11 preceding Hexclave-rename commits (config-file rename,
env-var dual-read, AI setup-prompt rebrand). If those should land
separately, re-parent before merge.

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Finishes the internal Stack Auth → Hexclave rename and cleans up
remaining stragglers, including dev-tool and prompt copy. All changes
are internal-only; public/wire APIs remain unchanged. Re-merged `dev`
and resolved the payments create-purchase-url conflict.

- **Refactors**
- Internal symbols: stack*/Stack* → hexclave*/Hexclave* (e.g.,
`getHexclaveServerApp` via `@/hexclave`, `getHexclaveStripe`,
`hexclaveAppInternalsSymbol`, `hexclaveSchemaInfo`, Prisma
`__hexclave_*`, `data-hexclave-handler-page`, Stripe mock
`hexclavePortPrefix`).
- Files/dirs: moved to `lib/hexclave-app`; handler route
`[...hexclave]`; backend entry `src/hexclave.tsx`; dashboard internals
`hexclave-app-internals`; companion `hexclave-companion`; dropped
`stack-` prefix across package dirs
(`packages/{shared,ui,sc,cli,next}`); workflows/emulator paths now
`packages/cli`; Quetzal codegen env at `packages/next/.env.local`.
- Packages/docs: `@stackframe/template` → `@hexclave/template`; removed
`packages/init-stack`; regenerated OpenAPI and updated docs
slugs/redirects for hexclave-app/use-hexclave-app.
- Brand strings/prompts: reworded remaining “Stack” dashboard strings to
Hexclave; updated dev-tool copy and prompts; `doctor/init` now prefer
`hexclave.config.ts`. Kept all wire-compat identifiers and public
aliases (`x-stack-*`, `stack-*` cookies, `STACK_*` env,
`*.stack-auth.com`, `Stack*` SDK names).
- Rebased/merged onto latest `dev`: retained `@hexclave/template`, kept
`src` in published files, refreshed setup-prompt imports and docs JSON,
adopted 1.0.5 version bumps, and re-merged `dev` again (resolved
`create-purchase-url` with `getHexclaveStripe`).

- **Bug Fixes**
- Restored dashboard AI type bundle by pointing the glob to
`packages/template/src/lib/hexclave-app`.
- Addressed rename leftovers: updated lingering `@/stack` imports and
CSS selector, fixed schema/meta and port-prefix expansions, and aligned
emulator commands to `packages/cli`.
- CI/build: removed a dead env var and stale ignore entries; fixed
Docker by renaming `STACK_SKIP_TEMPLATE_GENERATION` →
`HEXCLAVE_SKIP_TEMPLATE_GENERATION`.

<sup>Written for commit 3c1af3bff3.
Summary will update on new commits.</sup>

<a
href="https://cubic.dev/pr/hexclave/hexclave/pull/1547?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->
2026-06-03 18:57:09 -07:00

351 lines
11 KiB
Plaintext

---
title: "Emails"
description: "Send custom emails, manage templates, and track delivery - all from Hexclave."
icon: "/images/app-icons/emails.svg"
---
Hexclave includes a full email system for sending transactional and marketing emails to your users. It handles rendering, delivery, scheduling, notification preferences, and tracking out of the box.
## Email types
There are two categories of email:
- **Transactional** - Required for your app to function (verification, password reset, receipts). Users cannot opt out.
- **Marketing** - Promotional or informational. Always includes an unsubscribe link. Users can opt out.
<Warning>
Never send marketing content as transactional emails. Doing so can get your domain blacklisted by spam filters.
</Warning>
## Sending emails
Emails are sent from your server using `hexclaveServerApp.sendEmail()`. You must provide the content (HTML, a template, or a draft) and the recipients.
### Send to specific users
```typescript
await hexclaveServerApp.sendEmail({
userIds: ['user-id-1', 'user-id-2'],
subject: 'Welcome to our platform!',
html: '<h1>Welcome!</h1><p>Thanks for joining us.</p>',
});
```
### Send to all users
```typescript
await hexclaveServerApp.sendEmail({
allUsers: true,
templateId: 'your-template-id',
subject: 'We just shipped a big update',
variables: {
featureName: 'Dark mode',
},
});
```
### Send from a dashboard draft
If you've composed an email in the dashboard's draft editor, you can trigger it programmatically:
```typescript
await hexclaveServerApp.sendEmail({
userIds: ['user-id'],
draftId: 'your-draft-id',
});
```
### Full options
```typescript
await hexclaveServerApp.sendEmail({
// Recipients - exactly one of these is required:
userIds: ['user-id-1'], // specific users
// allUsers: true, // or all users in your project
// Content - exactly one of these is required:
html: '<p>Hello!</p>', // raw HTML
// templateId: 'template-id', // or a template with variables
// draftId: 'draft-id', // or a dashboard draft
// Optional:
subject: 'Hello!',
variables: { key: 'value' },
themeId: 'theme-id', // apply a specific theme
// themeId: null, // use the default theme
// themeId: false, // send with no theme at all
notificationCategoryName: 'Marketing',
scheduledAt: new Date('2025-12-25T00:00:00Z'),
});
```
### `SendEmailOptions` type shape
```typescript
type SendEmailOptions = {
userIds: string[]; // users to send to
themeId?: string | null | false; // theme override
subject?: string; // subject line
notificationCategoryName?: string; // preference category
html?: string; // raw HTML body
templateId?: string; // template ID
variables?: Record<string, any>; // template variables
};
```
<Info>
`sendEmail` requires a custom email server (SMTP, Resend, or Managed). It cannot be used with the shared development server.
</Info>
### Error handling
`sendEmail` returns a result object. Handle failures explicitly:
```typescript
const result = await hexclaveServerApp.sendEmail({
userIds: ['user-id'],
html: '<p>Hello!</p>',
subject: 'Test Email',
});
if (result.status === 'error') {
switch (result.error.code) {
case 'REQUIRES_CUSTOM_EMAIL_SERVER':
console.error('Please configure a custom email server');
break;
case 'SCHEMA_ERROR':
console.error('Invalid email data provided');
break;
case 'USER_ID_DOES_NOT_EXIST':
console.error('One or more user IDs do not exist');
break;
}
}
```
## Scheduling
Pass a `scheduledAt` date to delay delivery. The email enters the pipeline immediately but won't be sent until the scheduled time.
```typescript
await hexclaveServerApp.sendEmail({
userIds: ['user-id'],
html: '<p>Happy New Year!</p>',
subject: 'Happy New Year!',
scheduledAt: new Date('2026-01-01T00:00:00Z'),
});
```
If `scheduledAt` is omitted, the email is sent as soon as possible.
## Email pipeline
Emails are processed asynchronously through a multi-stage pipeline:
1. **Enqueue** - The email is saved to the outbox with its template, recipients, and scheduling metadata.
2. **Render** - The template TSX is compiled into HTML, subject, and plain text.
3. **Queue** - Rendered emails whose scheduled time has passed are queued for delivery, respecting your project's sending capacity.
4. **Send** - Emails are delivered, honoring notification preferences and skipping users who have unsubscribed.
5. **Track** - Delivery events (sent, opened, clicked, bounced, marked as spam) are recorded.
You can monitor every email's status in the dashboard under **Emails → Sent**.
## Templates
Templates are React Email components written in TSX. Each template receives the current `user`, `project`, and any custom `variables` you pass when sending.
```tsx
import { type } from "arktype";
import { Container } from "@react-email/components";
import { Subject, NotificationCategory, Props } from "@hexclave/emails";
export const variablesSchema = type({
featureName: "string",
});
export function EmailTemplate({
user,
project,
variables,
}: Props<typeof variablesSchema.infer>) {
return (
<Container>
<Subject value={`New feature: ${variables.featureName}`} />
<NotificationCategory value="Transactional" />
<p>Hi {user.displayName}, check out {variables.featureName}!</p>
</Container>
);
}
EmailTemplate.PreviewVariables = {
featureName: "Dark mode",
} satisfies typeof variablesSchema.infer;
```
Key concepts:
- **`variablesSchema`** - Define the shape of your template variables using [arktype](https://arktype.io). Hexclave validates variables against this schema at render time.
- **`<Subject>`** - Sets the email subject line from inside the template.
- **`<NotificationCategory>`** - Declares whether this is a `"Transactional"` or `"Marketing"` email.
- **`PreviewVariables`** - Sample data used for the live preview in the dashboard editor.
### Built-in templates
Hexclave ships with templates for common auth flows. These are used automatically by the built-in authentication components:
| Template | Trigger |
|---|---|
| **Email Verification** | User signs up or changes their email |
| **Password Reset** | User requests a password reset |
| **Magic Link / OTP** | User signs in with magic link or one-time password |
| **Team Invitation** | User is invited to join a team |
| **Sign-in Invitation** | User is invited to create an account |
| **Payment Receipt** | A payment succeeds (one-time or subscription) |
| **Payment Failed** | A payment fails |
You can customize any built-in template from the dashboard under **Emails → Templates**.
## Themes
Themes wrap your email content in a consistent layout - header, footer, background, branding. Hexclave includes three built-in themes:
- **Default Light** - Clean white background with subtle shadow
- **Default Dark** - Dark background with light text
- **Default Colorful** - Light purple background with an accent border
You can create custom themes in the dashboard under **Emails → Email Settings → Themes**. Themes are also TSX components:
```tsx
import { Html, Head, Tailwind, Body, Container } from "@react-email/components";
import { ThemeProps, ProjectLogo } from "@hexclave/emails";
export function EmailTheme({ children, unsubscribeLink, projectLogos }: ThemeProps) {
return (
<Html>
<Head />
<Tailwind>
<Body className="bg-white font-sans m-0 p-0">
<Container className="max-w-[600px] mx-auto p-8">
<ProjectLogo data={projectLogos} mode="light" />
{children}
</Container>
{unsubscribeLink && (
<p className="text-center text-xs opacity-60">
<a href={unsubscribeLink}>Unsubscribe</a>
</p>
)}
</Body>
</Tailwind>
</Html>
);
}
```
Set a default theme for your project in the dashboard. You can also override the theme per-email with the `themeId` option, or pass `themeId: false` to send without any theme.
## Notification preferences
Emails are categorized as either **Transactional** or **Marketing**. Users can opt out of Marketing emails but not Transactional ones.
When sending, specify the category:
```typescript
await hexclaveServerApp.sendEmail({
userIds: ['user-id'],
html: '<p>Check out our new feature!</p>',
subject: 'Product Updates',
notificationCategoryName: 'Marketing',
});
```
If a user has unsubscribed from Marketing emails, the email will be automatically skipped during delivery. Marketing emails always include an unsubscribe link.
## React components integration
Emails integrate with Hexclave UI components automatically (for example verification, password reset, and magic-link flows).
For custom flows, trigger `sendEmail` from your server code:
```typescript
import { hexclaveServerApp } from '@hexclave/next';
export async function inviteUser(userId: string) {
const result = await hexclaveServerApp.sendEmail({
userIds: [userId],
templateId: 'invitation-template',
subject: "You're invited!",
variables: {
inviteUrl: 'https://yourapp.com/invite/token123',
},
});
return result;
}
```
## Email server configuration
Configure your email server in the dashboard under **Emails → Email Settings**. There are four options:
### Shared (development only)
The default for new projects. Emails are sent from `noreply@sent-with-hexclave.com` using Hexclave's shared infrastructure. Good for development - not suitable for production.
### Custom SMTP
Connect any SMTP provider. Configure:
- **Host** - e.g. `smtp.sendgrid.net`
- **Port** - typically 587 (STARTTLS) or 465 (implicit TLS)
- **Username** and **Password**
- **Sender email** and **Sender name**
### Resend
Connect your [Resend](https://resend.com) account by entering your API key. Hexclave configures the SMTP connection automatically.
### Managed
Let Hexclave manage your email domain. Hexclave handles DNS configuration and deliverability for you. Set up requires:
1. Choose a subdomain (e.g. `mail.yourapp.com`)
2. Add the DNS records Hexclave provides
3. Verify the domain in the dashboard
<Info>
The dashboard tests your email configuration automatically when you save it by sending a test email.
</Info>
## Delivery stats
Hexclave tracks delivery metrics across multiple time windows (hour, day, week, month):
- **Sent** - Successfully delivered
- **Bounced** - Rejected by the recipient's mail server
- **Marked as spam** - Recipient flagged the email
Access these programmatically:
```typescript
const info = await hexclaveServerApp.getEmailDeliveryStats();
// info.stats.day.sent, info.stats.day.bounced, etc.
// info.capacity.rate_per_second, info.capacity.is_boost_active, etc.
```
Delivery capacity is managed automatically based on your sending reputation. If you need to temporarily increase throughput, you can activate a capacity boost:
```typescript
await hexclaveServerApp.activateEmailCapacityBoost();
```
## Drafts
The dashboard includes a full draft editor where you can compose emails visually before sending. Drafts support:
- TSX source editing with live preview
- Theme selection
- Recipient picker (specific users or all users)
- Scheduling
- Send history per draft
Once a draft is sent, it's marked as sent and its delivery can be tracked in the outbox.