# Chat step Source: https://docs.novu.co/.mintlify/skills/dashboard-workflows/references/chat-step # Chat Step Chat step for Slack / Discord / Teams — team notifications, developer alerts. ## Guidelines * **Conversational tone** with standalone context (the recipient sees the message outside your product UI). * **Markdown is supported** on most platforms (bold, links, code, lists). ## Variables Use Liquid syntax in `body`: * `{{ subscriber.firstName }}` * `{{ payload.* }}` * `{{ steps.. }}` — only when the upstream HTTP step declares the property in its `responseBodySchema` ## See Also * [`step-conditions.md`](./step-conditions.md) — gate Chat on workflow tags or severity * [`design-workflow/references/channel-selection.md`](../../design-workflow/references/channel-selection.md) — Chat is a fit when configured **and** `severity >= MEDIUM` # Delay step Source: https://docs.novu.co/.mintlify/skills/dashboard-workflows/references/delay-step # Delay Step Delay step to pause workflow execution. **Place BEFORE channel steps.** ## Common Patterns * **1–2 hours** before reminders. * **24 hours** before follow-up emails. * **5–10 minutes** between push and email for urgent notifications. ## See Also * [`step-conditions.md`](./step-conditions.md) — common pattern: skip a delay (and the steps after it) when an earlier In-App was already read * [`digest-step.md`](./digest-step.md) — when batching is the right tool instead of a fixed delay # Digest step Source: https://docs.novu.co/.mintlify/skills/dashboard-workflows/references/digest-step # Digest Step Digest step to batch multiple notifications. **Place BEFORE channel steps.** ## Digest Types * **`regular`** (default): * With a **look-back window** — digest only if a recent message was sent. * Without a look-back window — groups all events that arrive within the time window. * **`timed`** — with a cron expression, collects events until the scheduled time (UTC). ## Common Patterns * Pass the first event immediately, digest the rest. * Batch activity updates hourly. * Group by key (e.g. `payload.projectId`) for per-project digests. ## Accessing Digested Events Downstream Steps **after** a digest step can reference: * `steps..events` — the array of digested events (use with a `repeat` node in Block Editor or a `{% for %}` loop in HTML). * `steps..eventCount` — the number of digested events. See [`email-step.md`](./email-step.md) for the Block Editor `repeat` + `current.payload.*` pattern. ## See Also * [`design-workflow/references/digest-defaults.md`](../../design-workflow/references/digest-defaults.md) — default windows, digest key composition, when to skip the digest * [`email-step.md`](./email-step.md) — Block Editor digest variables (`current.payload.*` + `aliasFor`) * [`step-conditions.md`](./step-conditions.md) — gate steps on `eventCount` (e.g. only send a summary email when more than N events) # Email step Source: https://docs.novu.co/.mintlify/skills/dashboard-workflows/references/email-step # Email Step Email step for detailed content, formal communications, receipts. ## Schema Requirements (choose one `editorType`) ### Option 1: Block Editor Format (recommended for simple email layouts) Required properties: `subject`, `editorType`, `body`. | Field | Value | | - | - | | `subject` | `string` — email subject line | | `editorType` | `"block"` | | `body` | `object` — email body in Maily TipTap JSON format | ### Option 2: HTML Format (recommended for complex email layouts) Required properties: `subject`, `editorType`, `body`. | Field | Value | | - | - | | `subject` | `string` — email subject line | | `editorType` | `"html"` | | `body` | `string` — email body always in HTML format. Use semantic HTML with inline styles. Structure with headings, paragraphs, and styled buttons. | ## Email Content Requirements * Subject lines should be compelling and **under 60 characters**. * Keep paragraphs short and scannable. * Include clear call-to-action buttons when necessary. ## HTML Format Requirements * `body` must be valid HTML with **inline styles** for email client compatibility. * Use semantic HTML: `

`, `

`, `

`, ``, `` for layout. * Add inline styles for colors, spacing, fonts (e.g. `style="color: #333; margin: 16px 0;"`). * Make sure that the content has enough whitespace between the elements and around the content to be readable. * Use **tables for layout** to ensure compatibility across email clients. Avoid flexbox or grid; apply inline styles to table cells only when needed for spacing or typography. * Include variables using Liquid syntax: `{{ subscriber.firstName }}`, `{{ payload.variableName }}`. * **Full LiquidJS syntax** (loops, conditionals, filters) is only supported in the HTML editor. * When the payload or available variables contain an array (e.g. `payload.items`, `payload.providers`), use a LiquidJS `{% for %}` loop to iterate over it. Never hardcode or list individual array items as separate HTML elements. ```liquid theme={null} {% for item in payload.items %}

{{ item.name }}

{% endfor %} ``` ### Example button (HTML format only) ```html theme={null} Click Here ``` ## Block Editor Format Guideline 1. Use `heading` nodes for titles (level 1 for main, level 2 for sections). 2. Use `text` node for body text. 3. Use `spacer` nodes between sections (`height: 16` or `24`). 4. Use `button` nodes for CTAs with good contrast colors. ### Block Editor nodes must follow these requirements 1. Maily TipTap JSON format with proper node structure is required. 2. **Variable names in node attributes must NEVER use curly braces `{{` and `}}`.** This applies to ALL attributes across ALL node types (`url`, `text`, `src`, `id`, `each`, `href`, `externalLink`, etc.). * Always use the bare variable name directly, without any templating syntax. * Correct: `"payload.actionUrl"` * Wrong: `"{{ payload.actionUrl }}"` 3. **Text variables** should be defined using `variable` nodes with an `id` attribute like `"id": "subscriber.firstName"` or `"id": "payload.variableName"`. The `aliasFor` attribute is optional and should be used **only** when the variable is accessed inside a `repeat` node. 4. The **`repeat` node** must always have the `each` attribute, for example `"each": "payload.items"`. To access the items in the array, you must use the `variable` node with: * `id` attribute (required) * `aliasFor` attribute (required) Rules for the `variable` node **only** when used inside a `repeat` node: * The `id` attribute must use the special prefix `current.`, for example `"id": "current.variableName"`. * The `aliasFor` attribute must consist of: `` + `.` + ``, for example `"aliasFor": "payload.items.variableName"`. * Never use any other prefix than `current.` in the `variable` node `id` attribute when accessing array items. * Example: ```json theme={null} { "type": "variable", "attrs": { "id": "current.variableName", "aliasFor": "payload.items.variableName" } } ``` When the payload or available variables contain an array (e.g. `payload.items`, `payload.providers`), always use a `repeat` node to iterate over it. Never hardcode or list individual array items as separate nodes. Never use the `current.*` variable outside of the `repeat` node. 5. **`button` nodes:** when `url` or `text` holds a variable, use the bare variable name and set the corresponding boolean flag. * Correct: `{ "type": "button", "attrs": { "url": "payload.actionUrl", "isUrlVariable": true } }` * Wrong: `{ "type": "button", "attrs": { "url": "{{ payload.actionUrl }}", "isUrlVariable": true } }` * Correct: `{ "type": "button", "attrs": { "text": "payload.label", "isTextVariable": true } }` 6. **`image` nodes:** same rule — bare variable name in `src` or `externalLink` with the matching boolean flag. * Correct: `{ "type": "image", "attrs": { "src": "payload.imageUrl", "isSrcVariable": true } }` * Wrong: `{ "type": "image", "attrs": { "src": "{{ payload.imageUrl }}", "isSrcVariable": true } }` 7. **`inlineImage` nodes:** same rule for `src` with `isSrcVariable` and `externalLink` with `isExternalLinkVariable`. * Correct: `{ "type": "inlineImage", "attrs": { "src": "payload.imageUrl", "isSrcVariable": true } }` * Correct: `{ "type": "inlineImage", "attrs": { "externalLink": "payload.imageUrl", "isExternalLinkVariable": true } }` ### Digest Step Special Variables 1. **`steps..events`** * Available **only** for steps that come **after** a digest step. * The variable name is dynamic and depends on the digest step ID, for example: * `steps.digest-step.events` * `steps.digest-step-2.events` * It must be used with the `repeat` node only to iterate over the digested events payload. * To access the digested events `payload` data, use the `variable` node with attributes: * `id` attribute (required): * Must start with the `current.payload` prefix. * Format: `"current.payload."`. Example: `"id": "current.payload.variableName"`. * Never use any prefix other than `current.payload` in the `variable` node `id` attribute when accessing digested events. * `aliasFor` attribute (required): * Format: `"aliasFor": "steps..events.payload."`. * Example: `"aliasFor": "steps.digest-step.events.payload.variableName"`. * Example: ```json theme={null} { "type": "variable", "attrs": { "id": "current.payload.variableName", "aliasFor": "steps.digest-step.events.payload.variableName" } } ``` 2. **`steps..eventCount`** * Available **only** for steps that come **after** a digest step. * The variable name is dynamic and depends on the digest step ID, for example: * `steps.digest-step.eventCount` * `steps.digest-step-2.eventCount` * Used to access the **number of digested events**. ### HTTP Request Step Response Variables Available **only** for steps that come **after** an HTTP Request step that defines a `responseBodySchema`. Each property from the schema becomes a variable at `steps..`. * **Block Editor:** create a `variable` node: * `id`: `"steps.."` * Example: `{ "type": "variable", "attrs": { "id": "steps.fetch-user.name" } }` * **HTML format:** use Liquid syntax: `{{ steps.fetch-user.name }}`. > Only properties declared in the HTTP step's `responseBodySchema` are available — do not reference arbitrary response fields. ## See Also * [`http-request-step.md`](./http-request-step.md) — declare `responseBodySchema` so an email step can read response data * [`digest-step.md`](./digest-step.md) — when an email step is preceded by a digest, use the special variables above * [`step-conditions.md`](./step-conditions.md) — gate the email on subscriber state or previous step results # Http request step Source: https://docs.novu.co/.mintlify/skills/dashboard-workflows/references/http-request-step # HTTP Request Step HTTP Request step to call an external API, send a webhook, or fetch data from a third-party service. This is an **action step** — it does **not** send a notification to the subscriber. Use it when the workflow needs to integrate with external systems. ## Required Fields | Field | Description | | - | - | | `method` | HTTP method: `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `HEAD`, `OPTIONS` | | `url` | Absolute URL or a template variable. Examples: `"https://api.example.com/notify"`, `"{{payload.webhookUrl}}"` | ## Optional Fields | Field | Description | | - | - | | `headers` | Key-value pairs for request headers. Always include `Content-Type` when sending a body. | | `body` | Key-value pairs for the request body (only applicable for `POST`, `PUT`, `PATCH`). | | `responseBodySchema` | JSON Schema object (`type`, `properties`, `required`) describing the expected response shape. Defines which response fields are available downstream. | | `enforceSchemaValidation` | Set `true` only when validating the response against `responseBodySchema`. | | `continueOnFailure` | When `true`, the workflow continues even if this step fails. Default: `false`. | ## Response Schema When any subsequent step needs to use data from this HTTP step's response, you **MUST** define a `responseBodySchema`. Only properties declared in the schema are available to later steps as `{{ steps.. }}`. ```json theme={null} { "type": "object", "properties": { "name": { "type": "string" }, "email": { "type": "string" } }, "required": ["name", "email"] } ``` A downstream email step can then read `{{ steps.fetch-user.name }}` and `{{ steps.fetch-user.email }}`. ## Common Patterns * **Webhook after notification:** `POST` to `"{{payload.webhookUrl}}"` with event details in `body`. * **REST API call:** `POST` / `PUT` to a fixed URL with subscriber or payload data. * **Data fetch:** `GET` from an external service with `responseBodySchema` to make response available to subsequent steps. ## Guidelines * **Never hardcode secrets or API keys** — use payload or subscriber variables instead. * Set `Content-Type: application/json` header when sending a JSON body. * Use `continueOnFailure: true` when the HTTP call is non-critical to the workflow. * For `headers` and `body`: use an empty array `[]` when not needed. Never include entries with empty keys or values (e.g. `[{"key":"","value":""}]` is invalid). * Always define `responseBodySchema` when any later step references this step's response. ## See Also * [`step-conditions.md`](./step-conditions.md) — branch on HTTP response values (`{ "==": [{ "var": "steps..status" }, "active"] }`) * [`email-step.md`](./email-step.md) — read HTTP response fields from a Block Editor `variable` node or HTML Liquid expression * [`design-workflow/references/workflow-templates.md`](../../design-workflow/references/workflow-templates.md) — templates 8 and 9 show webhook and fetch-then-notify patterns # In app step Source: https://docs.novu.co/.mintlify/skills/dashboard-workflows/references/in-app-step # In-App Step In-app notification for real-time updates, activity feeds, high engagement. ## Guidelines * Include action buttons for engagement. * Focus on a **single action or piece of information**. * Can be longer than push notifications — but stay scannable. ## Variables Use Liquid syntax for personalization in subject / body / action labels: * `{{ subscriber.firstName }}` * `{{ payload.* }}` * `{{ steps.. }}` — only when the upstream HTTP step declares the property in its `responseBodySchema` ## See Also * [`step-conditions.md`](./step-conditions.md) — gate the In-App step (rarely needed; In-App is usually the primary channel) * [`design-workflow/references/channel-selection.md`](../../design-workflow/references/channel-selection.md) — when In-App is the right default * [`inbox-integration/SKILL.md`](../../inbox-integration/SKILL.md) — how In-App notifications surface in the recipient app # Push step Source: https://docs.novu.co/.mintlify/skills/dashboard-workflows/references/push-step # Push Step Push notification for mobile engagement, re-engagement, time-sensitive updates. ## Guidelines * **Title** (`subject`) must be **under 50 characters**. * **Body** must be **under 150 characters**. * Action-oriented; **front-load the important info**. ## Variables Use Liquid syntax in `subject` and `body`: * `{{ subscriber.firstName }}` * `{{ payload.* }}` * `{{ steps.. }}` — only when the upstream HTTP step declares the property in its `responseBodySchema` ## Common Pattern Pair Push with a step condition so it only fires when the recipient is offline (otherwise the In-App alert already covers it): ```json theme={null} { "==": [{ "var": "subscriber.isOnline" }, "false"] } ``` See [`step-conditions.md`](./step-conditions.md). ## See Also * [`step-conditions.md`](./step-conditions.md) — the canonical "subscriber offline" condition for Push * [`design-workflow/references/channel-selection.md`](../../design-workflow/references/channel-selection.md) — when Push is the right channel # Sms step Source: https://docs.novu.co/.mintlify/skills/dashboard-workflows/references/sms-step # SMS Step SMS step for urgent alerts, verification codes, time-sensitive messages. ## Guidelines * `body` must be **under 160 characters** to avoid message splitting. * Direct and actionable — essential info only. * Avoid special characters and unnecessary URLs. ## Variables Use Liquid syntax in `body`: * `{{ subscriber.firstName }}` * `{{ payload.* }}` * `{{ steps.. }}` — only when the upstream HTTP step declares the property in its `responseBodySchema` ## See Also * [`step-conditions.md`](./step-conditions.md) — common pattern: SMS only when `critical: true` or other channels failed * [`design-workflow/references/channel-selection.md`](../../design-workflow/references/channel-selection.md) — SMS is a last resort: OTP, regulatory, true emergencies # Step conditions Source: https://docs.novu.co/.mintlify/skills/dashboard-workflows/references/step-conditions # Step Conditions Generate a [JSONLogic](https://jsonlogic.com) condition for step execution in the Dashboard / Novu MCP. ## When to Use * The step **executes when the condition evaluates to `true`**. * Use `null` to **remove** the condition (the step always executes). ## Merge vs Replace vs Remove When editing an existing condition via the Novu MCP, decide based on the user's intent: | Intent | Behavior | | - | - | | **ADD / EXTEND** — "add", "also", "and", "in addition" | Combine existing condition with new using AND: `{ "and": [existing, new] }` | | **REPLACE** — "change to", "update to", "set to", "replace with" | Return the new condition entirely; ignore existing | | **REMOVE** — "remove", "delete", "clear" | Return `null` | ## Variable Reference Format Use `var` for variable references: `{ "var": "path.to.value" }`. | Namespace | Source | | - | - | | `payload.*` | Trigger payload (e.g. `payload.amount`, `payload.priority`) | | `subscriber.*` | Subscriber data (e.g. `subscriber.firstName`, `subscriber.isOnline`) | | `steps.*` | Previous step state (e.g. `steps.welcome-in-app.read`, `steps.welcome-in-app.seen`) | | `steps..*` | HTTP step response properties **defined in its `responseBodySchema`** (e.g. `steps.fetch-user.role`) | ## Common Patterns ### Subscriber offline ```json theme={null} { "==": [{ "var": "subscriber.isOnline" }, "false"] } ``` ### In-App not read ```json theme={null} { "==": [{ "var": "steps..read" }, "false"] } ``` ### In-App not seen ```json theme={null} { "==": [{ "var": "steps..seen" }, "false"] } ``` ### HTTP response value equals ```json theme={null} { "==": [{ "var": "steps..status" }, "active"] } ``` > Only when the property is declared in the HTTP step's `responseBodySchema`. See [`http-request-step.md`](./http-request-step.md). ### Payload value equals ```json theme={null} { "==": [{ "var": "payload.priority" }, "high"] } ``` ### Payload value not equals ```json theme={null} { "!=": [{ "var": "payload.priority" }, "low"] } ``` ### AND / OR / NOT ```json theme={null} { "and": [condition1, condition2] } ``` ```json theme={null} { "or": [condition1, condition2] } ``` ```json theme={null} { "!": [condition] } ``` ## Output Return only the `skip` field: a JSONLogic object **or** `null`. ## See Also * [`design-workflow/references/step-conditions.md`](../../design-workflow/references/step-conditions.md) — side-by-side Dashboard JSON-Logic vs Framework `skip` semantics, plus the full list of available `subscriber.*` properties and step-output paths * [`http-request-step.md`](./http-request-step.md) — declare `responseBodySchema` so an HTTP response field becomes addressable in `steps..` * [`design-workflow/references/channel-selection.md`](../../design-workflow/references/channel-selection.md) — when to use the "subscriber offline" gate on Push # Throttle step Source: https://docs.novu.co/.mintlify/skills/dashboard-workflows/references/throttle-step # Throttle Step Throttle step to limit notification frequency and prevent fatigue. ## Common Patterns * Max **3 per hour** per user. * Max **1 per day** for marketing. * Throttle by key (e.g. `payload.alertType`) for grouped limits. ## See Also * [`digest-step.md`](./digest-step.md) — use a digest when the goal is to **batch** events into one message; use throttle when the goal is to **drop** excess messages * [`step-conditions.md`](./step-conditions.md) — combine throttle with conditions for finer routing # Channel selection Source: https://docs.novu.co/.mintlify/skills/design-workflow/references/channel-selection # Channel Selection Decision rules for picking which channels a workflow should send on. Applies to both Dashboard- and Framework-authored workflows. ## Decision Tree ``` Did the user specify exact channels? │ ┌────────────── yes ──┴── no ─────────────┐ ▼ ▼ Use ONLY those channels. Pick from channels CONFIGURED No fallbacks. No extras. in the organization, in priority Add the channel even if it order, up to 3 channels: isn't configured (user asked). In-App > Email > Chat > Push > SMS ``` ## Rule 1 — User-Specified Channels Are Exact If the user mentions channels (`"send a push notification…"`, `"email and SMS only"`), use exactly those channels. Do **not** add fallbacks. Do **not** drop a channel because it's not configured — the user explicitly asked for it. > "Create a push notification when order ships" > > ``` > Trigger > ↓ > Push > ``` > "Notify users via email and SMS when their invoice is overdue" > > ``` > Trigger > ↓ > Email > ↓ > SMS > ``` ## Rule 2 — Default Selection (No User Preference) When the user doesn't specify channels, choose from channels **configured in the organization** in this order: 1. **In-App** 2. **Email** 3. **Chat** 4. **Push** 5. **SMS** Stop at 3 channels. Skipping is fine — pick the most relevant subset, not the first 3. ## Per-Channel Guidance ### In-App * Default for any in-product content. * Always include if the recipient is signed-in and could be using your product. * Skip when the user can't see it: password reset, OTP, pre-signup welcome, anything sent before account exists. ### Email * Use for receipts, documentation, async communication, things the user will want to find later. * Default fallback after In-App. * Skip for pure conversational pings (use In-App or Push instead). ### Chat (Slack / Teams / Discord) * Add when the channel is configured **and** `severity >= MEDIUM`. * Best for ops, deploys, internal alerts, B2B workflows. * Skip for marketing, low-severity nudges, or anything aimed at end consumers. ### Push * Use as a fallback when the subscriber is **offline** but needs immediate awareness. * Always pair with a step condition: only send when `subscriber.isOnline == false`. * Skip when the subscriber is online (the In-App alert covers it). ### SMS * Last resort. Reserve for true emergencies, OTP, regulatory compliance. * Add for `critical: true` workflows where every channel matters. * Skip if any other channel reaches the user. ## Combining Rules with Severity | Severity | Suggested channel mix (no user pref) | | - | - | | unset | In-App + Email + (Push if offline) | | `LOW` | In-App + Email | | `MEDIUM` | In-App + Email + Chat (if configured) | | `HIGH` | In-App + Chat + Email + Push (if offline) | | `critical: true` | All available channels in parallel; Push gated by offline | ## Quick Examples * **Order confirmation** — In-App, Email, Push (offline only) * **Comment on post** — In-App, Push (offline only), Email (only if In-App unread after delay) * **Payment failed** — In-App, Chat, Email, Push (offline only) * **Account suspended** (`critical: true`) — In-App, Email, SMS, Chat, Push (offline only) * **Forgot password** (`critical: true`, no In-App) — Email, SMS ## See Also * [`severity-and-critical.md`](./severity-and-critical.md) — how severity & `critical` change the channel mix * [`step-conditions.md`](./step-conditions.md) — how to gate Push on `subscriber.isOnline` * [`workflow-templates.md`](./workflow-templates.md) — the 9 templates with their channel choices # Digest defaults Source: https://docs.novu.co/.mintlify/skills/design-workflow/references/digest-defaults # Digest Defaults Defaults for the `digest` step in any workflow. Applies to both Dashboard digest and Framework `step.digest`. ## Default Configuration | Field | Default | | - | - | | Type | `regular` | | Look-back window | **5 minutes** | | Digest time | **1 hour** | | Digest key | `subscriberId` | A `regular` digest collects events that arrive within the look-back window after the first trigger, then waits the digest time before sending the aggregated notification. With the defaults, the first trigger waits up to 1 hour, scooping up any matching trigger that lands within 5 minutes of one another. ## Skip the Digest When * `severity: HIGH`, or * `critical: true` Critical and very-high-severity workflows must deliver immediately. The digest step is auto-skipped in those cases. ## Digest Key Composition The digest key controls **what counts as the same digest**. Default is `subscriberId` so each user gets their own digest. Add more parts to the key for finer grouping: | Pattern | Use case | | - | - | | `subscriberId` | One digest per recipient (default) | | `subscriberId + threadId` | Conversational flows — one digest per thread/post (comments, replies, mentions) | | `subscriberId + projectId` | Per-project activity feeds | | `subscriberId + organizationId` | Multi-tenant per-org digests | > Without `+threadId`, a comment on Post A and a comment on Post B end up in the same digest. The user sees "5 new comments" instead of "2 new comments on Post A, 3 on Post B". ## Conversational Digest Example For a "comment on your post" workflow: ``` Trigger (event: payload.threadId: "post_123") ↓ Digest: type "regular", look-back 5min, digest time 1h Key: subscriberId + threadId ↓ In-App Redirect: → thread ``` Each thread gets its own digest. Comments on Post 123 don't mix with comments on Post 456. ## When NOT to Add a Digest * Single-event flows (order confirmation for one order, password reset for one request). * `critical: true` workflows (digest is bypassed anyway). * High-severity alerts (`severity > HIGH`). * User-specified channel-only flows where the user didn't ask for batching. ## When TO Add a Digest * High-frequency conversational events (comments, mentions, reactions, follows). * Activity feeds ("5 new updates in your project"). * Lifecycle nudges that may fire many times in a short window. ## Cron-Based Digests Use a cron expression instead of `look-back + digest time` for fixed-schedule digests (e.g. "every weekday at 9 AM"): * Dashboard: switch the digest type to `cron` and provide a cron string. * Framework: pass `cron: "0 9 * * 1-5"` to `step.digest` instead of `unit`/`amount`. See [`framework-integration/references/workflow-and-steps.md`](../../framework-integration/references/workflow-and-steps.md#stepdigest) for the Framework signature. ## Common Pitfalls 1. **Forgetting `+threadId` for conversational flows** — comments on different posts collapse into one digest. 2. **Adding a digest to a `critical` workflow** — it's auto-skipped, but it's a code smell that hides intent. 3. **Two digest steps in one workflow** — not supported. Chain workflows with a custom step (Framework) or a second workflow trigger. 4. **Very long look-back windows** — digest delivery feels delayed. Keep look-back ≤ digest time. ## See Also * [`severity-and-critical.md`](./severity-and-critical.md) — when digest is auto-skipped * [`workflow-templates.md`](./workflow-templates.md) — templates 1 and 2 illustrate the standard digest pattern * [`framework-integration/references/workflow-and-steps.md`](../../framework-integration/references/workflow-and-steps.md) — Framework `step.digest` reference # Severity and critical Source: https://docs.novu.co/.mintlify/skills/design-workflow/references/severity-and-critical # Severity & Critical `severity` and `critical` are two **independent** workflow-level dials. Most workflows set neither. ## Severity | Value | Meaning | When to use | | - | - | - | | unset | No prioritization | Default. Use for the vast majority of workflows. | | `LOW` | Informational, no urgency | Marketing nudges, low-priority lifecycle. | | `MEDIUM` | Worth surfacing | Mentions, light alerts. | | `HIGH` | "Deal with this today" | Payment failed, trial expiring tomorrow, KYC required. | Severity is **purely visual** — it does not change preferences, digest, or delivery. It only affects how the Inbox renders the notification (color, glow, bell color), and informs the digest skip rule below. > See [`inbox-integration/SKILL.md`](../../inbox-integration/SKILL.md) ("Severity styling") for the visual mapping (`colorSeverityHigh`, `severityHigh__notificationBar`, etc.). ## Critical `critical: true` is the **runtime** override. When set: * **Subscriber preferences are bypassed.** The notification is delivered even if the subscriber disabled the channel. * **Digest is skipped.** Each trigger delivers immediately; no aggregation. * **No delays.** All steps run as fast as possible. * **All available channels** fire in parallel (Push still gated by `subscriber.isOnline == false`). Reserve `critical: true` for must-deliver events: * Account suspended / blocked * Security alert (new device login, suspicious activity) * Forgot password / OTP delivery * Legal or compliance notices > A workflow can be `critical: true` with `severity` unset — the two dials don't depend on each other. ## `readOnly` vs `critical` — the trap These are easy to confuse. They control different things: | Flag | Where it lives | What it does | | - | - | - | | `preferences.all.readOnly: true` | Workflow's preference defaults | Hides the workflow from the **Preferences UI**. Subscribers can't toggle channels for it. | | `critical: true` | Workflow-level flag | Bypasses preferences, digest, and delays at **runtime**. Delivers regardless of opt-out. | In practice you usually want `critical: true` (forces delivery). `readOnly: true` alone just removes the toggle from the UI but does not override existing subscriber overrides. See [`manage-preferences/SKILL.md`](../../manage-preferences/SKILL.md) for the resolution order. ## Behavior Matrix | Scenario | Preferences applied? | Digest runs? | Delays applied? | Inbox styling | | - | - | - | - | - | | `severity` unset, `critical: false` | yes | yes | yes | default | | `severity: HIGH`, `critical: false` | yes | **no** | yes | high | | `severity: HIGH`, `critical: true` | **no** | **no** | **no** | high | | `severity` unset, `critical: true` | **no** | **no** | **no** | default | Digest is automatically skipped when `severity: HIGH` **or** `critical: true`. ## Picking the Right Combination | Use case | severity | critical | | - | - | - | | Order confirmation | unset | false | | Comment on your post | unset | false | | Payment failed | HIGH | false | | Trial expiring tomorrow | HIGH | false | | Account suspended (KYC required) | HIGH | **true** | | Forgot password / OTP | unset | **true** | | Security alert | HIGH | **true** | | Marketing / weekly newsletter | unset | false | ## Common Pitfalls 1. **Setting `severity: HIGH` doesn't make the workflow critical** — it still respects preferences and runs delays. Add `critical: true` if you need bypass. 2. **`critical: true` doesn't auto-set severity** — set `severity: HIGH` explicitly if you also want the high-severity Inbox styling. 3. **Don't mark marketing workflows critical** — bypassing preferences for promotional content damages trust and is a deliverability risk. 4. **`readOnly: true` won't force delivery** — it only hides the workflow toggle. Use `critical: true` to actually force delivery. ## See Also * [`channel-selection.md`](./channel-selection.md) — how `critical` expands the channel mix * [`digest-defaults.md`](./digest-defaults.md) — when digest is auto-skipped * [`workflow-templates.md`](./workflow-templates.md) — templates that show `critical` in context * [`manage-preferences/SKILL.md`](../../manage-preferences/SKILL.md) — preference resolution order # Step conditions Source: https://docs.novu.co/.mintlify/skills/design-workflow/references/step-conditions # Step Conditions A step condition decides whether a step **runs** or is **skipped**. Same semantics on both authoring surfaces; different syntax. | Surface | Syntax | | - | - | | Dashboard (no-code) | [JSON-Logic](https://jsonlogic.com) on `step.condition` — `{ "==": [...] }` | | Framework (`@novu/framework`) | `skip: () => boolean \| Promise` callback | > Dashboard semantics: condition evaluates to `true` ⇒ step **runs**. > Framework semantics: `skip` returns `true` ⇒ step **is skipped**. > They're mirror images — invert the boolean when porting between surfaces. ## Available Variables Use **only** variables that are in scope for the workflow run. > **Prefer reusing existing variables for consistency.** Only introduce new `payload.*` variables when truly needed — duplication makes templates and conditions harder to maintain. ### Variable Namespaces | Namespace | Source | Contents | | - | - | - | | `workflow.*` | system | Workflow metadata: `workflowId`, `name`, `description`, `tags`, `severity` | | `subscriber.*` | system | Recipient info: `firstName`, `lastName`, `email`, `phone`, `avatar`, `locale`, `timezone`, `subscriberId`, `isOnline`, `lastOnlineAt`, `data` | | `payload.*` | user-defined | Event data passed at trigger time (e.g. `actionUrl`, `productName`, `orderNumber`). Validated against `payloadSchema` when defined. | | `steps.*` | system | Step results: In-App `seen` / `read`, digest `events` / `eventCount`, HTTP response properties (only those declared in `responseBodySchema`) | | `context.*` | user-defined | Multi-tenant metadata passed at trigger time (e.g. `tenant`, `region`, `app`). See [`inbox-integration/SKILL.md`](../../inbox-integration/SKILL.md) for context-based isolation. | ### Subscriber Properties Available `subscriber.*` properties: * `subscriber.firstName` * `subscriber.lastName` * `subscriber.email` * `subscriber.phone` * `subscriber.avatar` * `subscriber.locale` * `subscriber.timezone` * `subscriber.subscriberId` * `subscriber.isOnline` * `subscriber.lastOnlineAt` * `subscriber.data` (custom subscriber data; deeply addressable as `subscriber.data.`) ### Step Outputs | Path | When available | Notes | | - | - | - | | `steps..seen` | After an In-App step | Boolean — `true` once the user has seen the notification | | `steps..read` | After an In-App step | Boolean — `true` once the user has marked it read | | `steps..events` | After a digest step | Array of digested trigger events | | `steps..eventCount` | After a digest step | Length of `events` (convenience for templates) | | `steps..` | After an HTTP step | Only properties declared in `responseBodySchema` are addressable | ## Canonical Conditions (Dashboard JSON-Logic) ### Subscriber is offline ```json theme={null} { "==": [{ "var": "subscriber.isOnline" }, "false"] } ``` ### In-App was not read ```json theme={null} { "==": [{ "var": "steps..read" }, "false"] } ``` ### In-App was not seen ```json theme={null} { "==": [{ "var": "steps..seen" }, "false"] } ``` ### Workflow tags include any of ```json theme={null} { "in": ["tag1,tag2", { "var": "workflow.tags" }] } ``` ### HTTP response property equals a value ```json theme={null} { "==": [{ "var": "steps..status" }, "active"] } ``` > The property must be declared in the HTTP step's `responseBodySchema`. Undeclared properties are not addressable. ## Framework Equivalents The same conditions in `@novu/framework`. Note that `skip` is the inverse of "run if true" — you return `true` to **skip**. ### Subscriber is offline (run only if offline) ```typescript theme={null} const inApp = await step.inApp("inbox", async () => ({ /* ... */ })); await step.push("offline-push", async () => ({ title: "...", body: "..." }), { skip: ({ subscriber }) => subscriber.isOnline === true, }); ``` ### In-App was not read (send email fallback) ```typescript theme={null} const inApp = await step.inApp("inbox", async () => ({ /* ... */ })); await step.delay("wait", async () => ({ unit: "hours", amount: 4 })); await step.email("fallback", async () => ({ subject: "...", body: "..." }), { skip: () => inApp.read === true, }); ``` ### Branch on HTTP response ```typescript theme={null} const plan = await step.http("fetch-plan", async () => ({ method: "GET", url: `https://api.example.com/users/${payload.userId}/plan`, responseBodySchema: { type: "object", properties: { status: { type: "string" } }, required: ["status"], } as const, })); await step.email("notify", async () => ({ /* ... */ }), { skip: () => plan.status !== "active", }); ``` ## Quick Reference | Intent | Dashboard (JSON-Logic) | Framework (`skip`) | | - | - | - | | Run only when subscriber is offline | `{ "==": [{ "var": "subscriber.isOnline" }, "false"] }` | `skip: () => subscriber.isOnline === true` | | Run only when In-App not read | `{ "==": [{ "var": "steps.inbox.read" }, "false"] }` | `skip: () => inAppResult.read === true` | | Run only when In-App not seen | `{ "==": [{ "var": "steps.inbox.seen" }, "false"] }` | `skip: () => inAppResult.seen === true` | | Run only for workflows tagged "billing" | `{ "in": ["billing", { "var": "workflow.tags" }] }` | `skip: () => !tags.includes("billing")` | | Run only when HTTP `status == "active"` | `{ "==": [{ "var": "steps.fetch.status" }, "active"] }` | `skip: () => fetchResult.status !== "active"` | ## Common Pitfalls 1. **Inverting the boolean wrong** — Dashboard runs when condition is `true`; Framework `skip` skips when `true`. They're opposites. 2. **Referencing undeclared HTTP properties** — only properties in `responseBodySchema` are addressable in `steps..`. 3. **Using `subscriber.isOnline == true` as a string** — `isOnline` is a boolean. Use `"false"` (string) only in JSON-Logic; in Framework use the JS boolean `false`. 4. **Conditions on a delay step** — delays support skip too, but if a delay is skipped the workflow proceeds immediately. Don't treat skip as "shorten". ## See Also * [`channel-selection.md`](./channel-selection.md) — uses these conditions for offline gating * [`workflow-templates.md`](./workflow-templates.md) — every template's `Step condition` lines map to these snippets * [`framework-integration/references/workflow-and-steps.md`](../../framework-integration/references/workflow-and-steps.md) — full Framework `skip` reference * [`dashboard-workflows/references/step-conditions.md`](../../dashboard-workflows/references/step-conditions.md) — Dashboard / Novu MCP authoring flow, including the merge / replace / remove intent rules # Workflow templates Source: https://docs.novu.co/.mintlify/skills/design-workflow/references/workflow-templates # Workflow Templates Nine reference flows. Match a use case to a template and copy its shape on whichever surface you author on (Dashboard or Framework). Each template includes a metadata table: | Field | Meaning | | - | - | | `Severity` | `LOW` / `MEDIUM` / `HIGH` / unset (`None`) | | `Critical` | `true` ⇒ bypass preferences, skip digest, immediate delivery | | `Actionable` | `Informational` (no action) or `Requires Action` (CTA) | | `Interaction` | `USER TRANSACTION`, `CONVERSATIONAL`, `SYSTEM TRANSACTION`, `LIFECYCLE` | Channels noted with `(if channel is configured)` are only included when the organization has that integration set up. Steps with a `Step condition` line run only when the condition holds — see [`step-conditions.md`](./step-conditions.md) for the JSON-Logic and Framework `skip` equivalents. *** ## 1. Order Confirmation | Severity | None | | - | - | | Critical | `false` | | Actionable | Informational | | Interaction | USER TRANSACTION | ``` Trigger ↓ Digest: type "regular", look-back 5min, digest time 1h Key: subscriberId ↓ In-App ↓ Email ↓ Push (if channel is configured) Step condition: Send only if subscriber is offline ``` *** ## 2. Comment on Your Post | Severity | None | | - | - | | Critical | `false` | | Actionable | Informational | | Interaction | CONVERSATIONAL | ``` Trigger (event: payload.threadId: "post_123") ↓ Digest: type "regular", look-back 5min, digest time 1h Key: subscriberId + threadId ↓ In-App Redirect: → thread ↓ Push (if channel is configured) Step condition: Send only if subscriber is offline ↓ Delay (4 hours) Step condition: Only if In-App not seen ↓ Email Content: summary of the comments Step condition: Only if In-App not seen ``` *** ## 3. Payment Failed | Severity | HIGH | | - | - | | Critical | `false` | | Actionable | Requires Action | | Interaction | USER TRANSACTION | ``` Trigger ↓ In-App ↓ Chat (if channel is configured) ↓ Email ↓ Push (if channel is configured) Step condition: Send only if subscriber is offline ``` *** ## 4. Account Suspended | Severity | HIGH | | - | - | | Critical | `true` | | Actionable | Requires Action | | Interaction | SYSTEM TRANSACTION | Critical workflow: * Bypasses subscriber preferences * No delays, immediate delivery * All available channels in parallel ``` Trigger (event: payload.account.suspended, payload.reason: "kyc_required") ↓ In-App ↓ Email ↓ SMS (if channel is configured) ↓ Chat (if channel is configured) ↓ Push (if channel is configured) Step condition: Send only if subscriber is offline ``` *** ## 5. Forgot Password | Severity | None | | - | - | | Critical | `true` | | Actionable | Requires Action | | Interaction | SYSTEM TRANSACTION | No In-App step — the user isn't signed in when this fires. ``` Trigger ↓ Email ↓ SMS (if channel is configured) ``` *** ## 6. Trial Expiring Tomorrow | Severity | HIGH | | - | - | | Critical | `false` | | Actionable | Requires Action | | Interaction | LIFECYCLE | ``` Trigger ↓ In-App ↓ Chat (if channel is configured) ↓ Email ↓ Push (if channel is configured) Step condition: Send only if subscriber is offline ``` *** ## 7. Explicit Channel Request (User-Specified) > User said: "Create a push notification when order ships" ``` Trigger ↓ Push ``` Rule: when the user names channels, use **only** those channels. No fallbacks. No extras. Add the channel even if it's not configured in the organization (the user explicitly asked for it). *** ## 8. Webhook / External API Call > User said: "Notify users and call our webhook when a payment fails" | Severity | HIGH | | - | - | | Critical | `false` | | Actionable | Requires Action | | Interaction | USER TRANSACTION | ``` Trigger ↓ In-App ↓ Email ↓ HTTP Request method: POST url: "{{payload.webhookUrl}}" headers: [{ key: "Content-Type", value: "application/json" }] body: [ { key: "event", value: "payment_failed" }, { key: "subscriberId", value: "{{subscriber.subscriberId}}" } ] continueOnFailure: true ``` Use `HTTP Request` whenever a workflow must call an external API or webhook in addition to (or instead of) sending notifications. *** ## 9. Fetch Data Then Notify (HTTP Step → Channel Step) > User said: "Fetch the user's plan from our API and send them a personalized email" ``` Trigger ↓ HTTP Request (stepId: "fetch-plan") method: GET url: "https://api.example.com/users/{{payload.userId}}/plan" responseBodySchema: { type: "object", properties: { planName: { type: "string" }, renewalDate: { type: "string" } }, required: ["planName", "renewalDate"] } ↓ Email subject: "Your {{ steps.fetch-plan.planName }} plan" body: "Your plan renews on {{ steps.fetch-plan.renewalDate }}." ``` Rule: when a subsequent step references HTTP response data, the HTTP step **must** declare a `responseBodySchema`. Only properties declared in the schema are addressable as `{{ steps.. }}`. *** ## See Also * [`channel-selection.md`](./channel-selection.md) — why each template chose those channels * [`severity-and-critical.md`](./severity-and-critical.md) — when to set severity vs critical * [`digest-defaults.md`](./digest-defaults.md) — the digest config used in templates 1 & 2 * [`step-conditions.md`](./step-conditions.md) — JSON-Logic / `skip` snippets for "send only if offline" and "only if In-App not seen" * [`framework-integration/references/workflow-and-steps.md`](../../framework-integration/references/workflow-and-steps.md) — Framework primitives to implement these flows in code # Bridge endpoint Source: https://docs.novu.co/.mintlify/skills/framework-integration/references/bridge-endpoint # Bridge Endpoint Setup The Bridge Endpoint is a single HTTP route on your application (`/api/novu` by default) that Novu Cloud calls to: * Discover registered workflows (`GET`) * Resolve step content for a given subscriber + payload (`POST`) * Verify HMAC signatures on incoming requests * Respond to `OPTIONS` preflight requests Each framework ships a `serve` wrapper that handles parsing, HMAC verification, and response shaping. ## Defaults | Default | Value | | - | - | | Path | `/api/novu` | | Methods | `GET`, `POST`, `OPTIONS` | | Required env var | `NOVU_SECRET_KEY` | | HMAC | On when `NODE_ENV !== "development"` | You may use any path. The full bridge URL becomes ``. Example: `https://api.acme.com/internal/novu`. ## Next.js (App Router) ```typescript theme={null} // app/api/novu/route.ts import { serve } from "@novu/framework/next"; import { welcomeWorkflow } from "@/novu/workflows"; export const { GET, POST, OPTIONS } = serve({ workflows: [welcomeWorkflow], }); ``` ## Next.js (Pages Router) ```typescript theme={null} // pages/api/novu.ts import { serve } from "@novu/framework/next"; import { welcomeWorkflow } from "../../novu/workflows"; export default serve({ workflows: [welcomeWorkflow] }); ``` ## Express ```typescript theme={null} import express from "express"; import { serve } from "@novu/framework/express"; import { welcomeWorkflow } from "./novu/workflows"; const app = express(); app.use(express.json()); // required so Novu can parse POST bodies app.use("/api/novu", serve({ workflows: [welcomeWorkflow] })); app.listen(4000); ``` ## NestJS ### Basic ```typescript theme={null} import { Module } from "@nestjs/common"; import { NovuModule } from "@novu/framework/nest"; import { welcomeWorkflow } from "./novu/workflows"; @Module({ imports: [ NovuModule.register({ apiPath: "/api/novu", workflows: [welcomeWorkflow], }), ], }) export class AppModule {} ``` ### With Dependency Injection ```typescript theme={null} import { Module } from "@nestjs/common"; import { NovuModule } from "@novu/framework/nest"; import { NotificationService } from "./notification.service"; import { UserService } from "./user.service"; @Module({ imports: [ NovuModule.registerAsync({ imports: [], useFactory: (notificationService: NotificationService) => ({ apiPath: "/api/novu", workflows: [notificationService.welcomeWorkflow()], }), inject: [NotificationService], }), ], providers: [NotificationService, UserService], exports: [NotificationService], }) export class AppModule {} ``` ```typescript theme={null} import { Injectable } from "@nestjs/common"; import { workflow } from "@novu/framework"; import { z } from "zod"; import { UserService } from "./user.service"; @Injectable() export class NotificationService { constructor(private readonly userService: UserService) {} public welcomeWorkflow() { return workflow( "welcome-email", async ({ step, payload }) => { await step.email("send-email", async () => { const user = this.userService.getUser(payload.userId); return { subject: `Hello, ${user.name}`, body: "We are glad you are here!", }; }); }, { payloadSchema: z.object({ userId: z.string() }) } ); } } ``` ## Remix ```typescript theme={null} // app/routes/api.novu.ts import { serve } from "@novu/framework/remix"; import { welcomeWorkflow } from "../novu/workflows"; const handler = serve({ workflows: [welcomeWorkflow] }); export { handler as action, handler as loader }; ``` ## SvelteKit ```typescript theme={null} // src/routes/api/novu/+server.ts import { serve } from "@novu/framework/sveltekit"; import { welcomeWorkflow } from "$lib/novu/workflows"; export const { GET, POST, OPTIONS } = serve({ workflows: [welcomeWorkflow] }); ``` ## Nuxt ```typescript theme={null} // server/api/novu.ts import { serve } from "@novu/framework/nuxt"; import { welcomeWorkflow } from "~/novu/workflows"; export default defineEventHandler(serve({ workflows: [welcomeWorkflow] })); ``` ## H3 ```typescript theme={null} import { createApp, eventHandler, toNodeListener } from "h3"; import { createServer } from "node:http"; import { serve } from "@novu/framework/h3"; import { welcomeWorkflow } from "./novu/workflows"; const app = createApp(); app.use("/api/novu", eventHandler(serve({ workflows: [welcomeWorkflow] }))); createServer(toNodeListener(app)).listen(4000); ``` ## AWS Lambda ```typescript theme={null} import { serve } from "@novu/framework/lambda"; import { welcomeWorkflow } from "./novu/workflows"; export const novu = serve({ workflows: [welcomeWorkflow] }); ``` Wire `novu` to API Gateway / Lambda Function URL. Use a stable URL for the bridge — avoid generated stage URLs that rotate. ## Custom `serve` Function (Any Framework) If your framework isn't directly supported, wrap `NovuRequestHandler`: ```typescript theme={null} import { NovuRequestHandler, ServeHandlerOptions } from "@novu/framework"; import type { Request, Response } from "express"; export const serve = (options: ServeHandlerOptions) => { const requestHandler = new NovuRequestHandler({ frameworkName: "express", ...options, handler: (incomingRequest: Request, response: Response) => ({ method: () => incomingRequest.method, headers: (key) => { const header = incomingRequest.headers[key]; return Array.isArray(header) ? header[0] : header; }, queryString: (key) => { const qs = incomingRequest.query[key]; return Array.isArray(qs) ? qs[0] : qs; }, body: () => incomingRequest.body, url: () => new URL(incomingRequest.url, `https://${incomingRequest.headers.host || ""}`), transformResponse: ({ body, headers, status }) => { Object.entries(headers).forEach(([name, value]) => response.setHeader(name, value)); return response.status(status).send(body); }, }), }); return requestHandler.createHandler(); }; ``` The handler must implement: | Method | Returns | | - | - | | `method()` | `"GET" \| "POST" \| "OPTIONS"` | | `headers(key)` | `string \| undefined` | | `queryString(key)` | `string \| undefined` | | `body()` | parsed JSON body | | `url()` | full `URL` object | | `transformResponse({ body, headers, status })` | the framework's response object | ## Tunnel URL vs Bridge URL | | Generated by | Use for | | - | - | - | | **Tunnel URL** | `npx novu@latest dev` (e.g. `https://.novu.sh/api/novu`) | Local development & Studio testing | | **Bridge URL** | Your deployed app (e.g. `https://api.acme.com/api/novu`) | Production sync | The tunnel ID is persisted on your machine, so the same URL is reused across `npx novu dev` runs. ## FAQ ### Does the bridge endpoint need to be publicly accessible? Yes. Novu Cloud calls it from autoscaled workers — there's no static IP to allowlist. Use HTTPS in production. ### Can I use a path other than `/api/novu`? Yes. Set the path you want when mounting `serve` and pass the full URL (`https://app.com/`) when syncing. ### Does the bridge use my application's auth middleware? You can place the bridge behind any middleware as long as `serve` receives untouched `GET`/`POST`/`OPTIONS` requests. **Don't** attach JWT auth to the bridge — Novu authenticates with HMAC instead. # Deployment Source: https://docs.novu.co/.mintlify/skills/framework-integration/references/deployment # Deployment `@novu/framework` operates in a **GitOps model** — your workflows live in source control, and a sync step pushes them to Novu Cloud after each merge. ## The flow ``` 1. Develop locally (Studio against your machine) 2. Open PR 3. CI runs `npx novu sync` against Development env 4. Test e2e in Development 5. Merge to main 6. CI runs `npx novu sync` against Production env ``` Each Novu environment (**Development**, **Production**) has its own secret key. You sync once per environment. ## Environments | Environment | Purpose | Secret key | | - | - | - | | **Local Studio** | Develop against your machine via tunnel | (uses dev secret key) | | **Development** | Staging — non-technical peers preview controls | `NOVU_SECRET_KEY` (dev) | | **Production** | Customer-facing triggers | `NOVU_SECRET_KEY` (prod) | Get keys from `https://dashboard.novu.co/api-keys` for each environment. ## CLI Sync ```bash theme={null} npx novu@latest sync \ --bridge-url \ --secret-key \ --api-url https://api.novu.co ``` For EU customers: ```bash theme={null} npx novu@latest sync \ --bridge-url \ --secret-key \ --api-url https://eu.api.novu.co ``` ### What does sync push? * Workflow registrations (id, name, description, tags, preferences) * Step definitions (id, type, control schemas, default values) * Payload schemas The bridge URL is **stored** so Novu Cloud knows where to fetch step content at trigger time. ### Sync via Vercel Preview Free-tier preview URLs are deployment-protected by default. Enable [Protection Bypass for Automation](https://vercel.com/docs/security/deployment-protection/methods-to-bypass-deployment-protection) in your Vercel project settings, then pass the bypass token in the bridge URL: ```bash theme={null} npx novu@latest sync \ --bridge-url "https://my-app-preview.vercel.app/api/novu?x-vercel-protection-bypass=$BYPASS_TOKEN" \ --secret-key $NOVU_SECRET_KEY ``` ## GitHub Actions Use the [`novuhq/actions-novu-sync@v2`](https://github.com/novuhq/actions-novu-sync) action. ### Production sync on `main` ```yaml theme={null} name: Sync workflows to Novu Production on: push: branches: [main] workflow_dispatch: jobs: deploy: runs-on: ubuntu-latest steps: - name: Sync state to Novu uses: novuhq/actions-novu-sync@v2 with: secret-key: ${{ secrets.NOVU_SECRET_KEY }} bridge-url: ${{ secrets.NOVU_BRIDGE_URL }} api-url: https://api.novu.co ``` ### Development sync on PR ```yaml theme={null} name: Sync workflows to Novu Development on: pull_request: branches: [main] jobs: deploy-dev: runs-on: ubuntu-latest steps: - name: Sync state to Novu (Dev) uses: novuhq/actions-novu-sync@v2 with: secret-key: ${{ secrets.NOVU_DEV_SECRET_KEY }} bridge-url: ${{ secrets.NOVU_DEV_BRIDGE_URL }} api-url: https://api.novu.co ``` ### Inputs | Input | Required | Default | Description | | - | - | - | - | | `secret-key` | Yes | — | `NOVU_SECRET_KEY` for the target environment | | `bridge-url` | Yes | — | Public URL of the deployed bridge (`https://app.com/api/novu`) | | `api-url` | No | `https://api.novu.co` | Use `https://eu.api.novu.co` for EU | ## Other CI/CD All other CI tools can use the CLI directly. Examples: ### GitLab CI ```yaml theme={null} sync_novu: image: node:20 script: - npx novu@latest sync --bridge-url $NOVU_BRIDGE_URL --secret-key $NOVU_SECRET_KEY only: - main ``` ### CircleCI ```yaml theme={null} version: 2.1 jobs: sync-novu: docker: - image: cimg/node:20.11 steps: - run: npx novu@latest sync --bridge-url $NOVU_BRIDGE_URL --secret-key $NOVU_SECRET_KEY workflows: deploy: jobs: - sync-novu: filters: branches: only: main ``` ### Jenkins ```groovy theme={null} pipeline { agent any stages { stage('Sync Novu') { when { branch 'main' } steps { sh 'npx novu@latest sync --bridge-url $NOVU_BRIDGE_URL --secret-key $NOVU_SECRET_KEY' } } } } ``` ### Bitbucket Pipelines ```yaml theme={null} pipelines: branches: main: - step: image: node:20 script: - npx novu@latest sync --bridge-url $NOVU_BRIDGE_URL --secret-key $NOVU_SECRET_KEY ``` ### Azure DevOps ```yaml theme={null} trigger: - main pool: vmImage: ubuntu-latest steps: - task: NodeTool@0 inputs: versionSpec: "20.x" - script: npx novu@latest sync --bridge-url $(NOVU_BRIDGE_URL) --secret-key $(NOVU_SECRET_KEY) displayName: "Sync Novu" ``` ### Travis CI ```yaml theme={null} language: node_js node_js: - "20" deploy: provider: script script: npx novu@latest sync --bridge-url $NOVU_BRIDGE_URL --secret-key $NOVU_SECRET_KEY on: branch: main ``` ## Recommended Pipeline Structure ``` ┌──────────────────────────────────────────────────────────────────┐ │ PR opened / updated │ │ 1. Build & test app │ │ 2. Deploy preview to Vercel/Render │ │ 3. `npx novu sync --bridge-url --secret-key DEV` │ │ 4. Run e2e tests against Dev environment │ └──────────────────────────────────────────────────────────────────┘ │ ▼ ┌──────────────────────────────────────────────────────────────────┐ │ PR merged to main │ │ 1. Deploy app to production │ │ 2. `npx novu sync --bridge-url --secret-key PROD` │ └──────────────────────────────────────────────────────────────────┘ ``` ## Common Issues ### "Failed to reach bridge URL" * The bridge URL must be publicly accessible over HTTPS. * Auth middleware on `/api/novu` will block Novu — exempt that path. * Vercel preview URLs require Protection Bypass — see above. ### "Invalid secret key" You're syncing with the wrong environment's key. Each Novu environment has its own key — don't mix Dev and Prod. ### Workflows don't appear in Dashboard after sync * Check the sync command exited 0 — failures may be silent in some CI environments. * Make sure your bridge actually returns the workflow on `GET /api/novu` — Novu fetches the registration list from there. * If you renamed a workflow, the old `workflowId` is **not** auto-deleted. Delete it manually in the Dashboard if needed. ### Sync succeeded but triggers fail * The bridge URL stored in Novu Cloud is wrong — re-sync with the correct URL. * Production env vars are missing on your deployed app — `NOVU_SECRET_KEY` is required even for the bridge. # Email templates Source: https://docs.novu.co/.mintlify/skills/framework-integration/references/email-templates # Email Templates `@novu/framework` lets you render emails with libraries you already know — React Email, Vue Email, Svelte Email — by returning the rendered HTML string from your `step.email` resolver. ## Why use a component library? * **Reuse design tokens** across product UI and emails * **Type safety** for template props * **Dev-time preview** with React/Vue/Svelte Email's local preview servers * **Avoid HTML email tag soup** — components abstract away `
`-based layouts ## React Email ### Install ```bash theme={null} npm install @react-email/components react-email ``` ### Define a template ```tsx theme={null} // emails/welcome.tsx import { Body, Container, Head, Html, render, } from "@react-email/components"; import * as React from "react"; interface WelcomeEmailProps { name: string; } export const WelcomeEmail = ({ name }: WelcomeEmailProps) => ( Hello {name}, welcome to your first React Email template! ); export default WelcomeEmail; export function renderWelcome(name: string) { return render(); } ``` ### Use in a workflow ```typescript theme={null} import { workflow } from "@novu/framework"; import { z } from "zod"; import { renderWelcome } from "./emails/welcome"; export const welcomeWorkflow = workflow( "welcome", async ({ step, payload }) => { await step.email("send-email", async (controls) => ({ subject: controls.subject, body: renderWelcome(payload.userName), }), { controlSchema: z.object({ subject: z.string().default("Welcome to {{payload.appName}}"), }), }); }, { payloadSchema: z.object({ userName: z.string(), appName: z.string().default("Acme"), }), } ); ``` ### Local preview React Email ships its own preview dev server: ```bash theme={null} npx react-email dev ``` This is **independent** of the Novu Studio — useful for designing your templates before wiring them into a workflow. ### Pass controls into the template You can derive template props from controls: ```tsx theme={null} export const NewSignUp = ({ hideBanner, components, }: { hideBanner: boolean; components: { type: string; content: string }[]; }) => ( {!hideBanner && } {components.map((c, i) =>
{c.content}
)} ); ``` ```typescript theme={null} await step.email("send-email", async (controls) => ({ subject: controls.subject, body: render( ), }), { controlSchema: z.object({ hideBanner: z.boolean().default(false), subject: z.string().default("Welcome"), components: z.array( z.object({ type: z.enum(["header", "cta-row", "footer"]), content: z.string(), }) ), }), }); ``` ## Remix + React Email ```bash theme={null} npm install @react-email/components react-email ``` Place templates in `app/emails/`: ```tsx theme={null} // app/emails/sample-email.tsx import { Button, Html, render } from "@react-email/components"; function Email(props: { name: string }) { return ( ); } export function renderEmail(props: { name: string }) { return render(); } ``` ```typescript theme={null} import { renderEmail } from "../emails/sample-email"; import { workflow } from "@novu/framework"; workflow("welcome", async ({ step }) => { await step.email("send-email", async (inputs) => ({ subject: "Welcome to Remix and React Email", body: renderEmail(inputs as { name: string }), })); }); ``` A complete example app: [novuhq/novu-framework-remix-example](https://github.com/novuhq/novu-framework-remix-example). ## Vue Email (Nuxt) ### Install ```bash theme={null} npm install @vue-email/components ``` ### Configure Nuxt ```typescript theme={null} // nuxt.config.ts export default defineNuxtConfig({ build: { transpile: ["@vue/email"] }, nitro: { esbuild: { options: { target: "esnext" } }, }, }); ``` ### Define a template ```vue theme={null} ``` ### Use in a workflow ```typescript theme={null} import { workflow } from "@novu/framework"; import { renderEmail } from "./emails/welcome"; import { z } from "zod"; export const welcomeWorkflow = workflow("welcome", async ({ step, payload }) => { await step.email("send-email", async (controls) => ({ subject: controls.subject, body: renderEmail(payload.userName), }), { controlSchema: z.object({ subject: z.string().default("Welcome from {{payload.userName}}"), }), }); }, { payloadSchema: z.object({ userName: z.string().default("John Doe") }), }); ``` A complete example app: [novuhq/novu-framework-nuxt-example](https://github.com/novuhq/novu-framework-nuxt-example). ## Svelte Email ### Install ```bash theme={null} npm install svelte-email ``` ### Define a template ```svelte theme={null} Welcome to Svelte Email

Welcome, {name}!

Thanks for trying Svelte Email.

``` ```typescript theme={null} // src/emails/welcome.ts import { render } from "svelte-email"; import Welcome from "./welcome.svelte"; export function renderEmail(name: string) { return render({ template: Welcome, props: { name } }); } ``` ### Use in a workflow ```typescript theme={null} import { workflow } from "@novu/framework"; import { renderEmail } from "./emails/welcome"; import { z } from "zod"; export const welcomeWorkflow = workflow("welcome", async ({ step, payload }) => { await step.email("send-email", async (controls) => ({ subject: controls.subject, body: renderEmail(payload.userName), }), { controlSchema: z.object({ subject: z.string().default("Welcome to Acme"), }), }); }, { payloadSchema: z.object({ userName: z.string().default("John Doe") }), }); ``` A complete example app: [novuhq/novu-svelte-email](https://github.com/novuhq/novu-svelte-email). ## Tips * **Co-locate templates with workflows.** Keep `src/novu/workflows/welcome/template.tsx` next to `src/novu/workflows/welcome/index.ts`. * **Render synchronously when possible.** `render()` is sync for React Email (returns a string). Avoid awaiting `render` unless your library requires it. * **Keep template props small and serializable.** Templates are pure components — pass strings/numbers/arrays, not class instances. * **Don't fetch data in the template.** Fetch in `step.custom` or inside the `step.email` resolver, then pass plain props. * **Test in the Studio.** Trigger the workflow with a sample payload — the rendered HTML appears in the Studio preview pane. * **Use the framework-specific dev server** (`npx react-email dev`, etc.) for fast iteration on the design without round-tripping through the Studio. # Examples Source: https://docs.novu.co/.mintlify/skills/framework-integration/references/examples # Examples Cookbook Real-world workflow patterns built with `@novu/framework`. ## Multi-Step Onboarding Send a welcome email immediately, wait a week, then nudge with an in-app reminder if the user opted in. ```typescript theme={null} import { workflow } from "@novu/framework"; import { z } from "zod"; import { renderEmail } from "../emails/welcome"; export const onboardingWorkflow = workflow( "new-signup", async ({ step, payload }) => { await step.email("welcome-email", async () => { const user = await db.getUser(payload.userId); return { subject: `Welcome to Acme ${user.tier}, ${user.name}!`, body: renderEmail({ name: user.name, tier: user.tier }), }; }); await step.delay("wait-1-week", async () => ({ unit: "weeks", amount: 1, })); await step.inApp("nudge", async (controls) => { const user = await db.getUser(payload.userId); return { subject: "How is it going?", body: `Hey ${user.name}, how do you like Acme so far?`, primaryAction: { label: "Give Feedback", redirect: { url: controls.feedbackUrl, target: "_blank" }, }, }; }, { controlSchema: z.object({ feedbackUrl: z.string().url().default("https://acme.com/feedback"), }), skip: () => !payload.shouldFollowUp, }); }, { payloadSchema: z.object({ userId: z.string(), shouldFollowUp: z.boolean().default(true), }), name: "New Signup Onboarding", tags: ["onboarding", "lifecycle"], } ); ``` ## Skip Email if In-App Was Read Send an in-app notification, wait 6 hours, then send an email — but skip the email if the in-app was read. ```typescript theme={null} import { workflow } from "@novu/framework"; import { z } from "zod"; export const reminderWorkflow = workflow( "task-reminder", async ({ step, payload }) => { const inApp = await step.inApp("send-in-app", async () => ({ subject: "Task reminder!", body: "Task is not yet complete. Please complete the task.", data: { taskId: payload.taskId }, })); await step.delay("wait-6h", async () => ({ unit: "hours", amount: 6, })); await step.email("send-email", async () => ({ subject: "Task reminder!", body: "Task is not yet complete. Please complete the task.", }), { skip: () => inApp.read === true, }); }, { payloadSchema: z.object({ taskId: z.string() }), tags: ["reminder"], } ); ``` ## Daily Digest with React Email Aggregate all triggers within 24 hours into a single email. ```typescript theme={null} import { workflow } from "@novu/framework"; import { z } from "zod"; import { render } from "@react-email/components"; import { ActivityDigestEmail } from "../emails/activity-digest"; export const dailyDigestWorkflow = workflow( "activity-digest", async ({ step, payload }) => { const { events } = await step.digest("digest-window", async () => ({ unit: "days", amount: 1, })); await step.email("send-summary", async () => { const activities = events.map((e) => ({ type: e.payload.type, user: e.payload.userName, action: e.payload.action, time: e.time, })); return { subject: `Activity Summary (${events.length} updates)`, body: render(), }; }); }, { payloadSchema: z.object({ type: z.enum(["comment", "like", "follow"]), userName: z.string(), action: z.string(), }), tags: ["digest"], } ); ``` ## Cron-Based Digest Send a single morning digest at 9am UTC every day. ```typescript theme={null} export const morningDigest = workflow( "morning-digest", async ({ step }) => { const { events } = await step.digest("digest", async () => ({ cron: "0 9 * * *", // every day at 09:00 UTC })); if (events.length === 0) return; await step.email("digest", async () => ({ subject: `${events.length} updates from yesterday`, body: render(), })); } ); ``` ## Custom Digest Key (Per-Project) Aggregate events by `subscriberId + projectId` instead of just `subscriberId`. ```typescript theme={null} export const projectDigestWorkflow = workflow( "project-digest", async ({ step, payload }) => { const { events } = await step.digest("digest-step", async () => ({ unit: "hours", amount: 1, digestKey: payload.projectId, })); await step.inApp("notify", async () => ({ subject: `${events.length} updates in ${payload.projectName}`, body: events.map((e) => e.payload.title).join(", "), })); }, { payloadSchema: z.object({ projectId: z.string(), projectName: z.string(), title: z.string(), }), } ); ``` ## Two-Stage Digest with LLM Categorization A workflow can trigger another workflow via `step.custom`. Use this to chain digests when you need two windows. ```typescript theme={null} import { categorizeUsingLLM } from "../lib/llm"; const summaryWorkflow = workflow( "llm-summary", async ({ step }) => { const { events } = await step.digest("digest-6h", async () => ({ unit: "hours", amount: 6, })); await step.email("summary", async () => { const allRequests = events.map((e) => e.payload.requests); const { bugs, features, praise } = await categorizeUsingLLM(allRequests); return { subject: "LLM Feedback Digest — Last 6 Hours", body: ` Bugs reported: ${bugs}\n Feature requests: ${features}\n Praise received: ${praise}\n `, }; }); } ); export const requestsWorkflow = workflow( "customer-requests", async ({ step, subscriber, payload }) => { const { events } = await step.digest("digest-15m", async () => ({ unit: "minutes", amount: 15, })); await step.inApp("in-app-summary", async () => ({ subject: `${events.length} new requests`, body: `You've received ${events.length} customer requests in the last 15 minutes.`, })); await step.custom("trigger-llm-summary", async () => { return await summaryWorkflow.trigger({ to: subscriber.subscriberId, payload: { requests: events.map((e) => e.payload), }, }); }); } ); ``` ## Skip Delay for Premium Users Premium users get the email immediately; free users wait 24h. ```typescript theme={null} export const upsellWorkflow = workflow( "upsell", async ({ step, subscriber }) => { await step.delay("wait", async () => ({ unit: "hours", amount: 24 }), { skip: async () => subscriber.data?.tier === "premium", }); await step.email("upsell", async () => ({ subject: "Upgrade to unlock more features", body: "Try Premium free for 14 days.", })); } ); ``` ## Branch on Custom Step Result Fetch a task from the database, then conditionally email a reminder. ```typescript theme={null} import { db } from "../lib/db"; export const taskReminderWorkflow = workflow( "task-reminder", async ({ step, payload }) => { const task = await step.custom("fetch-task", async () => { const t = await db.fetchTask(payload.taskId); return { id: t.id, title: t.title, complete: t.complete }; }, { outputSchema: { type: "object", properties: { id: { type: "string" }, title: { type: "string" }, complete: { type: "boolean" }, }, required: ["id", "complete"], } as const, }); await step.email("reminder", async () => ({ subject: `Reminder: ${task.title}`, body: "This task is still open.", }), { skip: () => task.complete, }); }, { payloadSchema: z.object({ taskId: z.string() }), } ); ``` ## Slack Provider Override (Block Kit) Use the `chat` step but customize the Slack message with Block Kit. ```typescript theme={null} export const deployAlertWorkflow = workflow( "deploy-alert", async ({ step, payload }) => { await step.chat("slack", async () => ({ body: `Deploy ${payload.deployId} succeeded`, }), { providers: { slack: ({ controls, outputs }) => ({ text: outputs.body, blocks: [ { type: "section", text: { type: "mrkdwn", text: `:white_check_mark: *Deploy ${payload.deployId} succeeded*` }, }, { type: "context", elements: [ { type: "mrkdwn", text: `Branch: \`${payload.branch}\` • Author: ${payload.author}` }, ], }, { type: "actions", elements: [ { type: "button", text: { type: "plain_text", text: "View Build" }, url: payload.buildUrl, }, ], }, ], }), }, }); }, { payloadSchema: z.object({ deployId: z.string(), branch: z.string(), author: z.string(), buildUrl: z.string().url(), }), tags: ["deploys"], } ); ``` ## SendGrid CC + Provider Passthrough ```typescript theme={null} export const alertWorkflow = workflow( "alert", async ({ step, payload }) => { await step.email("alert", async () => ({ subject: `[ALERT] ${payload.title}`, body: payload.message, }), { providers: { sendgrid: () => ({ from: "alerts@acme.com", cc: ["ops@acme.com", "oncall@acme.com"], replyTo: "support@acme.com", _passthrough: { body: { ip_pool_name: "transactional" }, headers: { "X-Priority": "1" }, }, }), }, }); }, { payloadSchema: z.object({ title: z.string(), message: z.string(), }), tags: ["ops", "alerts"], } ); ``` ## Critical Workflow (Subscribers Cannot Disable) ```typescript theme={null} export const securityAlert = workflow( "security-alert", async ({ step }) => { await step.email("notify", async () => ({ subject: "New login from unrecognized device", body: "If this wasn't you, change your password immediately.", })); }, { preferences: { all: { enabled: true, readOnly: true }, // critical — subscribers cannot opt out }, tags: ["security"], } ); ``` ## In-App Only by Default In-app is on; subscribers can opt into other channels via Preferences UI. ```typescript theme={null} export const newsletter = workflow( "weekly-newsletter", async ({ step }) => { await step.inApp("in-app", async () => ({ subject: "Weekly digest", body: "Read this week's highlights", })); await step.email("email", async () => ({ subject: "Weekly digest", body: render(), })); }, { preferences: { all: { enabled: false }, channels: { inApp: { enabled: true } }, }, tags: ["marketing"], } ); ``` ## Locale-Aware Workflow with i18next See [translations.md](./translations.md) for the full i18next setup. ```typescript theme={null} import i18n from "../translations"; export const localizedWelcome = workflow( "welcome-localized", async ({ step, subscriber }) => { await step.email("send", async (controls) => { const t = i18n.getFixedT([subscriber?.locale ?? controls.defaultLocale]); return { subject: t("welcomeSubject", { name: subscriber.firstName }), body: render(), }; }, { controlSchema: z.object({ defaultLocale: z.string().default("en_US") }), }); } ); ``` # Schema validation Source: https://docs.novu.co/.mintlify/skills/framework-integration/references/schema-validation # Schema Validation `@novu/framework` accepts three kinds of schemas for both `payloadSchema` (workflow level) and `controlSchema` (step level): | Schema | Best for | Type inference | | - | - | - | | **Zod** | TypeScript-first projects | Best — automatic via `z.infer` | | **JSON Schema** | OpenAPI-style projects, advanced features (`oneOf`, `if/then/else`, `$ref`) | Good — requires `as const` | | **Class Validator** | OOP-style apps, NestJS DTOs | Requires `class-validator-jsonschema` and `reflect-metadata` | All three are converted to JSON Schema under the hood and pushed to Novu Cloud — so the Dashboard always renders the same UI. ## Zod (Recommended) Novu supports **Zod v3**. ### Install ```bash theme={null} npm install zod ``` ### Workflow Payload ```typescript theme={null} import { workflow } from "@novu/framework"; import { z } from "zod"; export const commentWorkflow = workflow( "comment-on-post", async ({ step, payload }) => { await step.email("send-email", async () => ({ subject: `New comment from ${payload.authorName}`, body: payload.comment, })); }, { payloadSchema: z.object({ postId: z.number(), authorName: z.string(), comment: z.string().max(200), }), } ); ``` ### Step Controls ```typescript theme={null} await step.email("send-email", async (controls) => ({ subject: controls.subject, body: render(), }), { controlSchema: z.object({ hideBanner: z.boolean().default(false), subject: z.string().default("Hi {{subscriber.firstName | capitalize}}"), components: z.array( z.object({ type: z.enum(["header", "cta-row", "footer"]), content: z.string(), }) ), }), }); ``` ### What gets rendered in the Dashboard | Zod feature | Dashboard input | | - | - | | `z.string()` | Text input | | `z.string().email()` | Email input with validation | | `z.string().url()` | URL input | | `z.string().regex(...)` | Text input with pattern validation | | `z.string().min/.max` | Length-validated input | | `z.number()` | Number input | | `z.boolean()` | Toggle | | `z.enum([...])` | Dropdown | | `z.array(...)` | Repeatable section | | `.default(value)` | Pre-filled value | > Zod doesn't support custom `title` on fields — the Dashboard label is derived from the property name. ## JSON Schema Use JSON Schema when you need features Zod doesn't expose: `oneOf`, `if/then/else`, `$ref`, `enumNames`, etc. ### Workflow Payload ```typescript theme={null} workflow("comment", handler, { payloadSchema: { type: "object", properties: { postId: { type: "number" }, authorName: { type: "string" }, comment: { type: "string", maxLength: 200 }, }, required: ["postId", "comment"], additionalProperties: false, } as const, // CRITICAL: required for TS inference }); ``` > Without `as const`, TypeScript infers `string` for `type` instead of the literal `"object"`, and you lose type inference on `payload`. ### Examples #### Simple object ```json theme={null} { "type": "object", "required": ["firstName", "lastName"], "properties": { "firstName": { "type": "string", "title": "First name", "default": "Chuck" }, "lastName": { "type": "string", "title": "Last name" }, "age": { "type": "integer", "title": "Age" } } } ``` #### Nested array ```json theme={null} { "type": "object", "properties": { "tasks": { "type": "array", "items": { "type": "object", "properties": { "title": { "type": "string" }, "done": { "type": "boolean", "default": false } } } } } } ``` #### `$ref` reuse ```json theme={null} { "definitions": { "address": { "type": "object", "properties": { "street": { "type": "string" }, "city": { "type": "string" } } } }, "type": "object", "properties": { "billing": { "$ref": "#/definitions/address" }, "shipping": { "$ref": "#/definitions/address" } } } ``` #### `oneOf` discriminated union ```json theme={null} { "type": "object", "oneOf": [ { "properties": { "lorem": { "type": "string" } }, "required": ["lorem"] }, { "properties": { "ipsum": { "type": "string" } }, "required": ["ipsum"] } ] } ``` #### `if/then/else` ```json theme={null} { "type": "object", "properties": { "animal": { "enum": ["Cat", "Fish"] } }, "allOf": [ { "if": { "properties": { "animal": { "const": "Cat" } } }, "then": { "properties": { "food": { "enum": ["meat", "grass", "fish"] } }, "required": ["food"] } }, { "if": { "properties": { "animal": { "const": "Fish" } } }, "then": { "properties": { "food": { "enum": ["insect", "worms"] }, "water": { "enum": ["lake", "sea"] } }, "required": ["food", "water"] } } ] } ``` #### Regex validation ```json theme={null} { "type": "object", "properties": { "phone": { "type": "string", "pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$" } } } ``` ## Class Validator For OOP-style projects (especially NestJS DTOs). ### Install ```bash theme={null} npm install class-validator class-validator-jsonschema reflect-metadata ``` > `class-validator-jsonschema` is required to convert decorators to JSON Schema. > `reflect-metadata` must be imported once at app entry (`import "reflect-metadata"`). ### Define DTOs ```typescript theme={null} import { workflow } from "@novu/framework"; import { IsString, IsBoolean, IsNotEmpty, IsOptional, ValidateNested, } from "class-validator"; import { Type } from "class-transformer"; class WelcomeComponent { @IsString() subject!: string; @IsString() content!: string; } class WelcomeControlSchema { @IsBoolean() hideBanner!: boolean; @IsString() @IsNotEmpty() @IsOptional() subject?: string; @Type(() => WelcomeComponent) @ValidateNested({ each: true }) @IsOptional() components?: WelcomeComponent[]; } class WelcomePayloadSchema { @IsString() username!: string; } export const welcomeWorkflow = workflow( "welcome", async ({ step, payload }) => { await step.email("send-email", async (controls) => ({ subject: controls.subject ?? `Welcome ${payload.username}`, body: "Hello!", }), { controlSchema: WelcomeControlSchema }); }, { payloadSchema: WelcomePayloadSchema } ); ``` ### Caveats * Class Validator does **not** support default values out of the box — set them in your resolver. * Class Validator does **not** support custom titles — Dashboard labels come from the property name. * Nested schemas can have inconsistencies — see [`class-validator-jsonschema`](https://www.npmjs.com/package/class-validator-jsonschema) docs. ## Choosing a Schema | You want… | Use | | - | - | | Best DX, type inference, Vercel-style validation | **Zod** | | Already use NestJS / DTOs | **Class Validator** | | Need `oneOf`, `$ref`, `if/then/else`, share schemas with API consumers | **JSON Schema** | | Want only IDE intellisense (no Dashboard schema) | Plain TS interfaces — but you lose Dashboard form generation | ## Other Resources * [JSON Schema specification](https://json-schema.org/specification) * [JSON Schema validator playground](https://www.jsonschemavalidator.net/) * [React JSON Schema Form](https://rjsf-team.github.io/react-jsonschema-form/) — same UI engine Novu uses for the Dashboard * [Zod docs](https://zod.dev/) * [class-validator docs](https://github.com/typestack/class-validator) # Security Source: https://docs.novu.co/.mintlify/skills/framework-integration/references/security # Production & Security The Bridge Endpoint is a public HTTP route, so Novu Framework includes builtin protections to ensure only Novu Cloud can invoke it. ## HMAC Authentication Each request from Novu Cloud to your Bridge includes a `Novu-Signature` header containing a timestamp and a signature. The Framework's `serve` wrapper verifies the signature against `NOVU_SECRET_KEY` before invoking your workflow handler. ### Header format ``` Novu-Signature: t=,v1= ``` * `t=` — when the request was signed * `v1=` — current valid signature scheme (more may come; always begin with `v`) ### When is HMAC enforced? | `NODE_ENV` | HMAC verification | | - | - | | `development` | **Disabled** — required for the Studio to reach your local bridge | | anything else (incl. `production`, `staging`, undefined) | **Enabled** | You don't write any verification code — `serve()` handles it. ### Override behavior ```typescript theme={null} import { Client as NovuFrameworkClient } from "@novu/framework"; import { serve } from "@novu/framework/next"; export const { GET, POST, OPTIONS } = serve({ client: new NovuFrameworkClient({ secretKey: process.env.NOVU_SECRET_KEY, strictAuthentication: false, // Disables HMAC — DEV ONLY }), workflows: [/* … */], }); ``` > **Never disable `strictAuthentication` in production.** Without HMAC, anyone who can reach your bridge URL can trigger arbitrary step resolution and exfiltrate subscriber/payload data. ## Network Requirements * **Public HTTPS** — your bridge must be reachable from the public internet. * **No IP allowlist published** — Novu Cloud workers autoscale; we don't expose stable IPs. * **No auth middleware on `/api/novu`** — Novu authenticates with HMAC, not with your app's JWT/session. If you need to harden the perimeter: * Place a WAF in front, but **allow** traffic to `/api/novu` (or whatever path you mounted). * Use rate limiting per HMAC header (each request includes a recent timestamp). * Log and alert on signature failures — they may indicate a misconfigured bridge URL or a hostile actor. ## Compliance Novu Cloud workers are: * **GDPR** compliant * **SOC 2 Type II** certified * **ISO 27001** certified Bridge requests carry only the data necessary to resolve a step: subscriber id (and any subscriber attributes you reference), payload (which you defined the schema for), and step controls. No additional telemetry is exfiltrated. ## Environment Variables The Framework reads these env vars by default (you can override with the `Client` class): | Variable | Default | Purpose | | - | - | - | | `NOVU_SECRET_KEY` | — | HMAC signing key; verifies request authenticity | | `NOVU_API_URL` | `https://api.novu.co` | Cloud API URL — set to `https://eu.api.novu.co` for EU | | `NODE_ENV` | — | If `development`, HMAC is disabled | ### EU Region Setup ```typescript theme={null} import { Client as NovuFrameworkClient } from "@novu/framework"; import { serve } from "@novu/framework/next"; export const { GET, POST, OPTIONS } = serve({ client: new NovuFrameworkClient({ secretKey: process.env.NOVU_SECRET_KEY, }), workflows: [/* … */], }); ``` ```bash theme={null} NOVU_API_URL=https://eu.api.novu.co NOVU_SECRET_KEY= ``` ## Best Practices 1. **Keep `NOVU_SECRET_KEY` server-only** — never commit it, never expose to the client. Use your platform's secrets manager (Vercel Env Vars, AWS Secrets Manager, GitHub Encrypted Secrets). 2. **Rotate the secret key periodically** — go to `dashboard.novu.co/api-keys`, create a new key, deploy it, then revoke the old one. 3. **Use separate keys per environment** — Dev and Prod must have different `NOVU_SECRET_KEY` values. 4. **Audit logs** — log every Bridge request server-side with subscriber id and workflow id so you can trace any anomaly. 5. **Set request timeout** — keep your `step.custom` operations under 30s. Longer operations should be enqueued (BullMQ, SQS) and resolved in a separate workflow. 6. **Don't return secrets in step output** — anything in `subject`/`body`/`data` is delivered to the user. 7. **Use HMAC for the Inbox too** — see [`inbox-integration` HMAC section](../../inbox-integration/SKILL.md#hmac-authentication). ## HMAC for the Inbox vs HMAC for the Bridge These are separate but related: | | Bridge HMAC | Inbox HMAC | | - | - | - | | Direction | Cloud → Bridge | Inbox SDK → Cloud | | Purpose | Authenticate Novu's call to your server | Authenticate the subscriber's session | | Header / Param | `Novu-Signature` (auto by `serve`) | `subscriberHash` prop on `` | | Computed how | Cloud signs with `NOVU_SECRET_KEY` | You compute `HMAC-SHA256(secretKey, subscriberId)` server-side | Both use the same `NOVU_SECRET_KEY`. See [`inbox-integration` references](../../inbox-integration/references/security.md) for the Inbox HMAC details. ## Vercel Preview URLs Vercel free-tier preview deployments are protected by default. Two ways to make the bridge reachable: ### 1. Bypass token (for sync only) Enable [Protection Bypass for Automation](https://vercel.com/docs/security/deployment-protection/methods-to-bypass-deployment-protection/protection-bypass-automation): ```bash theme={null} npx novu@latest sync \ --bridge-url "https://my-app-preview.vercel.app/api/novu?x-vercel-protection-bypass=$BYPASS" \ --secret-key $NOVU_SECRET_KEY ``` ### 2. Disable protection on the preview branch (for runtime triggers) Vercel Pro/Enterprise lets you disable Deployment Protection on a per-branch basis. Useful if you trigger workflows during preview integration tests. # Studio and cli Source: https://docs.novu.co/.mintlify/skills/framework-integration/references/studio-and-cli # Local Studio & Novu CLI The **Local Studio** is a companion app to `@novu/framework`. It runs locally, talks to your Bridge Endpoint, and gives you a live preview of every workflow you've registered — including step controls, payload, and rendered output. ## Prerequisites * Your bridge app running (e.g. `npm run dev` for Next.js, exposing `/api/novu`) * `NOVU_SECRET_KEY` exported (from `.env`) * **Chrome only** — the Studio currently doesn't support other browsers ## Launch ```bash theme={null} npx novu@latest dev ``` Defaults: * Bridge port: `4000` * Bridge route: `/api/novu` * Studio UI: `http://localhost:2022` The CLI: 1. Pings your bridge at `http://localhost:4000/api/novu` to discover workflows. 2. Spins up a public tunnel (`https://.novu.sh/api/novu`) so Novu Cloud can reach your machine. 3. Launches the Studio UI in Chrome. ## CLI Flags | Flag | Long form | Default | Purpose | | - | - | - | - | | `-p` | `--port ` | `4000` | Your app's port | | `-r` | `--route ` | `/api/novu` | Bridge route path | | `-o` | `--origin ` | `http://localhost` | Bridge origin | | `-d` | `--dashboard-url ` | `https://dashboard.novu.co` | Dashboard URL — use `https://eu.dashboard.novu.co` for EU | | `-sp` | `--studio-port ` | `2022` | Studio UI port | | `-t` | `--tunnel ` | auto | Self-hosted tunnel (e.g. ngrok) | | `-H` | `--headless` | `false` | Skip the Studio UI (just keep the tunnel alive) | ### Examples #### Bridge running on a non-default port ```bash theme={null} npx novu@latest dev --port 3002 ``` #### EU region ```bash theme={null} npx novu@latest dev --port 3002 --dashboard-url https://eu.dashboard.novu.co ``` #### Custom bridge path ```bash theme={null} npx novu@latest dev --route /internal/notify ``` #### Self-hosted tunnel (ngrok / Cloudflare Tunnel) ```bash theme={null} npx novu@latest dev --tunnel https://my-tunnel.ngrok.app ``` > When using a self-hosted tunnel, **the Studio cannot trigger test events** because it relies on the auto-generated tunnel for callback. Use the Cloud Dashboard to trigger instead. #### Headless mode Useful in CI or for keeping the tunnel alive without the UI: ```bash theme={null} npx novu@latest dev --headless ``` ## What you can do in the Studio * **Browse workflows** registered by your bridge — code-defined and Dashboard-defined alike * **Edit Step Controls** in real time and preview the resolved output * **Edit the Payload** to test edge cases without rebuilding your trigger code * **Trigger test events** to a subscriber of your choice * **Sync state** to your Cloud environment from a single button (use CI/CD for production) * **See errors** from your workflow handler with full stack traces ## Tunnel URL vs Bridge URL | | Created by | URL pattern | Use for | | - | - | - | - | | **Tunnel URL** | `npx novu@latest dev` | `https://.novu.sh/api/novu` | Local dev — Studio + Cloud testing | | **Bridge URL** | Your deployed app | `https://api.acme.com/api/novu` | Production sync | Tunnel IDs are persisted to your machine, so the same URL is reused across `dev` runs. ## `npx novu sync` Push workflows defined in code to Novu Cloud. ```bash theme={null} npx novu@latest sync \ --bridge-url \ --secret-key \ --api-url https://api.novu.co ``` | Flag | Purpose | | - | - | | `--bridge-url` | Public URL to your deployed bridge (`https://app.com/api/novu`) | | `--secret-key` | `NOVU_SECRET_KEY` for the target environment | | `--api-url` | `https://api.novu.co` (default) or `https://eu.api.novu.co` for EU | > Each environment (Development, Production) has its own secret key. Sync once per environment with the matching key. ### Sync from a Vercel Preview URL Vercel free-tier previews are protected. Enable [Protection Bypass for Automation](https://vercel.com/docs/security/deployment-protection/methods-to-bypass-deployment-protection) and append the bypass token: ```bash theme={null} npx novu@latest sync \ --bridge-url "https://my-app-preview.vercel.app/api/novu?x-vercel-protection-bypass=$BYPASS_TOKEN" \ --secret-key $NOVU_SECRET_KEY ``` ## `npx novu init` Bootstrap a complete bridge app with a sample workflow. Designed for first-run users. ```bash theme={null} npx novu init --secret-key= ``` Created files: * A working `/api/novu` route (Next.js) * `.env` with `NOVU_SECRET_KEY` * A sample `welcome-email` workflow demonstrating Step Controls + React Email ## FAQ ### Can I run the Studio without a tunnel? Yes — pass `-t/--tunnel` with your own URL. The preview will work, but you can't trigger test events from the Studio UI. ```bash theme={null} npx novu@latest dev -t https://my-tunnel.example.com ``` ### Why does the Studio say it can't reach my bridge? Common causes: * App isn't running on the port the Studio is checking — add `--port ` * Bridge route is mounted at a different path — add `--route /custom/path` * Bridge requires auth middleware that blocks Novu — disable JWT for the bridge route ### Why do I see HMAC errors in the Studio? `NODE_ENV` isn't `development`. Either: * Set `NODE_ENV=development` for the local bridge process, or * Pass `strictAuthentication: false` to a custom `Client` in your `serve` setup ### Can I run multiple bridges simultaneously? Yes — start each bridge on its own port and run a Studio per bridge with `--studio-port`. Each gets its own tunnel. ### Studio works but Cloud can't reach my bridge in production * Verify the bridge URL is publicly accessible over HTTPS * Check firewall / WAF rules — Novu workers come from autoscaled IPs, no allowlist * Make sure `NOVU_SECRET_KEY` is set in your production env vars * Ensure no auth middleware is blocking `/api/novu` # Translations Source: https://docs.novu.co/.mintlify/skills/framework-integration/references/translations # Translations (i18n) `@novu/framework` workflows are code-first — content is rendered inside your bridge during workflow execution. That means **i18n lives in your application layer**: define translation keys in code (e.g. with [i18next](https://www.i18next.com/)) and resolve them inside step resolvers using `subscriber.locale`. > The Novu **Translation** system on the Dashboard is intended for **Dashboard-defined** workflows. Framework workflows use your own i18n stack instead. ## Setup with i18next ### Install ```bash theme={null} npm install i18next ``` ### Define translations ```typescript theme={null} // src/novu/translations.ts import { createInstance, InitOptions } from "i18next"; const i18nOptions: InitOptions = { resources: { en_US: { translation: { welcomeEmailSubject: "Welcome to Twitch, {{username}}!", welcomeEmailIntroduction: "We're glad you could join us. Twitch has a huge, passionate community ready to watch and celebrate all the things you're into, and we've saved a seat just for you.", linkText: "WATCH NOW", welcomeEmailConclusion: "If you want to watch it, someone on Twitch streams it: games, anime, fitness, cosplay, esports, cooking, music, meditation. Take a look around, find a few channels to call home, and cozy up in chat.", }, }, de_DE: { translation: { welcomeEmailSubject: "Willkommen bei Twitch, {{username}}!", welcomeEmailIntroduction: "Wir freuen uns, dass Sie sich uns anschließen konnten. Twitch hat eine riesige, leidenschaftliche Community, die bereit ist, alles zu sehen und zu feiern, was Sie interessiert.", linkText: "JETZT ANSEHEN", welcomeEmailConclusion: "Wenn Sie es ansehen möchten, streamt es jemand auf Twitch.", }, }, }, }; const i18n = createInstance(i18nOptions); i18n.init(i18nOptions); export default i18n; ``` ## Use in a workflow ```typescript theme={null} import { workflow } from "@novu/framework"; import { z } from "zod"; import i18n from "./translations"; import { renderEmail } from "./emails/welcome"; export const localizedWorkflow = workflow( "welcome-localized", async ({ step, subscriber }) => { await step.email("email-step", async (controls) => { const t = i18n.getFixedT([ subscriber?.locale || (controls.defaultLocale as string), ]); const subject = t("welcomeEmailSubject", { username: subscriber?.firstName || "Novu", }); return { subject, body: await renderEmail( subject, t("welcomeEmailIntroduction"), t("linkText"), t("welcomeEmailConclusion") ), }; }, { controlSchema: z.object({ defaultLocale: z.string().default("en_US").optional(), }), }); } ); ``` ### How `subscriber.locale` is set `locale` comes from the subscriber record: ```typescript theme={null} await novu.subscribers.create({ subscriberId: "user-123", email: "jane@acme.com", locale: "de_DE", // ISO BCP 47 with underscore convention }); ``` You can also pass it inline at trigger time: ```typescript theme={null} await novu.trigger({ workflowId: "welcome-localized", to: { subscriberId: "user-123", locale: "de_DE" }, payload: {}, }); ``` If `locale` is missing, the resolver falls back to the `defaultLocale` control. ## Email Template Example ```tsx theme={null} // src/novu/emails/welcome.tsx import { Body, Container, Head, Html, Preview, Section, Text, Link, Img, Row, Column, render, } from "@react-email/components"; import * as React from "react"; const baseUrl = process.env.IMAGE_BASE_URL; export const TwitchWelcomeEmail = ({ subject, body, linkText, body2, }: { subject: string; body: string; linkText: string; body2: string; }) => ( {subject}
{body}
{linkText}
{body2}
); const main = { backgroundColor: "#efeef1", fontFamily: "Helvetica, Arial, sans-serif" }; const paragraph = { lineHeight: 1.5, fontSize: 14 }; const container = { maxWidth: 580, margin: "30px auto", backgroundColor: "#ffffff" }; const content = { padding: "5px 20px 10px 20px" }; const logo = { display: "flex", justifyContent: "center", padding: 30 }; const center = { display: "flex", justifyContent: "center" }; const link: React.CSSProperties = { background: "#9147ff", color: "#fff", borderRadius: 3, display: "inline-block", fontSize: 18, padding: "10px 30px", textDecoration: "none", }; export async function renderEmail( subject: string, body: string, linkText: string, body2: string ) { return render( ); } ``` ## Mount in your bridge ```typescript theme={null} // app/api/novu/route.ts import { serve } from "@novu/framework/next"; import { localizedWorkflow } from "@/novu/workflows/welcome-localized"; export const { GET, POST, OPTIONS } = serve({ workflows: [localizedWorkflow], }); ``` ## Testing 1. Sync the workflow: `npx novu@latest sync --bridge-url ... --secret-key ...` 2. Create or update subscribers with different locales: ```typescript theme={null} await novu.subscribers.patch({ locale: "de_DE" }, "user-123"); ``` 3. Trigger: ```typescript theme={null} await novu.trigger({ workflowId: "welcome-localized", to: "user-123", payload: {}, }); ``` The user should receive their email in `de_DE`. ## Tips * Use **ISO 639-1 + ISO 3166-1** with underscore convention (`en_US`, `de_DE`, `pt_BR`). * **Hard-fail on missing keys in development** by setting i18next's `saveMissing` and `missingKeyHandler` — this catches gaps in translations before deploy. * For **digest emails**, build a localized React component that takes a translation function as a prop and walks events. * Keep translation files **separate from workflow code** so your translation team can edit JSON without touching TypeScript. * Use **i18next-http-backend** + your CMS if translations should be edited by non-engineers without a code deploy. ## Alternatives i18next is just one option — any i18n library works: * [`react-i18next`](https://react.i18next.com/) (React Email components support hooks via i18next provider patterns) * [`next-intl`](https://next-intl-docs.vercel.app/) (server-side resolution works fine inside the bridge) * [`@formatjs/intl`](https://formatjs.io/) for ICU MessageFormat support * A simple `Record>` lookup if you only need a few strings # Workflow and steps Source: https://docs.novu.co/.mintlify/skills/framework-integration/references/workflow-and-steps # Workflow & Step API Reference Full reference for the `workflow()` and `step.*` APIs in `@novu/framework`. ## `workflow(id, handler, options?)` ```typescript theme={null} import { workflow } from "@novu/framework"; workflow(workflowId, handler, options); ``` ### `workflowId: string` Unique identifier within your environment. Used as the trigger key in `novu.trigger({ workflowId })`. Convention: kebab-case (`weekly-digest`, `password-reset`). ### `handler: ({ step, payload, subscriber }) => Promise` The body of the workflow. Receives: | Field | Type | Description | | - | - | - | | `step` | `StepBuilder` | All step methods (`step.email`, `step.delay`, etc.) | | `payload` | `InferredFromSchema` | Validated trigger payload | | `subscriber` | `Subscriber` | Recipient — `{ subscriberId, firstName?, lastName?, email?, phone?, locale?, timezone?, data?, ... }` | ### `options: WorkflowOptions` | Option | Type | Description | | - | - | - | | `payloadSchema` | `ZodSchema \| JsonSchema \| ClassValidatorClass` | Validates trigger payload, infers `payload` type | | `name` | `string` | Display name in Dashboard / Inbox (defaults to `workflowId`) | | `description` | `string` | Description shown in Dashboard | | `tags` | `string[]` | Filter / Inbox tab grouping | | `severity` | `'low' \| 'medium' \| 'high'` | Visual prioritization in the Inbox. Default unset. See [`inbox-integration/SKILL.md`](../../inbox-integration/SKILL.md#severity-styling). | | `critical` | `boolean` | If `true`, the workflow **bypasses subscriber preferences**, **skips digest**, and runs **without delays**. Reserve for must-deliver events (account suspended, security alert, password reset). | | `preferences` | `WorkflowPreferences` | Default channel preferences and `readOnly` flag | ### `severity` vs `critical` vs `readOnly` Three distinct dials — pick deliberately. See [`design-workflow/references/severity-and-critical.md`](../../design-workflow/references/severity-and-critical.md) for the full matrix. | Dial | What it does | | - | - | | `severity` | Pure visual prioritization in the Inbox. Does NOT change preferences, digest, or delivery. | | `critical: true` | Runtime override: bypasses preferences, skips digest, no delays. Forces delivery. | | `preferences.all.readOnly: true` | Hides the workflow from the **Preferences UI**. Subscribers can't toggle channels for it. | `critical: true` is a stronger guarantee than `readOnly: true`. Use `critical` when you need to **force delivery**; use `readOnly` only when you want to **hide the toggle**. ### Workflow Preferences ```typescript theme={null} preferences: { all: { enabled: true, readOnly: false }, channels: { email: { enabled: true }, sms: { enabled: false }, push: { enabled: true }, chat: { enabled: false }, inApp: { enabled: true }, }, } ``` | Field | Default | Notes | | - | - | - | | `all.enabled` | `true` | Fallback for any channel not specified in `channels` | | `all.readOnly` | `false` | If `true`, subscribers cannot disable channels in Preferences UI; this does **not** make the workflow critical | | `channels..enabled` | `true` | Per-channel default | ## Channel Steps All channel steps share the same shape: ```typescript theme={null} await step.(stepId, resolver, options?); ``` ### `step.email` ```typescript theme={null} await step.email("welcome", async (controls) => ({ subject: "Welcome to Acme", body: "

Hello!

", attachments: [{ filename: "guide.pdf", content: pdfBuffer }], from: "hello@acme.com", replyTo: "support@acme.com", })); ``` Returns: `void`. | Output | Type | Required | | - | - | - | | `subject` | `string` | Yes | | `body` | `string` | Yes | | `attachments` | `Attachment[]` | No | | `from` | `string` | No | | `replyTo` | `string` | No | ### `step.sms` ```typescript theme={null} await step.sms("verification", async () => ({ body: `Your code is ${payload.code}`, })); ``` | Output | Type | Required | | - | - | - | | `body` | `string` | Yes | ### `step.push` ```typescript theme={null} await step.push("new-message", async () => ({ title: "New Message", body: "You received a new message from John", data: { messageId: "123", senderId: "456" }, image: "https://acme.com/notification.png", icon: "https://acme.com/icon.png", })); ``` | Output | Type | Required | | - | - | - | | `title` | `string` | Yes | | `body` | `string` | Yes | | `data` | `Record` | No | | `image` | `string` | No | | `icon` | `string` | No | ### `step.chat` ```typescript theme={null} await step.chat("notify", async () => ({ body: "A new post has been created", })); ``` | Output | Type | Required | | - | - | - | | `body` | `string` | Yes | For Slack `blocks`, Discord embeds, etc., use `providers` overrides — see below. ### `step.inApp` ```typescript theme={null} const { seen, read, lastSeenDate, lastReadDate } = await step.inApp("inbox", async () => ({ subject: "Welcome to Acme!", body: "We are excited to have you on board.", avatar: "https://acme.com/avatar.png", redirect: { url: "/welcome", target: "_self" }, primaryAction: { label: "Get Started", redirect: { url: "/get-started", target: "_self" }, }, secondaryAction: { label: "Learn More", redirect: { url: "/learn-more", target: "_self" }, }, data: { entityType: "user", entityId: payload.userId }, })); ``` | Output | Type | Required | Description | | - | - | - | - | | `body` | `string` | Yes | Main content (HTML allowed if `disableOutputSanitization: true`) | | `subject` | `string` | No | Notification title | | `avatar` | `string` | No | URL — overrides actor avatar | | `redirect` | `{ url, target? }` | No | Click destination (`target` is `_self`/`_blank`/`_parent`/`_top`/`_unfencedTop`, default `_blank`) | | `primaryAction` | `{ label, redirect? }` | No | Accent-colored CTA button | | `secondaryAction` | `{ label, redirect? }` | No | Muted CTA button | | `data` | `Record` | No | Custom metadata (≤ 10 keys; strings ≤ 256 chars) | | Result | Type | Description | | - | - | - | | `seen` | `boolean` | True after the user views the notification in the Inbox | | `read` | `boolean` | True after the user marks it read | | `lastSeenDate` | `Date \| null` | When `seen` flipped to true | | `lastReadDate` | `Date \| null` | When `read` flipped to true | Use the result to drive `skip` on subsequent steps (e.g. don't email if already read). ## Action Steps ### `step.delay` Pause workflow execution. ```typescript theme={null} await step.delay("wait", async () => ({ unit: "days", amount: 1, })); ``` | Output | Type | Required | Notes | | - | - | - | - | | `amount` | `number` | Yes | Number of `unit`s | | `unit` | `'seconds' \| 'minutes' \| 'hours' \| 'days' \| 'weeks' \| 'months'` | Yes | Time unit | Returns: `{ duration: number }` (in milliseconds). If a delay step **fails**, the workflow stops — it does not proceed to the next step. ### `step.digest` Aggregate triggers over a time window or cron schedule. ```typescript theme={null} const { events } = await step.digest("daily", async () => ({ unit: "days", amount: 1, digestKey: payload.projectId, // optional — group by custom key })); ``` | Output | Type | Required | Notes | | - | - | - | - | | `amount` | `number` | One of (`amount`+`unit`) **or** (`cron`) | | | `unit` | `'seconds' \| 'minutes' \| 'hours' \| 'days' \| 'weeks' \| 'months'` | | | | `cron` | `string` | | Cron expression (e.g. `"0 0 * * *"`) | | `digestKey` | `string` | No | Group key in addition to `subscriberId` | | Result | Type | Description | | - | - | - | | `events` | `DigestEvent[]` | Array of digested triggers | Each `DigestEvent` is `{ id: string, time: Date, payload: object }`. Constraints: * **One digest step per workflow.** For two-stage digests, trigger a second workflow from `step.custom`. * Digest content captured at trigger time — editing the workflow doesn't affect events already in flight. * Digest results are not available in step controls — only inside subsequent step `resolver`/`providers`/`skip` callbacks. ### `step.custom` Run arbitrary code and persist its output. ```typescript theme={null} const result = await step.custom("fetch", async () => { const r = await fetch("https://api.example.com/users/123"); return await r.json(); }, { outputSchema: { type: "object", properties: { name: { type: "string" }, email: { type: "string" }, }, required: ["name", "email"], } as const, }); ``` | Option | Type | Description | | - | - | - | | `outputSchema` | `JsonSchema \| ZodSchema` | Validates and types the return value (defaults to `unknown` if omitted) | The return value must be JSON-serializable. The result is persisted in durable execution context and re-used on retries. ### `step.http` Call an external HTTP endpoint as part of the workflow — for fetching just-in-time data, posting to a webhook, or fanning out to a downstream service. ```typescript theme={null} const plan = await step.http("fetch-plan", async () => ({ method: "GET", url: `https://api.example.com/users/${payload.userId}/plan`, headers: [{ key: "Authorization", value: "Bearer xxxxx" }], responseBodySchema: { type: "object", properties: { planName: { type: "string" }, renewalDate: { type: "string" }, }, required: ["planName", "renewalDate"], } as const, })); await step.email("notify", async () => ({ subject: `Your ${plan.planName} plan`, body: `Your plan renews on ${plan.renewalDate}.`, })); ``` Webhook-style fan-out: ```typescript theme={null} await step.http("webhook", async () => ({ method: "POST", url: payload.webhookUrl, headers: [{ key: "Content-Type", value: "application/json" }], body: [ { key: "event", value: "payment_failed" }, { key: "subscriberId", value: subscriber.subscriberId }, ], continueOnFailure: true, })); ``` | Output | Type | Required | Notes | | - | - | - | - | | `method` | `'GET' \| 'POST' \| 'PUT' \| 'PATCH' \| 'DELETE'` | Yes | HTTP verb | | `url` | `string` | Yes | Fully qualified URL. Liquid templating is allowed (`{{payload.webhookUrl}}`). | | `headers` | `Array<{ key: string; value: string }>` | No | Outgoing headers | | `body` | `Array<{ key: string; value: string }>` | No | Form-style body. Use the SDK's typed body for JSON payloads. | | `responseBodySchema` | `JsonSchema \| ZodSchema` | Required if downstream steps reference response data | Declares which response properties are addressable | | `continueOnFailure` | `boolean` | No | If `true`, a non-2xx response does not stop the workflow. Default `false`. | Constraints: * **`responseBodySchema` is required** when subsequent steps reference response data. Only properties declared in the schema are available as `{{ steps.. }}` (Dashboard) or as typed fields on the returned object (Framework). * The HTTP step participates in retries. Treat it as a side effect — if you need exactly-once external calls, prefer `step.custom` with your own idempotency key. * The Liquid `{{subscriber.*}}` and `{{payload.*}}` variables are usable inside `url`, `headers`, and `body` values. ## Step Options ```typescript theme={null} await step.(stepId, resolver, { controlSchema, skip, providers, disableOutputSanitization, }); ``` ### `controlSchema` Defines no-code controls editable in the Dashboard. Pass a Zod schema, JSON Schema (`as const`), or Class-Validator class. ```typescript theme={null} await step.email("welcome", async (controls) => ({ subject: controls.subject, body: render(), }), { controlSchema: z.object({ hideBanner: z.boolean().default(false), subject: z.string().default("Hi {{subscriber.firstName | capitalize}}"), }), }); ``` Control values support [LiquidJS templating](https://liquidjs.com/filters/overview.html): * `{{subscriber.firstName}}` * `{{payload.userId}}` * `{{payload.invoiceDate | date: '%b %d, %y'}}` * `{{subscriber.firstName | capitalize | append: '!'}}` ### `skip` Skip a step based on dynamic logic. ```typescript theme={null} await step.email("follow-up", resolver, { skip: () => inAppNotification.read === true, }); // Or based on subscriber data await step.email("upsell", resolver, { skip: () => subscriber.data?.tier === "enterprise", }); ``` The function receives the resolved controls and returns `boolean | Promise`. ### `providers` (Per-Step Overrides) Override the request sent to the underlying provider SDK. ```typescript theme={null} await step.chat("notify", resolver, { providers: { slack: ({ controls, outputs }) => ({ text: outputs.body, blocks: [ { type: "section", text: { type: "mrkdwn", text: `*New post:* ${outputs.body}` }, }, ], }), }, }); ``` ```typescript theme={null} await step.email("alert", resolver, { providers: { sendgrid: ({ controls, outputs }) => ({ from: "alerts@acme.com", cc: ["ops@acme.com"], _passthrough: { body: { ip_pool_name: "transactional" }, headers: { "X-Custom": "value" }, query: { foo: "bar" }, }, }), }, }); ``` The `_passthrough` block deep-merges into the final provider request — typed provider keys take precedence over `_passthrough`. ### `disableOutputSanitization` Allow raw HTML / unescaped characters in step output. ```typescript theme={null} await step.inApp("link", async () => ({ body: "Check it out", data: { link: "/p/123?active=true&env=prod" }, // & gets escaped by default }), { disableOutputSanitization: true }); ``` For Inbox HTML rendering, also use `dangerouslySetInnerHTML` in `renderBody` / `renderSubject` (see [`inbox-integration`](../../inbox-integration)). ## Conditional Patterns ### Send email only if in-app wasn't seen ```typescript theme={null} const inAppNotification = await step.inApp("inbox", async () => ({ subject: "Task reminder!", body: "Task is not yet complete.", })); await step.delay("wait-6h", async () => ({ unit: "hours", amount: 6 })); await step.email("email-fallback", async () => ({ subject: "Task reminder!", body: "Task is not yet complete.", }), { skip: () => inAppNotification.read === true, }); ``` ### Skip delay for premium users ```typescript theme={null} await step.delay("wait", async () => ({ unit: "hours", amount: 24 }), { skip: async () => subscriber.data?.tier === "premium", }); ``` ### Branch on a fetched value ```typescript theme={null} const task = await step.custom("fetch-task", async () => { const t = await db.fetchTask(payload.taskId); return { id: t.id, complete: t.complete, title: t.title }; }, { outputSchema: { type: "object", properties: { id: { type: "string" }, complete: { type: "boolean" }, title: { type: "string" }, }, required: ["id", "complete"], } as const, }); await step.email("reminder", async () => ({ subject: `Reminder: ${task.title}`, body: "Please complete your task.", }), { skip: () => task.complete, }); ``` ## Failure & Retries * If a **delay** or **digest** step fails, the workflow stops — subsequent steps do not run. * If a **channel** step fails delivery, retries depend on provider config and Novu's retry policy. * Workflow handlers may be re-invoked on retry. Keep them deterministic — push side effects into `step.custom` so the result is persisted in durable context. ## Type Inference When `payloadSchema` and `controlSchema` are provided as Zod or JSON Schema (with `as const`), `payload` and `controls` are fully typed: ```typescript theme={null} workflow("typed", async ({ step, payload }) => { // payload.userId is `string` (inferred from Zod schema below) await step.email("greet", async (controls) => ({ // controls.subject is `string` (inferred from Zod schema below) subject: controls.subject, body: `Hi ${payload.firstName}`, }), { controlSchema: z.object({ subject: z.string().default("Hi") }), }); }, { payloadSchema: z.object({ userId: z.string(), firstName: z.string(), }), }); ``` If you don't supply a schema, `payload` and `controls` are `unknown`. ## Appendix: Step Conditions (Dashboard JSON-Logic ↔ Framework `skip`) Dashboard authors gate a step with [JSON-Logic](https://jsonlogic.com) on `step.condition`. Framework authors pass a `skip: () => boolean` callback. The semantics are inverse — Dashboard runs when the condition is `true`, Framework `skip` skips when the callback returns `true`. | Intent | Dashboard JSON-Logic | Framework `skip` | | - | - | - | | Run only when subscriber is offline | `{ "==": [{ "var": "subscriber.isOnline" }, "false"] }` | `skip: ({ subscriber }) => subscriber.isOnline === true` | | Run only when In-App not read | `{ "==": [{ "var": "steps..read" }, "false"] }` | `skip: () => inAppResult.read === true` | | Run only when In-App not seen | `{ "==": [{ "var": "steps..seen" }, "false"] }` | `skip: () => inAppResult.seen === true` | | Run only for workflows tagged `billing` | `{ "in": ["billing", { "var": "workflow.tags" }] }` | (filter at trigger time) | | Run only when HTTP `status == "active"` | `{ "==": [{ "var": "steps..status" }, "active"] }` | `skip: () => httpResult.status !== "active"` | Variables you can reference in either surface (full breakdown in [`design-workflow/references/step-conditions.md`](../../design-workflow/references/step-conditions.md)): * `workflow.*` — `workflowId`, `name`, `description`, `tags`, `severity` * `subscriber.*` — `subscriberId`, `firstName`, `lastName`, `email`, `phone`, `avatar`, `locale`, `timezone`, `isOnline`, `lastOnlineAt`, `data.*` * `payload.*` — any field declared in `payloadSchema` * `steps..*` — In-App `seen` / `read`, digest `events` / `eventCount`, HTTP properties declared in `responseBodySchema` * `context.*` — multi-tenant metadata passed at trigger time (tenant, region, app) > See [`design-workflow/references/step-conditions.md`](../../design-workflow/references/step-conditions.md) for the full list of canonical conditions and the design reasoning. # Branding and styling Source: https://docs.novu.co/.mintlify/skills/inbox-integration/references/branding-and-styling # Branding & Styling Reference The Inbox component is fully themeable through the `appearance` prop. This reference covers every level of customization — from dropping in a base theme to building dynamic, severity-aware, brand-perfect styles. > Inspiration: [inbox.novu.co](https://inbox.novu.co) showcases pre-built variants like Notion and Reddit. ## The `appearance` prop ```ts theme={null} type Appearance = { baseTheme?: BaseTheme; variables?: Variables; elements?: Record string)>; icons?: Record ReactNode>; }; ``` | Key | Purpose | | - | - | | `baseTheme` | Start from a predefined theme (e.g. `dark`) | | `variables` | Global design tokens (colors, fonts, radius, severity colors) | | `elements` | Per-element styles — string, style object, or callback | | `icons` | Replace built-in icons with your own React components | When both `baseTheme` and `variables` are set, **variables win**. Styles are auto-injected into ``. If the Inbox is rendered inside a shadow DOM, styles are scoped to that shadow root. ## Base themes Novu currently ships a `dark` base theme: ```tsx theme={null} import { Inbox } from "@novu/react"; import { dark } from "@novu/react/themes"; ``` Compose `baseTheme` + `variables` to start from a theme and tweak just a few tokens: ```tsx theme={null} appearance={{ baseTheme: dark, variables: { colorPrimary: "#FB4CA3", borderRadius: "12px" }, }} ``` ## Variables (design tokens) | Variable | Description | | - | - | | `colorBackground` | Inbox background | | `colorForeground` | Primary text color | | `colorPrimary` | Accent color for interactive elements | | `colorPrimaryForeground` | Text on primary surfaces | | `colorSecondary` | Less prominent surfaces | | `colorSecondaryForeground` | Text on secondary surfaces | | `colorCounter` | Background of unread counters | | `colorCounterForeground` | Text inside counters | | `colorNeutral` | Borders and neutral surfaces | | `colorShadow` | Shadow color | | `fontSize` | Base font size | | `borderRadius` | Border radius applied across elements | | `colorSeverityHigh` | High-severity accent | | `colorSeverityMedium` | Medium-severity accent | | `colorSeverityLow` | Low-severity accent | ```tsx theme={null} appearance={{ variables: { colorBackground: "#0B0B0F", colorForeground: "#F4F4F6", colorPrimary: "#FB4CA3", colorPrimaryForeground: "#FFFFFF", colorSecondary: "#1A1A22", colorSecondaryForeground: "#A1A1AA", colorCounter: "#FB4CA3", colorCounterForeground: "#FFFFFF", colorNeutral: "#27272A", colorShadow: "rgba(0, 0, 0, 0.4)", fontSize: "14px", borderRadius: "10px", colorSeverityHigh: "#E5484D", colorSeverityMedium: "#F76808", colorSeverityLow: "#3E63DD", }, }} ``` ## Element-level styling Each key in `appearance.elements` accepts: * **String of class names** — CSS, CSS Modules, Tailwind * **Style object** — inline CSS * **Callback** — `(context) => string` returning class names, evaluated on every render with the relevant context (notification, unreadCount, preference, schedule) ### Inline style object ```tsx theme={null} appearance={{ elements: { notificationSubject: { color: "#ff0000", fontWeight: 600 }, }, }} ``` ### Tailwind classes ```tsx theme={null} appearance={{ elements: { bellIcon: "p-4 bg-white rounded-full", notification: "bg-white rounded-lg shadow-sm hover:shadow-md hover:bg-gray-50", notificationPrimaryAction__button: "bg-pink-500 text-white px-3 py-1 rounded", }, }} ``` ### CSS Modules ```css theme={null} /* inbox.module.css */ .bellIcon { padding: 1rem; background-color: white; border-radius: 50%; } .bellIcon:hover { background-color: #f9fafb; } .notification { background: white; border-radius: 0.5rem; box-shadow: 0 1px 2px rgba(0,0,0,0.05); } ``` ```tsx theme={null} import styles from "./inbox.module.css"; appearance={{ elements: { bellIcon: styles.bellIcon, notification: styles.notification, }, }} ``` ### Dynamic styling via callbacks Callbacks receive contextual data and return class names. Use them for state-aware styles (unread count, notification severity, payload data): ```tsx theme={null} appearance={{ elements: { bellIcon: ({ unreadCount }) => { if (unreadCount.total > 10) { return "[--bell-gradient-start:var(--color-red-500)] [--bell-gradient-end:var(--color-red-500)]"; } if (unreadCount.total > 0) { return "[--bell-gradient-start:var(--color-yellow-500)] [--bell-gradient-end:var(--color-yellow-500)]"; } return "[--bell-gradient-start:var(--color-gray-500)] [--bell-gradient-end:var(--color-gray-500)]"; }, notification: ({ notification }) => notification.data?.priority === "high" ? "bg-red-50 ring-1 ring-red-300" : "", severityHigh__notificationBar: ({ notification }) => notification.read ? "opacity-50" : "opacity-100", }, }} ``` ### Common element keys | Element | Key | | - | - | | Notification container | `notification` | | Notification subject text | `notificationSubject` | | Notification body text | `notificationBody` | | Notification image / icon | `notificationImage` | | Notification date | `notificationDate` | | Notification list | `notificationList` | | Primary action button | `notificationPrimaryAction__button` | | Secondary action button | `notificationSecondaryAction__button` | | Archive button | `notificationArchive__button` | | Snooze button | `notificationSnooze__button` | | Mark unread button | `notificationUnread__button` | | Bell icon | `bellIcon` | | Bell container | `bellContainer` | | Bell dot (unread indicator) | `bellDot` | | Popover content | `popoverContent` | | Preferences button | `preferences__button` | | Schedule container | `scheduleContainer` | | Schedule header | `scheduleHeader` | | Schedule body / table | `scheduleBody`, `scheduleTable` | > To find any element key, inspect the DOM. Class names starting with `nv-` (visible just before a 🔔 emoji in DevTools) map to keys in `elements`. Drop the `nv-` prefix. ### Callback context signatures | Element group | Context | | - | - | | `bellIcon`, `bellContainer`, `bellDot`, `bellSeverityGlow`, `severity*__bellContainer` | `{ unreadCount: { total: number; severity: Record } }` | | `notification`, `notification*`, `severity*__notification*`, `notificationDot` | `{ notification: Notification }` | | `notificationList`, `notificationListContainer` | `{ notifications: Notification[] }` | | `workflow*`, `channelsContainer`, `channelName` | `{ preference: Preference }` | | `channelContainer`, `channelLabelContainer`, `channelIconContainer`, `channelLabel`, `channelSwitchContainer`, `channel__icon` | `{ preference?: Preference; preferenceGroup?: { name: string; preferences: Preference[] } }` | | `preferencesGroup*` | `{ preferenceGroup: { name: string; preferences: Preference[] } }` | | `preferencesContainer` | `{ preferences?: Preference[]; groups: Array<{ name: string; preferences: Preference[] }> }` | | `schedule*`, `dayScheduleCopy*`, `timeSelect*` | `{ schedule?: Schedule }` | ## Severity styling Notifications expose three severity levels: `high`, `medium`, `low`. Styling can be applied through variables (global colors) or elements (precise overrides). ### Severity variables | Variable | Description | | - | - | | `colorSeverityHigh` | High severity color | | `colorSeverityMedium` | Medium severity color | | `colorSeverityLow` | Low severity color | ```tsx theme={null} appearance={{ variables: { colorSeverityHigh: "#E5484D", colorSeverityMedium: "#F76808", colorSeverityLow: "#3E63DD", }, }} ``` Updating these automatically restyles both the notification accent bar and the bell glow. ### Severity element keys | Key | Description | | - | - | | `severityHigh__bellContainer` | Bell container for high severity | | `severityMedium__bellContainer` | Bell container for medium severity | | `severityLow__bellContainer` | Bell container for low severity | | `bellSeverityGlow` | Base bell glow style | | `severityGlowHigh__bellSeverityGlow` | Glow for high severity | | `severityGlowMedium__bellSeverityGlow` | Glow for medium severity | | `severityGlowLow__bellSeverityGlow` | Glow for low severity | | `severityHigh__notification` | High severity notification row | | `severityMedium__notification` | Medium severity notification row | | `severityLow__notification` | Low severity notification row | | `notificationBar` | Vertical bar on the left of a notification | | `severityHigh__notificationBar` | Bar for high severity | | `severityMedium__notificationBar` | Bar for medium severity | | `severityLow__notificationBar` | Bar for low severity | ```tsx theme={null} appearance={{ elements: { severityHigh__notificationBar: { backgroundColor: "red" }, severityHigh__bellContainer: "ring-2 ring-red-500", severityGlowHigh__bellSeverityGlow: "bg-red-500/40 blur-md", }, }} ``` > By default the bell takes the color of the highest-severity unread notification. ## Custom icons Replace built-in icons with anything that renders to a React node: ```tsx theme={null} import { Inbox } from "@novu/react"; import { RiSettings3Fill, RiArrowDownLine, RiNotification3Fill, } from "react-icons/ri"; , cogs: () => , arrowDown: () => , }, }} /> ``` ### Icon keys | Key | Description | | - | - | | `arrowDown` | Down arrow used in drop-downs and expandable sections | | `arrowDropDown` | Drop-down arrow in menus and selectors | | `arrowLeft` | Left arrow used in pagination/navigation | | `arrowRight` | Right arrow used in pagination/navigation | | `bell` | Notification bell in the header | | `chat` | Chat channel icon in preferences | | `check` | Checkmark for selected items | | `clock` | Date/time display | | `cogs` | Settings/preferences icon | | `dots` | Three-dot menu in notification items | | `email` | Email channel icon in preferences | | `inApp` | In-app channel icon in preferences | | `markAsArchived` | Archive notification | | `markAsArchivedRead` | Archive + read | | `markAsRead` | Mark as read | | `markAsUnread` | Mark as unread | | `markAsUnarchived` | Unarchive | | `push` | Push channel icon in preferences | | `sms` | SMS channel icon in preferences | | `trash` | Delete | | `unread` | Unread indicator | | `unsnooze` | Unsnooze indicator | > To find more keys, inspect the DOM for class names starting with `nv-` containing a 🖼️ emoji. The part after `nv-` is the icon key. ## Responsive Inbox ```tsx theme={null} ``` ```css theme={null} /* global.css */ .novu-popover-content { max-width: 500px; } @media (max-width: 768px) { .novu-popover-content { max-width: 350px; } } @media (max-width: 480px) { .novu-popover-content { max-width: 250px; } } @media (max-width: 320px) { .novu-popover-content { max-width: 200px; } } ``` For a mobile drawer experience, use the [Custom Popover](./personalization.md#custom-popover-with-shadcn-drawer) pattern with shadcn's ``. ## Brand-presets cookbook ### Notion-style (light, calm) ```tsx theme={null} appearance={{ variables: { colorBackground: "#FFFFFF", colorForeground: "#37352F", colorPrimary: "#2383E2", colorPrimaryForeground: "#FFFFFF", colorSecondary: "#F7F6F3", colorSecondaryForeground: "#787774", colorNeutral: "#E9E9E7", colorShadow: "rgba(15, 15, 15, 0.05)", fontSize: "14px", borderRadius: "6px", }, elements: { notification: "hover:bg-[#F7F6F3] transition-colors", notificationSubject: { fontWeight: 600 }, }, }} ``` ### Reddit-style (vibrant) ```tsx theme={null} appearance={{ variables: { colorPrimary: "#FF4500", colorPrimaryForeground: "#FFFFFF", colorBackground: "#FFFFFF", colorForeground: "#1A1A1B", colorSecondary: "#F6F7F8", colorCounter: "#FF4500", colorCounterForeground: "#FFFFFF", borderRadius: "16px", }, }} ``` ### Brand-locked dark ```tsx theme={null} import { dark } from "@novu/react/themes"; appearance={{ baseTheme: dark, variables: { colorPrimary: "#FB4CA3", colorPrimaryForeground: "#FFFFFF", borderRadius: "12px", }, }} ``` # Headless inbox examples Source: https://docs.novu.co/.mintlify/skills/inbox-integration/references/headless-inbox-examples # Headless Inbox Examples Use `@novu/js` for vanilla JavaScript applications or when you want full control over the UI. ## Installation ```bash theme={null} npm install @novu/js ``` ## Initialize the Client ```typescript theme={null} import { Novu } from "@novu/js"; const novu = new Novu({ applicationIdentifier: "YOUR_NOVU_APP_ID", subscriberId: "subscriber-123", subscriberHash: "hmac-hash-from-server", }); ``` ## Fetch Notifications ```typescript theme={null} const { data: notifications } = await novu.notifications.list({ limit: 20, }); notifications.forEach((notification) => { console.log(notification.subject, notification.body, notification.read); }); ``` ## Count Notifications ```typescript theme={null} // with single filter const count = await novu.notifications.count({ read: false, seen: false, archived: false, severity: SeverityLevelEnum.HIGH, // data attributes data: { type: 'login', }, }); // with multiple filters const counts = await novu.notifications.count({ filters: [ { read: false }, { seen: false }, { severity: SeverityLevelEnum.HIGH } { archived: true }, { tags: ['tag1'] }, { data: { type: 'login' } } ], }); ``` ## Mark as Read ```typescript theme={null} // Single notification await novu.notifications.read(notificationId); // All notifications await novu.notifications.readAll(); ``` ## Mark as Unread ```typescript theme={null} await novu.notifications.unread(notificationId); ``` ## Archive ```typescript theme={null} await novu.notifications.archive(notificationId); await novu.notifications.archiveAll(); ``` ## Unarchive ```typescript theme={null} await novu.notifications.unarchive(notificationId); ``` ## Complete Actions ```typescript theme={null} await novu.notifications.completePrimary(notificationId); await novu.notifications.completeSecondary(notificationId); ``` ## Snooze / Unsnooze ```typescript theme={null} await novu.notifications.snooze(notificationId, { duration: "1h" }); await novu.notifications.unsnooze(notificationId); ``` ## Delete ```typescript theme={null} await novu.notifications.delete(notificationId); await novu.notifications.deleteAll(); ``` ## Preferences ```typescript theme={null} // List preferences const { data: preferences } = await novu.preferences.list(); // Update a workflow preference await novu.preferences.update({ channels: { email: true, push: true }, workflowId: "workflow-id", }); ``` ## Real-Time Updates The `@novu/js` client automatically maintains a WebSocket connection for real-time notification updates. No additional configuration is needed. ## Vanilla JavaScript Example ```html theme={null}
``` # Multi tenancy Source: https://docs.novu.co/.mintlify/skills/inbox-integration/references/multi-tenancy # Multi-Tenancy with Contexts Use **Contexts** to scope notifications by tenant, workspace, organization, environment, or feature area — without duplicating workflows or subscribers. The Inbox displays only notifications whose trigger context exactly matches the Inbox context. > Contexts are a Novu primitive. If you're new to them, start with the [Contexts overview](https://docs.novu.co/platform/workflow/advanced-features/contexts). ## How context filtering works The Inbox uses **exact-match** filtering. The full context object passed to the `` must equal (key for key, value for value) the context used at trigger time: | Workflow Context | Inbox Context | Displayed? | | - | - | - | | `{ tenant: "acme" }` | `{ tenant: "acme" }` | ✅ | | `{}` | `{}` | ✅ | | `{}` | `{ tenant: "acme" }` | ❌ | | `{ tenant: "acme" }` | `{ tenant: "globex" }` | ❌ | | `{ tenant: "acme" }` | `{}` | ❌ | | `{ tenant: "acme", app: "first" }` | `{ tenant: "acme" }` | ❌ | This isolation makes context predictable and tamper-resistant (when combined with `contextHash`). ## End-to-end setup ### 1. Define the tenant context A tenant context is a JSON object that identifies a tenant. The `id` is the only required field; `data` is optional metadata. ```ts theme={null} const acmeContext = { tenant: { id: "acme-corp", data: { name: "Acme Corporation", plan: "enterprise", logo: "https://cdn.acme.com/logo.png", }, }, }; ``` You can also pass a bare string for simple cases: ```ts theme={null} const acmeContext = { tenant: "acme-corp" }; ``` Contexts are **auto-created** when first seen by Novu (via trigger or Inbox). Existing contexts are **not** auto-updated to prevent overwriting tenant data. To manage contexts manually, use the dashboard's **Contexts** section, the API, or `@novu/api`. ### 2. Trigger workflows with context ```typescript theme={null} import { Novu } from "@novu/api"; const novu = new Novu({ secretKey: process.env.NOVU_SECRET_KEY! }); await novu.trigger({ workflowId: "invoice-paid", to: { subscriberId: "user-123" }, payload: { amount: "$250" }, context: { tenant: { id: "acme-corp", data: { name: "Acme Corporation", plan: "enterprise" }, }, }, }); ``` All notifications emitted by this trigger are isolated to the `acme-corp` tenant. They will only surface in an Inbox initialized with the same tenant context. ### 3. Filter the Inbox by tenant ```tsx theme={null} import { Inbox } from "@novu/react"; ; ``` If a subscriber switches tenants in your app, re-render the Inbox with the new context. The Inbox automatically refetches notifications and reconnects the WebSocket scope. ### 4. Secure the context with `contextHash` Because `context` is set on the client, a hostile user could swap the tenant ID to peek at another tenant's notifications. To prevent that, generate an HMAC hash of a **canonicalized** context server-side. Canonicalization is required because JSON objects with the same data but different key order would otherwise produce different hashes. Use a library that implements [RFC-8259](https://datatracker.ietf.org/doc/html/rfc8259) canonicalization. ```typescript theme={null} import { createHmac } from "crypto"; import { canonicalize } from "@tufjs/canonical-json"; const context = { tenant: { id: "acme-corp", data: { name: "Acme Corporation", plan: "enterprise" }, }, }; export function getContextHash(context: object): string { return createHmac("sha256", process.env.NOVU_SECRET_KEY!) .update(canonicalize(context)) .digest("hex"); } const contextHash = getContextHash(context); ``` Pass both `context` and `contextHash` to the Inbox: ```tsx theme={null} ``` > If you change the `context` you must regenerate the `contextHash`. The hash is bound to the exact, canonicalized JSON. ## Patterns ### Switching tenants client-side ```tsx theme={null} "use client"; import { useState } from "react"; import { Inbox } from "@novu/react"; export function MultiTenantInbox({ user, tenants }) { const [activeTenant, setActiveTenant] = useState(tenants[0]); return ( <> ); } ``` Pre-compute one `contextHash` per tenant on the server: ```ts theme={null} const contextHashByTenant = Object.fromEntries( user.tenants.map((t) => [t.id, getContextHash({ tenant: t })]), ); ``` ### Per-feature scoping Contexts aren't limited to tenants — use them to scope by feature area, environment, or anything else: ```ts theme={null} context: { app: "billing", workspace: "production", } ``` The Inbox in your billing dashboard sees only billing notifications; the inbox in your monitoring dashboard sees only monitoring notifications. ### Combining tenant + app ```ts theme={null} context: { tenant: { id: "acme-corp", data: { name: "Acme" } }, app: "billing", } ``` The Inbox must declare the same combined context to see these notifications. ## Using context data in templates Once a context is created, its `data` is exposed in every template editor (email, in-app, SMS, push) via the `{{context}}` helper. This lets you personalize content per tenant from a single workflow definition. Example In-App body: ```liquid theme={null} Hello {{subscriber.firstName}}, your {{context.tenant.data.plan}} plan on {{context.tenant.data.name}} just renewed. ``` You can also branch workflow logic on context. See [Contexts in Workflows](https://docs.novu.co/platform/workflow/advanced-features/contexts/contexts-in-workflows). ## Operational notes * **Auto-create**: contexts referenced for the first time are automatically created in Novu. Visible in the dashboard under **Contexts**. * **No auto-update**: existing context data is never overwritten by a new trigger or Inbox initialization. To update tenant data, use the API. * **Context + HMAC**: when HMAC is enforced for the project, you must also pass `contextHash` if `context` is set. Subscribers will see no notifications otherwise. * **Order-independent hashing**: always canonicalize the JSON before hashing so `{ a: 1, b: 2 }` and `{ b: 2, a: 1 }` produce the same hash. * **Tenant switch ⇒ re-render**: changing `context` triggers a re-fetch and a new WebSocket subscription scope. ## Common pitfalls 1. **Empty context vs no context** — `context={{}}` is treated as "no context". Notifications triggered with a non-empty context will not appear, and vice versa. 2. **Mismatched object shape** — `{ tenant: "acme" }` is not equal to `{ tenant: { id: "acme" } }`. Pick one shape and use it consistently in both trigger and Inbox. 3. **Forgetting to regenerate the hash** — any change to the context object requires a new `contextHash`. A stale hash silently drops notifications. 4. **Canonicalization mismatch** — if your server canonicalizes but your test fixture doesn't (or vice versa), hashes diverge. Always go through the same `canonicalize` step. 5. **Storing secrets in `data`** — context data is read from the client. Don't include API keys, tokens, or PII you wouldn't otherwise expose. # Nextjs inbox examples Source: https://docs.novu.co/.mintlify/skills/inbox-integration/references/nextjs-inbox-examples # Next.js Inbox Examples ## App Router Setup The Inbox component is client-side only. Create a client component wrapper: ```tsx theme={null} // components/NotificationInbox.tsx "use client"; import { Inbox } from "@novu/nextjs"; export function NotificationInbox({ subscriberId, subscriberHash, }: { subscriberId: string; subscriberHash: string; }) { return ( ); } ``` Use it in a server component or layout: ```tsx theme={null} // app/layout.tsx import { NotificationInbox } from "../components/NotificationInbox"; import { getSubscriberHash } from "../lib/novu"; export default async function RootLayout({ children }) { const user = await getCurrentUser(); const subscriberHash = getSubscriberHash(user.id); return ( {children} ); } ``` ## HMAC Hash Generation (Server Utility) ```typescript theme={null} // lib/novu.ts import { createHmac } from "crypto"; export function getSubscriberHash(subscriberId: string): string { return createHmac("sha256", process.env.NOVU_SECRET_KEY!) .update(subscriberId) .digest("hex"); } ``` ## Pages Router Setup ```tsx theme={null} // pages/_app.tsx import { Inbox } from "@novu/nextjs"; function MyApp({ Component, pageProps }) { return ( <> ); } export default MyApp; ``` ## Environment Variables ```bash theme={null} # .env.local NEXT_PUBLIC_NOVU_APP_ID=your-app-id # Client-side (public) NOVU_SECRET_KEY=your-secret-key # Server-side only ``` **Important:** Use `NEXT_PUBLIC_` prefix for the app ID (client-safe). Never expose `NOVU_SECRET_KEY` to the client. ## With Router Integration Handle notification clicks with Next.js router: ```tsx theme={null} "use client"; import { Inbox } from "@novu/nextjs"; import { useRouter } from "next/navigation"; export function NotificationInbox({ subscriberId, subscriberHash }) { const router = useRouter(); return ( router.push(path)} onNotificationClick={(notification) => { if (notification.redirect?.url) { router.push(notification.redirect.url); } }} /> ); } ``` # Personalization Source: https://docs.novu.co/.mintlify/skills/inbox-integration/references/personalization # Personalization Reference The Inbox can be personalized at every level — from swapping the bell icon, to per-row layout, to fully custom popovers and routing. This reference covers render props, click handling, conditional display, HTML content, and composing the Inbox primitives inside your own UI. ## Render props Render props let you replace specific parts of the Inbox while keeping the surrounding chrome (default actions, hover states, animations, accessibility). | Prop | Replaces | Keep default actions? | | - | - | - | | `renderBell` | Bell icon | N/A | | `renderAvatar` | Notification avatar | ✅ | | `renderSubject` | Subject line | ✅ | | `renderBody` | Body text | ✅ | | `renderDefaultActions` | Mark-as-read / archive / snooze buttons | ❌ (you implement them) | | `renderCustomActions` | Primary + secondary action buttons | ✅ | | `renderNotification` | Entire notification row | ❌ (you implement everything) | ### `renderBell` Receives the unread count broken down by severity: ```tsx theme={null} import { Inbox, SeverityLevelEnum } from "@novu/react"; ( )} /> ``` ### `renderAvatar` ```tsx theme={null} ( )} /> ``` ### `renderSubject` / `renderBody` ```tsx theme={null} ( {notification.subject} )} renderBody={(notification) => (

{notification.body}

)} /> ``` ### `renderDefaultActions` Replaces the built-in mark-as-read / archive / snooze affordances. **You're responsible for re-implementing them.** ```tsx theme={null} import { Inbox } from "@novu/react"; import { Archive, Check } from "lucide-react"; (
)} /> ``` ### `renderCustomActions` (primary / secondary buttons) Useful for matching brand button styles without re-implementing default actions: ```tsx theme={null} (
{notification.secondaryAction && ( )} {notification.primaryAction && ( )}
)} /> ``` ### `renderNotification` (full takeover) Use sparingly — you lose all built-in affordances: ```tsx theme={null} (

{notification.subject}

{notification.body}

)} /> ``` ## Conditional display `renderNotification` receives the full notification object, including `tags`, `data`, `severity`, and `workflow`. Branch on whichever signal best fits the UI. ### By workflow tag ```tsx theme={null} renderNotification={(notification) => { if (notification.tags?.includes("billing")) { return ; } return ; }} ``` ### By workflow identifier ```tsx theme={null} renderNotification={(notification) => { if (notification.workflow?.identifier === "comment-mention") { return ; } return ; }} ``` ### By data object ```tsx theme={null} renderNotification={(notification) => { if (notification.data?.priority === "high") { return (
{notification.subject}

{notification.body}

); } return ; }} ``` ### By severity ```tsx theme={null} import { SeverityLevelEnum } from "@novu/react"; renderNotification={(notification) => { if (notification.severity === SeverityLevelEnum.HIGH) { return ; } return ; }} ``` ## HTML in notification content By default Novu sanitizes the `subject` and `body` to prevent XSS. To allow rich HTML: 1. **In the workflow** — open the In-App step editor and toggle on **Disable content sanitization**. 2. **In the Inbox** — render the field with `dangerouslySetInnerHTML`. > Only enable this if you fully control the trigger payload. Raw HTML opens an XSS surface area. ### Body only ```tsx theme={null} (
)} /> ``` ### Subject only ```tsx theme={null} ( )} /> ``` ### Both subject and body ```tsx theme={null} (

)} /> ``` Example workflow content (works with both Liquid variables and HTML tags): ```html theme={null} {{subscriber.firstName}}, good news! Your analytics dashboard is ready. Open it. ``` ## Notification click behavior ### `routerPush` integration When a notification has a `redirect.url` defined in the workflow, Novu calls `routerPush(url)` so navigation stays inside your SPA router. ```tsx theme={null} // Next.js App Router import { useRouter } from "next/navigation"; const router = useRouter(); router.push(path)} />; ``` ```tsx theme={null} // React Router v6 import { useNavigate } from "react-router-dom"; const navigate = useNavigate(); navigate(path)} />; ``` ```tsx theme={null} // Remix import { useNavigate } from "@remix-run/react"; const navigate = useNavigate(); navigate(path)} />; ``` ```tsx theme={null} // Gatsby import { navigate } from "gatsby"; navigate(path)} />; ``` ### `onNotificationClick` Override click behavior entirely (open a drawer, modal, etc.): ```tsx theme={null} { if (notification.data?.entity === "issue") { openIssueDrawer(notification.data.entityId); return; } if (notification.redirect?.url) { window.location.href = notification.redirect.url; } }} /> ``` ### `onPrimaryActionClick` / `onSecondaryActionClick` ```tsx theme={null} acceptInvite(notification.data.inviteId)} onSecondaryActionClick={(notification) => declineInvite(notification.data.inviteId)} /> ``` ## Custom popover The `` component is composable. When passed children, it acts as a context provider — drop the feed into any popover, drawer, or page. | Component | Renders | | - | - | | `` | Bell icon trigger | | `` | Header + scrollable list + footer (no Preferences page) | | `` | Same as `` plus the Preferences page | | `` | Standalone preferences | ### Standalone notification feed (no popover) ```tsx theme={null} import { Inbox, Notifications } from "@novu/react"; ``` ### Popover with Radix UI ```tsx theme={null} import { Inbox, InboxContent, Bell } from "@novu/react"; import { Popover, PopoverTrigger, PopoverContent } from "@radix-ui/react-popover"; ``` ### Custom popover with shadcn Drawer ```tsx theme={null} "use client"; import { Drawer, DrawerContent, DrawerHeader, DrawerTitle, DrawerTrigger, } from "@/components/ui/drawer"; import { Inbox, InboxContent } from "@novu/react"; export function NotificationDrawer() { return ( Notifications Inbox ); } ``` ### Full-page notification center ```tsx theme={null} import { Inbox, InboxContent } from "@novu/react"; export default function NotificationsPage() { return (

Notifications

); } ``` All customization props (`appearance`, `localization`, `tabs`, `routerPush`, render props, `context`) flow through the `` provider and apply to children automatically. ## Localization Override Inbox UI text per locale. Localization changes UI chrome only — to translate notification *content*, use [Workflow Translations](https://docs.novu.co/platform/workflow/advanced-features/translations). ```tsx theme={null} ``` The full key list is in [`defaultLocalization.ts`](https://github.com/novuhq/novu/blob/next/packages/js/src/ui/config/defaultLocalization.ts). ### Localizing workflow names `localization.dynamic` is a `Record` used to display friendly workflow names in the Preferences UI: ```tsx theme={null} localization={{ dynamic: { "weekly-digest": "Weekly Digest", "team-mention": "Team Mentions", }, }} ``` ### Multi-language switching pattern ```tsx theme={null} const [locale, setLocale] = useState("en-US"); const localizationByLocale = { "en-US": { "preferences.title": "Notification Preferences", locale: "en-US" }, "es-ES": { "preferences.title": "Preferencias de Notificación", locale: "es-ES" }, "fr-FR": { "preferences.title": "Préférences de Notification", locale: "fr-FR" }, }; ; ``` ## Tabs Group notifications into filtered tabs: ```tsx theme={null} import { Inbox, SeverityLevelEnum } from "@novu/react"; ; ``` * `tags`: workflow-level. Multiple tags use `OR` logic. * `severity`: from the In-App step's severity. Accepts a single value or an array. * `data`: matches keys defined in the In-App step's data object. * Combine `tags` + `data` + `severity` for narrower filters. To show counts per tab, use the [`useCounts` hook](https://docs.novu.co/platform/sdks/react/hooks/use-counts). ## Recipe: brand-aligned, fully personalized Inbox ```tsx theme={null} "use client"; import { useRouter } from "next/navigation"; import { Inbox, SeverityLevelEnum } from "@novu/react"; import { dark } from "@novu/react/themes"; export function BrandedInbox({ subscriberId, subscriberHash }) { const router = useRouter(); return ( router.push(path)} tabs={[ { label: "All", filter: { tags: [] } }, { label: "Mentions", filter: { tags: ["mention"] } }, { label: "Critical", filter: { severity: SeverityLevelEnum.HIGH } }, ]} appearance={{ baseTheme: dark, variables: { colorPrimary: "#FB4CA3", colorPrimaryForeground: "#FFFFFF", borderRadius: "12px", }, elements: { notification: ({ notification }) => notification.data?.priority === "high" ? "bg-red-500/10 ring-1 ring-red-500/30" : "", notificationPrimaryAction__button: "bg-pink-500 hover:bg-pink-600", }, }} renderAvatar={(notification) => ( )} localization={{ locale: "en-US", "inbox.filters.labels.default": "All", "notifications.emptyNotice": "Nothing new — you're all caught up.", }} /> ); } ``` # React inbox examples Source: https://docs.novu.co/.mintlify/skills/inbox-integration/references/react-inbox-examples # React Inbox Examples ## Basic Inbox ```tsx theme={null} import { Inbox } from "@novu/react"; function App() { return ( ); } ``` ## Custom Bell Icon ```tsx theme={null} import { Inbox } from "@novu/react"; function App() { return ( ( )} /> ); } ``` ## Custom Notification Rendering ```tsx theme={null} import { Inbox } from "@novu/react"; function App() { return ( (
{notification.avatar && ( )}
{notification.subject &&

{notification.subject}

}

{notification.body}

)} /> ); } ``` ## Granular Render Customization Customize individual parts instead of the entire notification: ```tsx theme={null} ( )} renderSubject={(notification) => ( {notification.subject} )} renderBody={(notification) => (

{notification.body}

)} renderDefaultActions={(notification) => (
{notification.primaryAction && ( )}
)} /> ``` ## Event Handlers ```tsx theme={null} { console.log("Clicked:", notification.id); if (notification.redirect?.url) { window.location.href = notification.redirect.url; } }} onPrimaryActionClick={(notification) => { console.log("Primary action:", notification.primaryAction?.label); }} onSecondaryActionClick={(notification) => { console.log("Secondary action:", notification.secondaryAction?.label); }} /> ``` ## Themed Inbox ```tsx theme={null} ``` ## Composable Components Use child components for full layout control: ```tsx theme={null} import { Inbox, Bell, Notifications, Preferences } from "@novu/react"; function NotificationCenter() { return ( ); } ``` # Security Source: https://docs.novu.co/.mintlify/skills/inbox-integration/references/security # Inbox Security ## HMAC Subscriber Hash The subscriber hash prevents unauthorized access to notifications. Without it, anyone who knows a subscriber ID can read their notifications. **HMAC is mandatory in production.** The Novu API rejects unauthenticated Inbox requests in production environments. ## How It Works 1. Your **server** generates an HMAC-SHA256 hash of the subscriber ID using the `NOVU_SECRET_KEY` 2. The hash is passed to the Inbox component as `subscriberHash` 3. Novu verifies the hash server-side before returning notifications ## Generate the Hash ### Node.js ```typescript theme={null} import { createHmac } from "crypto"; function getSubscriberHash(subscriberId: string): string { return createHmac("sha256", process.env.NOVU_SECRET_KEY!) .update(subscriberId) .digest("hex"); } const hash = getSubscriberHash("user-123"); // => "a1b2c3d4e5f6..." ``` ### Python ```python theme={null} import hmac import hashlib import os def get_subscriber_hash(subscriber_id: str) -> str: return hmac.new( os.environ["NOVU_SECRET_KEY"].encode(), subscriber_id.encode(), hashlib.sha256 ).hexdigest() hash = get_subscriber_hash("user-123") ``` ### Go ```go theme={null} import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "os" ) func getSubscriberHash(subscriberID string) string { mac := hmac.New(sha256.New, []byte(os.Getenv("NOVU_SECRET_KEY"))) mac.Write([]byte(subscriberID)) return hex.EncodeToString(mac.Sum(nil)) } ``` ## Pass to the Component ### React ```tsx theme={null} ``` ### Vanilla JS ```typescript theme={null} const novu = new Novu({ applicationIdentifier: "YOUR_NOVU_APP_ID", subscriberId: userId, subscriberHash: subscriberHash, }); ``` ## Security Checklist * **Never expose `NOVU_SECRET_KEY` on the client** — the hash must be generated server-side * **`applicationIdentifier` is public** — it can safely be in client-side code and environment variables * **Generate the hash per subscriber** — each subscriber gets a unique hash based on their ID * **The hash is deterministic** — same subscriber ID + same secret key always produces the same hash * **Rotate the secret key carefully** — changing the key invalidates all existing hashes * **Use HTTPS in production** — prevent the hash from being intercepted in transit # Preferences ui examples Source: https://docs.novu.co/.mintlify/skills/manage-preferences/references/preferences-ui-examples # Preferences UI Examples ## Built-In Preferences (Inside Inbox) The Inbox component includes a built-in Preferences panel. Subscribers access it via the settings icon: ```tsx theme={null} import { Inbox } from "@novu/react"; function App() { return ( ); } ``` ## Standalone Preferences Component Render the Preferences panel independently: ```tsx theme={null} import { Inbox, Preferences } from "@novu/react"; function PreferencesPage() { return ( ); } ``` ## Preferences with Filtering Filter which workflows appear in the Preferences panel: ```tsx theme={null} ``` ## Preference Groups Group workflows in the Preferences panel: ```tsx theme={null} ``` ## Custom Preferences UI with @novu/js Build a completely custom preferences interface: ```typescript theme={null} import { Novu } from "@novu/js"; const novu = new Novu({ applicationIdentifier: "YOUR_NOVU_APP_ID", subscriberId: "subscriber-123", subscriberHash: "hmac-hash", }); // Fetch all preferences const { data: preferences } = await novu.preferences.list(); // Render custom UI preferences.forEach((pref) => { console.log(`Workflow: ${pref.workflow.name}`); console.log(` Email: ${pref.channels.email}`); console.log(` SMS: ${pref.channels.sms}`); console.log(` Push: ${pref.channels.push}`); console.log(` In-App: ${pref.channels.inApp}`); console.log(` Chat: ${pref.channels.chat}`); }); // Toggle a preference preferences?.[1]?.update({ channels: { email: true, push: true }, }); ``` ## Next.js Example ```tsx theme={null} // components/PreferencesPanel.tsx "use client"; import { Inbox, Preferences } from "@novu/nextjs"; export function PreferencesPanel({ subscriberId, subscriberHash, }: { subscriberId: string; subscriberHash: string; }) { return ( ); } ``` ## Important Notes * Read-only workflows (`readOnly: true`) are **hidden** from the Preferences UI — subscribers cannot change them. It signifies that workflow is critical * The Preferences component requires a parent `` wrapper for the Novu context * Preferences are per-subscriber and per-environment (dev, staging, prod) and scoped per context * Changes made via the UI are immediately reflected in notification delivery # Subscriber preferences examples Source: https://docs.novu.co/.mintlify/skills/manage-preferences/references/subscriber-preferences-examples # Subscriber Preferences Examples ## List All Preferences ### Node.js ```typescript theme={null} import { Novu } from "@novu/api"; const novu = new Novu({ secretKey: process.env.NOVU_SECRET_KEY, }); const preferences = await novu.subscribers.preferences.list({ subscriberId: "subscriber-123", }); console.log(preferences.result); ``` ### cURL ```bash theme={null} curl https://api.novu.co/v1/subscribers/subscriber-123/preferences \ -H "Authorization: ApiKey $NOVU_SECRET_KEY" ``` ## Update Workflow-Specific Preference ### Node.js ```typescript theme={null} await novu.subscribers.preferences.update( { workflowId: "weekly-newsletter", channels: { email: false, inApp: true }, }, "subscriber-123" ); ``` ### cURL ```bash theme={null} curl -X PATCH https://api.novu.co/v1/subscribers/subscriber-123/preferences \ -H "Authorization: ApiKey $NOVU_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "workflowId": "weekly-newsletter", "channels": { "email": false, "inApp": true } }' ``` ## Update Global Preferences Applies across all workflows — omit `workflowId`: ```typescript theme={null} await novu.subscribers.preferences.update( { channels: { sms: false, push: false } }, "subscriber-123" ); ``` ## Client-Side Preference Updates Using `@novu/js`: ```typescript theme={null} import { Novu } from "@novu/js"; const novu = new Novu({ applicationIdentifier: "YOUR_NOVU_APP_ID", subscriberId: "subscriber-123", // subscriberHash is required if HMAC encryption is turned on. Read more https://docs.novu.co/platform/inbox/prepare-for-production#secure-your-inbox-with-hmac-encryption subscriberHash: "hmac-hash", }); // List preferences const { data: preferences } = await novu.preferences.list(); // Update a specific workflow await novu.preferences.update({ channels: { email: true, push: true }, workflowId: "workflow-id", }); // bulk update preferences await novu.preferences.bulkUpdate([ { workflowId: 'workflow_id', channels: { email: false, sms: true } }, { workflowId: 'workflow_id_2', channels: { email: true, sms: false, in_app: true } }, ]); ``` ## Common Preference Operations ### Disable email at global preference level. ```typescript theme={null} await novu.subscribers.preferences.update( { channels: { email: false } }, "subscriber-123" ); ``` ### Opt out of email channel for a specific workflow ```typescript theme={null} await novu.subscribers.preferences.update( { workflowId: "weekly-newsletter", channels: { email: true } }, "subscriber-123" ); ``` # Workflow preferences examples Source: https://docs.novu.co/.mintlify/skills/manage-preferences/references/workflow-preferences-examples # Workflow Preferences Examples ## All Channels Enabled, Subscriber-Editable ```typescript theme={null} import { workflow } from "@novu/framework"; const myWorkflow = workflow("general-notification", execute, { preferences: { all: { enabled: true, readOnly: false }, }, }); ``` ## Specific Channels Only ```typescript theme={null} const emailOnlyWorkflow = workflow("weekly-report", execute, { preferences: { all: { enabled: false }, channels: { email: { enabled: true }, }, }, }); ``` ## Critical Notification (Read-Only) ```typescript theme={null} const securityAlertWorkflow = workflow("security-alert", execute, { preferences: { all: { enabled: true, readOnly: true }, }, }); ``` ## Mixed Channel Defaults ```typescript theme={null} const orderUpdateWorkflow = workflow("order-update", execute, { preferences: { all: { enabled: true, readOnly: false }, channels: { email: { enabled: true }, sms: { enabled: false }, // off by default, subscriber can enable push: { enabled: true }, chat: { enabled: false }, inApp: { enabled: true }, }, }, }); ``` ## In-App + Email Default ```typescript theme={null} const commentWorkflow = workflow("new-comment", execute, { preferences: { all: { enabled: false }, channels: { email: { enabled: true }, inApp: { enabled: true }, }, }, }); ``` ## All Channels Disabled by Default Subscribers must opt in: ```typescript theme={null} const optInWorkflow = workflow("beta-updates", execute, { preferences: { all: { enabled: false, readOnly: false }, }, }); ``` # Credentials examples Source: https://docs.novu.co/.mintlify/skills/manage-subscribers/references/credentials-examples # Credentials Examples Subscriber credentials store channel-specific tokens and webhook URLs needed for push and chat delivery. ## FCM (Firebase Cloud Messaging) ```typescript theme={null} import { Novu } from "@novu/api"; const novu = new Novu({ secretKey: process.env.NOVU_SECRET_KEY, }); await novu.subscribers.credentials.update( { providerId: "fcm", // use integrationIdentifier if there are multiple fcm type active integrations integrationIdentifier: "fcm-abc-123", credentials: { deviceTokens: ["fcm-device-token-here"] } }, "subsriberId-1" ); ``` ### Multiple Device Tokens A subscriber can have multiple devices. Each device has one device tokens. ```typescript theme={null} await novu.subscribers.credentials.update( { providerId: "fcm", integrationIdentifier: "fcm-abc-123", credentials: { deviceTokens: [ "token-phone-abc", "token-tablet-def", "token-desktop-ghi", ], }, }, "user-123" ); ``` ## APNS (Apple Push Notification Service) ```typescript theme={null} await novu.subscribers.credentials.update( { providerId: "apns", credentials: { deviceTokens: ["apns-device-token-xyz789"] } }, "user-123" ); ``` ## Expo Push ```typescript theme={null} await novu.subscribers.credentials.update( { providerId: "expo", credentials: { deviceTokens: ["ExponentPushToken[xxx]"] } }, "user-123" ); ``` ## Discord ```typescript theme={null} await novu.subscribers.credentials.update( { providerId: "discord", credentials: { webhookUrl: "https://discord.com/api/webhooks/123/abc" } }, "user-123" ); ``` ## cURL ```bash theme={null} curl -X PUT https://api.novu.co/v1/subscribers/user-123/credentials \ -H "Authorization: ApiKey $NOVU_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "providerId": "fcm", integrationIdentifier: "fcm-abc-123", "credentials": { "deviceTokens": ["fcm-device-token-abc123"] } }' ``` ## Important Notes * Device tokens are set as an array — providing a new array **replaces** existing tokens in `PUT` api request and new tokens are appended in case of `PATCH` request. * Each provider (FCM, APNS etc.) must be configured as an integration in the Novu dashboard before storing the credentials. * Push tokens expire — For FCM and EXPO, novu handles the expiration of stale tokens. For rest other providers, user need to handle the expiry of tokens. # Subscriber crud examples Source: https://docs.novu.co/.mintlify/skills/manage-subscribers/references/subscriber-crud-examples # Subscriber CRUD Examples ## Create ### Node.js ```typescript theme={null} import { Novu } from "@novu/api"; const novu = new Novu({ secretKey: process.env.NOVU_SECRET_KEY, }); await novu.subscribers.create({ subscriberId: "user-123", email: "jane@example.com", firstName: "Jane", lastName: "Doe", phone: "+15551234567", avatar: "https://example.com/jane.jpg", locale: "en-US", timezone: "America/New_York", data: { plan: "pro", company: "Acme Inc", }, }); ``` ### Python ```python theme={null} from novu_py import Novu novu = Novu(security=Security(secret_key=os.environ["NOVU_SECRET_KEY"])) novu.subscribers.create(request={ "subscriber_id": "user-123", "email": "jane@example.com", "first_name": "Jane", "last_name": "Doe", }) ``` ### cURL ```bash theme={null} curl -X POST https://api.novu.co/v1/subscribers \ -H "Authorization: ApiKey $NOVU_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "subscriberId": "user-123", "email": "jane@example.com", "firstName": "Jane", "lastName": "Doe" }' ``` ## Read ### Retrieve Single Subscriber ```typescript theme={null} const subscriber = await novu.subscribers.retrieve("user-123"); console.log(subscriber.result); ``` ### cURL — Get Subscriber ```bash theme={null} curl https://api.novu.co/v1/subscribers/user-123 \ -H "Authorization: ApiKey $NOVU_SECRET_KEY" ``` ### Search Subscribers ```typescript theme={null} const results = await novu.subscribers.search({ email: "jane@example.com", }); ``` ## Update ### Partial Update ```typescript theme={null} await novu.subscribers.patch( { firstName: "Jane", data: { plan: "enterprise" } }, "user-123" ); ``` ### cURL ```bash theme={null} curl -X PATCH https://api.novu.co/v1/subscribers/user-123 \ -H "Authorization: ApiKey $NOVU_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "firstName": "Jane", "data": { "plan": "enterprise" } }' ``` ## Delete ```typescript theme={null} await novu.subscribers.delete("user-123"); ``` ### cURL ```bash theme={null} curl -X DELETE https://api.novu.co/v1/subscribers/user-123 \ -H "Authorization: ApiKey $NOVU_SECRET_KEY" ``` ## Bulk Create At max 500 subscribers can be created in one single api call ```typescript theme={null} await novu.subscribers.createBulk({ subscribers: [ { subscriberId: "user-1", email: "alice@example.com", firstName: "Alice" }, { subscriberId: "user-2", email: "bob@example.com", firstName: "Bob" }, { subscriberId: "user-3", email: "carol@example.com", firstName: "Carol" }, ], }); ``` # Topics examples Source: https://docs.novu.co/.mintlify/skills/manage-subscribers/references/topics-examples # Topics Examples Topics are named groups of subscribers used for broadcast-style notifications. ## Create a Topic ```typescript theme={null} import { Novu } from "@novu/api"; const novu = new Novu({ secretKey: process.env.NOVU_SECRET_KEY, }); await novu.topics.create({ key: "engineering-team", name: "Engineering Team", }); ``` ### cURL ```bash theme={null} curl -X POST https://api.novu.co/v1/topics \ -H "Authorization: ApiKey $NOVU_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "key": "engineering-team", "name": "Engineering Team" }' ``` ## Add Subscribers to a Topic ```typescript theme={null} await novu.topics.subscriptions.create( { subscriptions: ["user-1", "user-2", "user-3"] }, "engineering-team" ); ``` ### cURL ```bash theme={null} curl -X POST https://api.novu.co/v1/topics/engineering-team/subscriptions \ -H "Authorization: ApiKey $NOVU_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "subscriptions": ["user-1", "user-2", "user-3"] }' ``` ## Remove Subscribers from a Topic ```typescript theme={null} await novu.topics.subscriptions.delete( { subscriptions: ["user-3"] }, "engineering-team" ); ``` ## List All Topics ```typescript theme={null} const topics = await novu.topics.list({}); console.log(topics.result); ``` ### cURL ```bash theme={null} curl https://api.novu.co/v1/topics \ -H "Authorization: ApiKey $NOVU_SECRET_KEY" ``` ## Retrieve a Specific Topic ```typescript theme={null} const topic = await novu.topics.get("engineering-team"); console.log(topic.result); ``` ## Rename a Topic ```typescript theme={null} await novu.topics.update( { name: "Engineering & Platform Team" }, "engineering-team" ); ``` ## Delete a Topic ```typescript theme={null} await novu.topics.delete("engineering-team"); ``` ## Trigger to a Topic ```typescript theme={null} await novu.trigger({ workflowId: "sprint-update", to: { type: "Topic", topicKey: "engineering-team" }, payload: { message: "Sprint 42 retrospective notes are ready" }, }); ``` ## Common Topic Patterns ### Per-Project Topics ```typescript theme={null} // Create a topic per project await novu.topics.create({ key: `project-${projectId}`, name: projectName }); // Add team members await novu.topics.subscriptions.create( { subscriptions: teamMemberIds }, `project-${projectId}` ); // Notify the project team await novu.trigger({ workflowId: "project-update", to: { type: "Topic", topicKey: `project-${projectId}` }, payload: { update: "New deployment" }, }); ``` ### Role-Based Topics ```typescript theme={null} const roles = ["admin", "editor", "viewer"]; for (const role of roles) { await novu.topics.create({ key: `role-${role}`, name: `${role} Users` }); } // Add users by role await novu.topics.subscriptions.create( { subscriptions: adminUserIds }, "role-admin" ); ``` # Best practices Source: https://docs.novu.co/.mintlify/skills/trigger-notification/references/best-practices # Best Practices > Designing the workflow itself (channels, severity, `critical`, digest, conditions, templates)? See [`design-workflow/`](../../design-workflow). This file covers **trigger-side** best practices only — idempotency, retries, payload design, and topic vs bulk choice. ## Idempotency `transactionId` is unique to each workflow trigger (event). Novu generates unique transactionId if not provided during trigger. It can be used for idempotennt workflow run and to cancel the pending workflow run later ```typescript theme={null} import { randomUUID } from "crypto"; const result = await novu.trigger({ workflowId: "order-confirmation", to: "customer-123", payload: { orderId: "order-001" }, transactionId: `order-confirmation-order-001`, // deterministic ID prevents duplicates }); ``` **Deterministic IDs** (based on the event context) are preferred over random UUIDs — they naturally prevent duplicate triggers for the same event. ## Error Handling ```typescript theme={null} try { const result = await novu.trigger({ workflowId: "welcome-email", to: "subscriber-123", payload: { userName: "Jane" }, }); console.log("Triggered successfully:", result); } catch (error) { if (error.statusCode === 422) { console.error("Validation error — check payload schema:", error.message); } else if (error.statusCode === 401) { console.error("Authentication failed — check NOVU_SECRET_KEY"); } else if (error.statusCode === 404) { console.error("Workflow not found — check workflowId"); } else { console.error("Unexpected error:", error); } } ``` ## Retry Strategy For transient failures (5xx errors, network timeouts), use exponential backoff: ```typescript theme={null} async function triggerWithRetry( novu: Novu, params: TriggerParams, maxRetries = 3 ) { for (let attempt = 0; attempt <= maxRetries; attempt++) { try { return await novu.trigger(params); } catch (error) { const isRetryable = error.statusCode >= 500 || error.code === "ECONNRESET"; if (!isRetryable || attempt === maxRetries) throw error; const delay = Math.pow(2, attempt) * 1000; // 1s, 2s, 4s await new Promise((resolve) => setTimeout(resolve, delay)); } } } ``` **Non-retryable errors** (do not retry): * `401` — Invalid API key * `404` — Workflow not found * `422` — Payload validation failure ## Payload Design * Keep payloads small — include IDs and references, not full objects * Use the workflow's `payloadSchema` to enforce structure * Avoid sensitive data in payloads (they may be logged/stored) ```typescript theme={null} // Good: reference IDs { orderId: "order-001", userId: "user-123" } // Avoid: full objects with sensitive data { order: { id: "order-001", creditCard: "4111..." } } ``` ## Topic vs. Bulk Triggers | Use Case | Approach | | - | - | | Same notification to a group | Topic trigger | | Different payloads per subscriber | Bulk trigger | | All subscribers in the environment | Broadcast | | More than 100 unique events | Chunked bulk triggers | # Bulk trigger examples Source: https://docs.novu.co/.mintlify/skills/trigger-notification/references/bulk-trigger-examples # Bulk Trigger Examples ## Basic Bulk Trigger Send up to 100 events in a single request: ```typescript theme={null} import { Novu } from "@novu/api"; const novu = new Novu({ secretKey: process.env.NOVU_SECRET_KEY, }); const result = await novu.triggerBulk({ events: [ { workflowId: "welcome-email", to: "subscriber-1", payload: { userName: "Alice" }, }, { workflowId: "welcome-email", to: "subscriber-2", payload: { userName: "Bob" }, }, { workflowId: "order-shipped", to: "subscriber-3", payload: { orderId: "ORD-100" }, }, ], }); ``` ## Chunking for Large Batches For more than 100 events, chunk into groups: ```typescript theme={null} function chunk(array: T[], size: number): T[][] { const chunks: T[][] = []; for (let i = 0; i < array.length; i += size) { chunks.push(array.slice(i, i + size)); } return chunks; } const allEvents = users.map((user) => ({ workflowId: "weekly-digest", to: user.id, payload: { userName: user.name }, })); const batches = chunk(allEvents, 100); for (const batch of batches) { await novu.triggerBulk({ events: batch }); } ``` ## cURL ```bash theme={null} curl -X POST https://api.novu.co/v1/events/trigger/bulk \ -H "Authorization: ApiKey $NOVU_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "events": [ { "name": "welcome-email", "to": "subscriber-1", "payload": { "userName": "Alice" } }, { "name": "welcome-email", "to": "subscriber-2", "payload": { "userName": "Bob" } } ] }' ``` ## Important Notes * Maximum **100 events** per bulk request * Each event in the bulk request is independent — different workflows, subscribers, and payloads are allowed * Errors/Success responses are returned per-event, not for the entire batch * For very large sends (thousands+), consider using topic-based triggers instead # Installation Source: https://docs.novu.co/.mintlify/skills/trigger-notification/references/installation # Installation ## Node.js / TypeScript ```bash theme={null} npm install @novu/api # or pnpm add @novu/api # or yarn add @novu/api ``` ## Environment Variables ```bash theme={null} NOVU_SECRET_KEY=your-secret-key-here ``` Get your API key from [dashboard.novu.co/api-keys](https://dashboard.novu.co/api-keys). ## Initialize the SDK ```typescript theme={null} import { Novu } from "@novu/api"; const novu = new Novu({ secretKey: process.env.NOVU_SECRET_KEY, }); ``` ## Python ```bash theme={null} pip install novu-py ``` ```python theme={null} import novu_py from novu_py import Novu with Novu( secret_key="YOUR_SECRET_KEY_HERE", ) as novu: ``` ## cURL All API requests require the `Authorization` header: ```bash theme={null} curl -X POST https://api.novu.co/v1/events/trigger \ -H "Authorization: ApiKey YOUR_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "workflow-id", "to": "subscriber-id", "payload": {} }' ``` **Note:** In the REST API, the trigger field is called `name` (not `workflowId`). The SDK maps `workflowId` to `name` automatically. # Single trigger examples Source: https://docs.novu.co/.mintlify/skills/trigger-notification/references/single-trigger-examples # Single Trigger Examples ## Basic Trigger ### Node.js ```typescript theme={null} import { Novu } from "@novu/api"; const novu = new Novu({ secretKey: process.env.NOVU_SECRET_KEY, }); const result = await novu.trigger({ workflowId: "welcome-email", to: "subscriber-123", payload: { userName: "Jane", companyName: "Acme Inc", }, }); console.log(result); ``` ### Python ```python theme={null} from novu_py import Novu from novu_py.models import TriggerEventRequestDto novu = Novu(security=Security(secret_key=os.environ["NOVU_SECRET_KEY"])) result = novu.trigger(request=TriggerEventRequestDto( workflow_id="welcome-email", to="subscriber-123", payload={ "userName": "Jane", "companyName": "Acme Inc", }, )) print(result) ``` ### cURL ```bash theme={null} curl -X POST https://api.novu.co/v1/events/trigger \ -H "Authorization: ApiKey $NOVU_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "welcome-email", "to": "subscriber-123", "payload": { "userName": "Jane", "companyName": "Acme Inc" } }' ``` ## Trigger with Inline Subscriber Auto-create or update the subscriber during trigger: ```typescript theme={null} const result = await novu.trigger({ workflowId: "welcome-email", to: { subscriberId: "user-456", email: "jane@example.com", firstName: "Jane", lastName: "Doe", phone: "+15551234567", avatar: "https://example.com/avatars/jane.jpg", locale: "en-US", data: { plan: "pro", signupSource: "landing-page", }, }, payload: { userName: "Jane" }, }); ``` ## Trigger with Actor Include the actor (who triggered the action) for use in templates: ```typescript theme={null} const result = await novu.trigger({ workflowId: "comment-notification", to: "post-author-123", payload: { commentText: "Great post!", postTitle: "Getting Started with Novu", }, actor: "commenter-456", }); ``` ## Trigger with Transaction ID For idempotency and cancellation support: ```typescript theme={null} import { randomUUID } from "crypto"; const transactionId = randomUUID(); const result = await novu.trigger({ workflowId: "order-confirmation", to: "customer-789", payload: { orderId: "order-001", total: "$99.99" }, transactionId, }); // Later, cancel if needed (only works for delayed/digested notifications) await novu.cancel(transactionId); ``` ## Trigger with Overrides Override provider-specific settings: ```typescript theme={null} const result = await novu.trigger({ workflowId: "alert-notification", to: "admin-001", payload: { message: "CPU usage above 90%" }, overrides: { "providers": { "sendgrid": { from: "alerts@example.com", cc: ["user1@example.com", "user2@example.com"], replyTo: "support@example.com", } } }, }); ``` ## Trigger with Context (Multi-Tenancy) Pass organizational context for multi-tenant applications: ```typescript theme={null} const result = await novu.trigger({ workflowId: "invoice-created", to: "user-123", payload: { invoiceId: "INV-001" }, context: { organizationId: "org-acme", }, }); ``` # Topic trigger examples Source: https://docs.novu.co/.mintlify/skills/trigger-notification/references/topic-trigger-examples # Topic Trigger Examples Topics let you send notifications to groups of subscribers. Create a topic, add subscribers, then trigger to the topic. ## Create a Topic and Add Subscribers ```typescript theme={null} import { Novu } from "@novu/api"; const novu = new Novu({ secretKey: process.env.NOVU_SECRET_KEY, }); // Create a topic await novu.topics.create({ key: "project-alpha-watchers", name: "Project Alpha Watchers", }); // Add subscribers to the topic await novu.topics.subscriptions.create( { subscriptions: ["user-1", "user-2", "user-3"] }, "project-alpha-watchers" ); ``` ## Trigger to a Topic All subscribers in the topic receive the notification: ```typescript theme={null} const result = await novu.trigger({ workflowId: "project-update", to: { type: "Topic", topicKey: "project-alpha-watchers", }, payload: { projectName: "Alpha", update: "New release v2.0 deployed", }, }); ``` ## Trigger to Multiple Topics ```typescript theme={null} const result = await novu.trigger({ workflowId: "company-announcement", to: [ { type: "Topic", topicKey: "engineering-team" }, { type: "Topic", topicKey: "product-team" }, ], payload: { announcement: "Company all-hands at 3pm", }, }); ``` ## cURL ```bash theme={null} curl -X POST https://api.novu.co/v1/events/trigger \ -H "Authorization: ApiKey $NOVU_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "project-update", "to": { "type": "Topic", "topicKey": "project-alpha-watchers" }, "payload": { "projectName": "Alpha", "update": "New release v2.0 deployed" } }' ``` ## Important Notes * Topics must be created before triggering to them * One subscriber can belong to multiple topics * Topic triggers fan out to all subscribed members individually * Duplicate subscribers across multiple topics in the same trigger are automatically deduplicated # AGENTS Source: https://docs.novu.co/AGENTS # Documentation project instructions ## About this project * Novu is the open-source notification infrastructure for in-app (Inbox), email, SMS, push, and chat * This is a documentation site built on [Mintlify](https://mintlify.com) * Pages are MDX files with YAML frontmatter * Configuration lives in `docs.json` * Use the Mintlify MCP server, `https://mcp.mintlify.com`, to edit content and settings via MCP * Use the Mintlify docs MCP server, `https://www.mintlify.com/docs/mcp`, to query information about using Mintlify via MCP ## Terminology Use Novu-specific terms consistently. For full definitions, see the [glossary](/platform/additional-resources/glossary). * Use **subscriber** (not "user") for notification recipients, identified by `subscriberId` * Use **workflow** for the notification flow definition; **step** for individual nodes; **trigger** for invocation * Use **channel** for delivery mediums: in-app/Inbox, email, SMS, push, and chat * Use **provider** for the delivery service behind a channel (for example, SendGrid for email, Twilio for SMS) * Use **Inbox** (capitalized) for the in-app notification component; avoid "notification center" * Use **topic** for grouping subscribers for bulk notifications * Use **tenant** for multi-tenant isolation when relevant using contexts feature * Use **integration** for a configured provider connection in Novu * Use **environment** for Development or Production contexts * Use **organization** for the top-level account in the Novu Dashboard * Use **layout** for email HTML wrappers; **digest** for aggregated notification batches * Distinguish **Novu Cloud** from self-hosted deployments, and **Community** vs **Enterprise** editions where relevant ## Style preferences * Use active voice and second person ("you") * Keep sentences concise — one idea per sentence * Use sentence case for headings * Bold for UI elements: Click **Settings** * Code formatting for file names, commands, paths, and code references * Capitalize **Novu** and product names: Inbox, Framework, Dashboard * Include frontmatter `title` and `description` on MDX pages * Use `sidebarTitle` for short navigation labels when the page `title` is long (for example, SEO question-format titles) * OpenAPI-backed API reference pages (`openapi: "METHOD /path"` in frontmatter) must **not** include a frontmatter `description` — Mintlify pulls the page description from the OpenAPI operation summary/description. Use `title` + `openapi` only, for example: ```mdx theme={null} --- title: "Create an agent" openapi: "POST /v1/agents" --- ``` * Optional 1–2 sentence intro prose before the OpenAPI block is fine on endpoint pages; do not duplicate that text as frontmatter `description` * API schema reference pages use markdown tables (`Field | Type | Description`), not ``. Escape union separators in the **Type** column as `\|` (for example, `` `string \| null` ``). Prefer `Record` over `{ [k: string]: any; }` in table cells. * Provider integration pages use the title pattern `{Provider} {Channel} Integration with Novu` with `sidebarTitle` for the short provider name * Use descriptive alt text on all diagrams and screenshots * See [SEO and GEO maintenance](/SEO_MAINTENANCE.md) for the ongoing review checklist * Use icons on top-level navigation section titles only (set `"icon"` on groups in `docs.json`), not on individual pages or nested collapsible groups * For icons we use the [Lucide](https://lucide.dev/) library. * Prefer Mintlify components (``, ``, ``, ``) over raw HTML ## API schema reference pages Pages under `docs/api-reference/**/**-schema.mdx` document resource field shapes for the API reference sidebar. * Use a **markdown table** with columns `Field`, `Type`, and `Description`. * Do **not** use `` — it is a legacy Mintlify component that is not supported in this docs setup and does not render reliably. * Follow the pattern in `docs/api-reference/agents/agent-schema.mdx` and `docs/api-reference/contexts/context-schema.mdx` (intro prose + table when listing fields). * OpenAPI-backed endpoint pages (`openapi: "METHOD /path"` in frontmatter) inherit request/response schemas from the spec; separate schema pages are only needed when you want a human-readable field glossary in the sidebar. ## AI prompt blocks Use the Mintlify `` component for pre-built AI prompts users can copy or open in Cursor. Write prompt text directly inside `` children — do not use ``, which copies as JSX instead of the prompt text. ```mdx theme={null} # Add Novu Inbox to Next.js App Install `@novu/nextjs`... ``` **When to use ``** * Integration setup where an AI assistant can implement code in the user's repo (Inbox, workflow triggers, webhooks, agent connect buttons) * MCP or skills pages where users paste operational prompts into connected AI tools * Do not use for in-product Copilot-style chat or one-line examples better suited to prose **Conventions** * Always set `actions={["copy", "cursor"]}` to match the Novu dashboard * Use Lucide icons: `sparkles` (integration), `bot` (MCP/skills), `zap` (workflows), `plug` (agents) * Use `YOUR_*` placeholders for dashboard-specific values (application identifier, subscriber ID, workflow ID) * Add a `` near the first prompt on a page telling users to substitute values from **API Keys**, **Subscribers**, or **Workflows** in the dashboard * Place prompts after prerequisites and adjacent to the code or setup steps they help implement ## Server-side SDK code examples When documenting REST API operations that developers call from backend code, show examples for **all official server-side SDKs** plus cURL. Do not default to Node.js and cURL only. **Official server-side SDKs** (see [SDK overview](/platform/sdks#server-side-sdks) and [API reference](/api-reference)): | Language | Package | Doc page | | - | - | - | | TypeScript / Node.js | `@novu/api` | `/platform/sdks/server/typescript` | | Python | `novu-py` | `/platform/sdks/server/python` | | Go | `github.com/novuhq/novu-go` | `/platform/sdks/server/go` | | PHP | `novuhq/novu` | `/platform/sdks/server/php` | | .NET | `Novu` | `/platform/sdks/server/dotnet` | | Java | `co.novu:novu-java` | `/platform/sdks/server/java` | **Tab order** — use `` with this consistent order: 1. `Node.js` 2. `Python` 3. `Go` 4. `PHP` 5. `.NET` 6. `Java` 7. `cURL` **Conventions** * Derive SDK examples from the corresponding SDK reference page and the [OpenAPI specification](https://api.novu.co/openapi.json). The REST field `name` maps to `workflowId` in SDKs. * Keep examples minimal and aligned across tabs — same workflow ID, subscriber ID, and payload shape. * Use `` or `NOVU_SECRET_KEY` placeholders; never hardcode real keys. * Community SDKs (Kotlin, Laravel, Ruby) do not need tabs on platform pages unless the page is SDK-specific. * Do not edit files under `docs/.mintlify/skills/` in this repo — they are synced from [novuhq/skills](https://github.com/novuhq/skills). Update trigger, subscriber, or preference skill examples there instead. ## Content boundaries * Document public platform features, SDKs, and API reference * Do not document internal admin features, enterprise-only implementation details, or unreleased features * Link to the [glossary](/platform/additional-resources/glossary) for term definitions rather than redefining them inline # SEO MAINTENANCE Source: https://docs.novu.co/SEO_MAINTENANCE # SEO and GEO maintenance This document defines the ongoing SEO and GEO (Generative Engine Optimization) maintenance process for [docs.novu.co](https://docs.novu.co). ## Monthly Google Search Console review 1. Open [Google Search Console](https://search.google.com/search-console) for `docs.novu.co`. 2. Review **Queries** for the notification infrastructure keyword cluster: * notification infrastructure * in-app notification component * notification API * Novu inbox * transactional notifications 3. Prioritize pages with **high impressions but low CTR** (rewrite title/description). 4. Prioritize pages with **low average position** on target queries (expand content depth, add internal links). 5. Submit or verify `https://docs.novu.co/sitemap.xml` in the Sitemaps report. ## Pre-deploy checklist Before merging documentation changes: * [ ] Every new MDX page has unique `title` and `description` frontmatter * [ ] API endpoint pages include a `description` and 1–2 sentence intro before the OpenAPI block * [ ] Provider pages use the `{Provider} {Channel} Integration with Novu` title pattern * [ ] Headings on key pages use question format where appropriate * [ ] Images include descriptive alt text * [ ] Run `mint broken-links` from the `docs/` directory (requires Mintlify CLI) * [ ] Run `mint score` to validate SEO/GEO signals including `robotsTxtAllowsAI` ## Quarterly AI citation testing Test these questions in ChatGPT, Perplexity, and Claude: 1. How do I authenticate API requests with Novu? 2. What are Novu API rate limits? 3. How do I add in-app notifications to a Next.js app? 4. What is Novu and what channels does it support? 5. How do Novu workflows work? 6. How do I send a transactional notification with Novu? 7. What is Novu Inbox? 8. How do I migrate from Knock to Novu? 9. Can I self-host Novu? 10. What is Agent Communication Infrastructure (ACI)? 11. How do I build a Vercel AI SDK agent with Novu Connect? 12. How do I build a LangChain agent with Novu Connect? 13. How do I build a Mastra agent with Novu Connect? 14. Which messaging channels does Novu Connect support for agents? For each response, verify: * Whether docs.novu.co is cited * Whether cited content is accurate * Whether code examples match current API patterns Log inaccurate citations and update the corresponding documentation page. ## Technical references * `llms.txt`: `https://docs.novu.co/llms.txt` (Mintlify auto-generated) * `sitemap.xml`: `https://docs.novu.co/sitemap.xml` * `robots.txt`: `https://docs.novu.co/robots.txt` * Mintlify SEO config: `docs.json` → `seo` block ## Target keyword ownership | Keyword cluster | Primary doc page | | - | - | | Open-source notification infrastructure | `/platform`, `/platform/what-is-novu` | | In-app notification component | `/platform/inbox`, `/platform/quickstart/nextjs` | | Multi-channel notification API | `/api-reference`, `/api-reference/events/trigger-event` | | Notification workflows | `/platform/concepts/workflows` | | Transactional notifications | `/guides/use-cases/transactional-notifications` | | Agent communication / ACI | `/agents`, `/agents/get-started/what-is-aci` | | Custom code agent (AI SDK) | `/agents/get-started/ai-sdk` | | Custom code agent (LangChain) | `/agents/get-started/langchain` | | Custom code agent (Mastra) | `/agents/get-started/mastra` | | Vercel AI SDK + Novu Connect agent | `/agents/get-started/ai-sdk` | | LangChain + Novu Connect agent | `/agents/get-started/langchain` | | Mastra + Novu Connect agent | `/agents/get-started/mastra` | | Agent channels (Slack, Teams, WhatsApp, Telegram, email) | `/agents/get-started/agents-and-providers` | | Self-host notifications | `/community/self-hosting-novu/overview` | | Novu vs competitors | `/guides/migrate-from-*` | # Novu Connect - Agent Communication Infrastructure (ACI) Source: https://docs.novu.co/agents Connect AI agents to Slack, Teams, WhatsApp, Telegram, and email. Route inbound messages, preserve conversation context, and deliver replies through Novu ACI. Novu Connect is based on the [Agent Communication Infrastructure (ACI)](/agents/get-started/what-is-aci). It ingests channel webhooks, normalizes events, maintains conversation state, and delivers replies so you can run one agent across Slack, Microsoft Teams, WhatsApp, Telegram, email, and in-app [Web Chat](/agents/channels/web-chat) without rebuilding each integration. ACI separates two layers: * **Communication infrastructure**: Webhook ingestion, message normalization, conversation state, identity resolution, and delivery. Owned by ACI. * **Agent intelligence**: Your LLM, prompts, tools, managed agent config, business logic, or custom runtime. Owned by you. ## Common patterns ### Inbound conversations Users message the agent on a connected channel (DM, @mention, email, or in-app Web Chat). Novu loads the conversation history and forwards it to your agent brain with the current turn. Replies go back to the same thread. ### Tool approval Before a sensitive tool runs, the agent can pause and post Approve / Deny in the channel. The turn resumes after the user decides. See [Tool approval](/agents/custom-code-agent/building-blocks/tool-approval). ## Connect your agent Choose how the agent brain runs: > [card] [Custom code](/agents/get-started/ai-sdk) > > AI SDK, LangChain, Mastra, or custom handlers on your bridge. > [card] [Claude managed agent](/agents/get-started/claude-managed) > > Anthropic Claude. No bridge server. > [card] [AWS Claude managed agent](/agents/get-started/aws-claude) > > Claude Platform on AWS. No bridge server. ### Frameworks > [card] [AI SDK](/agents/get-started/ai-sdk) > > `@novu/framework/ai-sdk` + Vercel AI SDK. > [card] [LangChain](/agents/get-started/langchain) > > `@novu/framework/langchain`. > [card] [Mastra](/agents/get-started/mastra) > > `@novu/framework` calling Mastra `generate()`. ### Channels > [card] [Slack](/agents/channels/slack) > > Typing, plan cards, Block Kit, tool approval. > [card] [Microsoft Teams](/agents/channels/microsoft-teams) > > Adaptive Cards, typing, tool approval. > [card] [WhatsApp](/agents/channels/whatsapp) > > Quick-reply buttons, session context. > [card] [Telegram](/agents/channels/telegram) > > Inline keyboards, typing, edit-in-place. > [card] [Email](/agents/channels/email) > > Threaded HTML, action-link approvals. > [card] [Web Chat](/agents/channels/web-chat) > > In-app headless hook, typing, tool approval. Platform differences are listed in [Channels overview](/agents/channels/overview). ## Message flow 1. A user sends a message on a connected channel. 2. Novu ingests the webhook, normalizes the event, and resolves identity. 3. Novu forwards the event and conversation history to your agent brain. 4. Your agent returns a reply (and may wait on tool approval). 5. Novu delivers the reply to the correct thread. 6. The conversation is stored and visible in the [Novu dashboard](https://dashboard.novu.co/agents). ## Learn more > [card] [What is ACI?](/agents/get-started/what-is-aci) > > Architecture and scope of the communication layer. > [card] [Mental model](/agents/get-started/mental-model) > > Inbound path from channel to agent and back. > [card] [Agents and providers](/agents/get-started/agents-and-providers) > > Agent entities and provider connections. > [card] [Channels overview](/agents/channels/overview) > > Feature support by platform. > [card] [Tool approval](/agents/custom-code-agent/building-blocks/tool-approval) > > Pause the turn until the user approves a tool call. > [card] [Conversation observability](/agents/conversations) > > Inspect live conversations in the dashboard. > [card] [Build the Web Chat UI](/agents/channels/web-chat) > > Headless `useWebChat` in your product UI. # Email Source: https://docs.novu.co/agents/channels/email Connect your agent to email: threaded HTML replies, action-link buttons, and tool approval. No typing indicator or plan card. Use email as a messaging channel for your agent. Novu preserves standard email threading, delivers HTML replies with action links, and can request tool approval in-thread. Email is request/response only: no typing indicator or plan card. ## Capabilities | Capability | Support | | - | - | | Full context history | Yes | | Threaded replies (email threading) | Yes | | Live typing indicator | No | | React with eyes on the original email | Yes | | Plan card | No | | Rich text | HTML | | Tap-to-respond | Yes (action links in the body) | | Emoji reactions | Gmail only (limited set) | | Message edits in place | No | | Action / MCP tool approval | Yes (action links) | | MCP connect card | Yes (action links) | | Resolve conversation | Yes | | File sharing | Not yet | | Streaming word-by-word | Not yet | | Quote reply | — | Full matrix: [Channels overview](/agents/channels/overview). ## Examples ### Inbound email A user emails the agent address. Novu reacts with eyes on the original message while the agent runs, then sends a threaded HTML reply with optional action links. ### Tool approval Gated tools send Approve / Deny action links in a follow-up email. The handler resumes after the user clicks a link. ## Setup | Framework / Platform | Guide | | - | - | | Custom code agent | Follow a [connect guide](/agents/get-started/ai-sdk), then add email as another provider | | Managed agent | [Claude](/agents/get-started/claude-managed) or [AWS Claude](/agents/get-started/aws-claude), then link email in the dashboard | Email provider credentials are configured in the Novu dashboard when you add the provider. ## Connect component `@novu/react` does not ship an email connect button. Email connections are address-based: configure the email provider on the agent in the dashboard (or via the [Agents API](/api-reference/agents/create-an-agent-integration)). Users reach the agent by emailing that address; threading is handled by ACI. For Slack, Teams, and Telegram embeddable buttons, see [Connect components](/agents/custom-code-agent/connect-components). ## Related > [card] [Reply](/agents/custom-code-agent/building-blocks/reply) > > HTML / markdown replies and action links. > [card] [Tool approval](/agents/custom-code-agent/building-blocks/tool-approval) > > Approve / Deny via action links. > [card] [Signals](/agents/custom-code-agent/building-blocks/signals) > > Resolve the conversation when the thread is done. > [card] [Channels overview](/agents/channels/overview) > > Compare providers. # Microsoft Teams Source: https://docs.novu.co/agents/channels/microsoft-teams Connect your agent to Microsoft Teams: threading, typing indicators, Adaptive Cards, and tool approval. Use Microsoft Teams as a messaging channel for your agent. Novu keeps conversation context, shows typing during the turn, can update a plan card in place, can attach files on replies, and posts Adaptive Card approvals for gated tools. ## Capabilities | Capability | Support | | - | - | | Full context history | Yes | | Threaded replies | Yes | | Live typing indicator (custom status text) | Yes | | React with eyes on inbound messages | Yes | | Plan card (markdown edit-in-place / Adaptive Card) | Yes | | Rich text / markdown | Yes | | Tap-to-respond buttons | Yes | | Emoji reactions | Yes | | Message edits in place | Yes | | Action / MCP tool approval | Yes | | MCP connect card | Yes | | Resolve conversation | Yes | | File sharing | Yes | | Streaming word-by-word | Not yet | | Quote reply | Plain post | Full matrix: [Channels overview](/agents/channels/overview). ## Examples ### Inbound chat A user messages the agent in Teams. Novu adds an eyes reaction, shows typing, updates a plan card while tools run, then replies with action buttons. ### Tool approval Gated tools surface as an Adaptive Card (**Deny**, **Approve once**, **Always allow this tool**). The turn resumes after the user selects an option. ## Setup | Framework / Platform | Guide | | - | - | | Custom code agent | Follow a [connect guide](/agents/get-started/ai-sdk), then add Teams as another provider on the same agent | | Managed agent | [Claude](/agents/get-started/claude-managed) or [AWS Claude](/agents/get-started/aws-claude), then link Teams in the dashboard | Teams provider credentials and app packaging are configured in the Novu dashboard when you add the Microsoft Teams provider. ## Distribute to other tenants Teams has no equivalent of Slack's Public Distribution. Novu installs the app in your own Microsoft 365 tenant during setup. Every other tenant, including each customer's, must make the same app package available before its users can connect. 1. **Download the app package.** In the Novu dashboard, open the Teams integration on your agent and download the multi-tenant app package. The same package works in every tenant. 2. **Upload it in each tenant.** A Teams admin opens **Teams admin center → Teams apps → Manage apps**, chooses **Actions → Upload new app**, and confirms its status is **Allowed**. 3. **Allow it in the permission policy.** In **Teams apps → Permission policies**, the admin allows custom apps, or allowlists this app, in the policy assigned to users. If this step is skipped, users see "This app is not available". 4. **Grant admin consent.** A Global Admin of each tenant opens the admin consent link shown in the dashboard once. 5. **Users connect from your app.** Users in that tenant connect with `MsTeamsConnectButton`, and the bot installs for them. Changes can take up to 24 hours to propagate. To distribute to many customers without sharing the package with each tenant, [publish the app to the Microsoft Teams Store](https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/deploy-and-publish/apps-publish-overview). ## Connect component Use `MsTeamsConnectButton` from `@novu/react` so end users can admin-consent and link Teams to your agent from your product UI. In subscriber mode, `autoLinkUser` defaults to `true` so the per-user Teams identity is linked after consent. Render it on an authenticated page and pass the signed-in user's id as `subscriberId`. See [Connect components in production](/agents/custom-code-agent/connect-components#use-connect-components-in-production). ```tsx theme={null} import { NovuProvider, MsTeamsConnectButton } from '@novu/react'; // userId: the signed-in user's id from your app's auth session export function TeamsConnect({ userId }: { userId: string }) { const subscriberId = userId; const integrationIdentifier = 'msteams-integration-identifier'; return ( { // Workspace linked }} onConnectError={(error: unknown) => { console.error(error); }} /> ); } ``` If auto-link fails after consent, use `MsTeamsLinkUser` as a follow-up step. Full prop reference: [Connect components](/agents/custom-code-agent/connect-components#microsoft-teams-connect-button). ## Related > [card] [Reply](/agents/custom-code-agent/building-blocks/reply) > > Plain text, markdown, and interactive cards. > [card] [Typing indicator](/agents/custom-code-agent/building-blocks/typing-indicator) > > Custom status text while the handler runs. > [card] [Tool approval](/agents/custom-code-agent/building-blocks/tool-approval) > > Approve / Deny before tools execute. > [card] [Edit sent messages](/agents/custom-code-agent/building-blocks/edit-sent-messages) > > Update a sent message in place. > [card] [Connect components](/agents/custom-code-agent/connect-components) > > MsTeamsConnectButton and MsTeamsLinkUser. # Overview Source: https://docs.novu.co/agents/channels/overview Feature support matrix for Novu Connect on Slack, Microsoft Teams, WhatsApp, Telegram, email, and Web Chat. Novu normalizes inbound events and outbound replies, but each provider exposes a different subset of UI features. Use this matrix when implementing replies, typing, edits, and tool approval. ## Supported capabilities | Capability | Slack | Teams | WhatsApp | Telegram | Email | Web Chat | | - | - | - | - | - | - | - | | Full context history | Yes | Yes | Yes | Yes | Yes | Yes | | Threaded replies | Yes | Yes | Yes | Yes | Yes | Yes | | Live typing indicator | Yes | Yes | Yes | Yes | No | Yes | | React with eyes on new message | Yes | Yes | Yes | Yes | Yes | No | | Plan card (chain of thought) | Yes (native) | Markdown edit-in-place | No | Markdown edit-in-place | No | Yes (thinking parts) | | Rich text styling | Yes | Yes | Bold / italics | Yes | HTML | Yes (your UI) | | Tap-to-respond (buttons) | Yes | Yes | Yes (up to 3) | Yes | Yes (action links) | Yes | | Emoji reactions | Yes | Yes | Yes | Yes | Gmail only | No | | Message edits in place | Yes | Yes | Yes | Yes | No | Yes | | Action / tool approval | Yes | Yes | Yes | Yes | Yes | Yes | | MCP tool approval | Yes | Yes | Yes | Yes | Yes | Yes | | MCP connect card | Yes | Yes | Yes | Yes | Yes | Yes | | Resolve conversation | Yes | Yes | Yes | Yes | Yes | Yes | | Message queueing | Yes | Yes | Yes | Yes | Yes | Yes | | Outbound file attachments | Yes | Yes | Not yet | Not yet | Not yet | Yes (file parts) | | Quote reply | Plain post | Plain post | Native | Native | — | — | Replies stream word by word on Slack, Telegram, and Web Chat. On Teams, WhatsApp, and email the reply arrives once it is complete. ## Channel pages > [card] [Slack](/agents/channels/slack) > > Block Kit, native plan cards, tool approval. > [card] [Microsoft Teams](/agents/channels/microsoft-teams) > > Adaptive Cards, typing, tool approval. > [card] [WhatsApp](/agents/channels/whatsapp) > > Quick-reply buttons, session context. > [card] [Telegram](/agents/channels/telegram) > > Inline keyboards, edit-in-place plans. > [card] [Email](/agents/channels/email) > > Threaded HTML, action-link approvals. > [card] [Web Chat](/agents/channels/web-chat) > > In-app headless hook, typing, tool approval. ## Building blocks Each building block page lists channel support for that API: * [Reply](/agents/custom-code-agent/building-blocks/reply) * [Typing indicator](/agents/custom-code-agent/building-blocks/typing-indicator) * [Edit sent messages](/agents/custom-code-agent/building-blocks/edit-sent-messages) * [Tool approval](/agents/custom-code-agent/building-blocks/tool-approval) * [Signals](/agents/custom-code-agent/building-blocks/signals) * [Handlers and context](/agents/custom-code-agent/building-blocks/handle-events) # Slack Source: https://docs.novu.co/agents/channels/slack Connect your agent to Slack: threading, typing indicators, plan cards, Block Kit, and tool approval. Use Slack as a messaging channel for your agent. Users can DM or @mention the bot. Novu keeps thread context, shows typing and plan cards during the turn, can attach files on replies, and can post Approve / Deny cards before gated tools run. Connect it from the [Setup](#setup) section. ## Capabilities | Capability | Support | | - | - | | Full context history | Yes | | Threaded replies | Yes | | Live typing indicator (custom status text) | Yes | | React with eyes on inbound messages | Yes | | Plan card (native) | Yes | | Rich text / Block Kit | Yes | | Tap-to-respond buttons | Yes | | Emoji reactions (both directions) | Yes | | Message edits in place | Yes | | Action / MCP tool approval | Yes | | MCP connect card | Yes | | Resolve conversation | Yes | | File sharing | Yes | | Streaming word-by-word | Yes | | Quote reply | Plain post | Full matrix: [Channels overview](/agents/channels/overview). ## Examples ### Inbound thread A user @mentions the agent in a thread. Novu adds an eyes reaction, shows typing and a plan card while the agent runs tools, then replies in the same thread with optional action buttons. ### Tool approval When a tool is gated, Slack shows a native approval block (**Deny**, **Approve once**, **Always allow this tool**). The handler resumes after the user selects an option. ## Create a Slack app When the dashboard or CLI asks for a Slack App Configuration Token: 1. Open [Slack API apps](https://api.slack.com/apps). 2. Under **Your App Configuration Tokens**, click **Generate Token**. ![Generate Slack token](https://mintcdn.com/novu-c5de82d9/GgsvkDH1Mx055NRY/images/agents/quickstart/generate-slack-token.png?fit=max\&auto=format\&n=GgsvkDH1Mx055NRY\&q=85\&s=3317c804540eb819472823bd49592682) 3. Select your workspace and click **Generate**. 4. Copy the token (starts with `xoxe.xoxp-`) and paste it into Novu or the CLI. 5. Finish the install / Allow flow in Slack. ![Install app](https://mintcdn.com/novu-c5de82d9/GgsvkDH1Mx055NRY/images/agents/quickstart/install-app.png?fit=max\&auto=format\&n=GgsvkDH1Mx055NRY\&q=85\&s=c1cc531047e6a1e0c5e3d4dcd2d9e0cc) The configuration token is used once to create the Slack app. Novu does not store it. ## Distribute to other workspaces A Slack app only works in the workspace where it was created. Users in any other workspace are blocked when they click your connect button until you enable Public Distribution. 1. Open your app in [Slack API apps](https://api.slack.com/apps). 2. Go to **Manage Distribution**. 3. Complete the checklist and click **Activate Public Distribution**. Novu does not turn this on for you. Public Distribution is a manual setting in Slack, and the app manifest that Novu generates leaves it off. ## Setup | Framework / Platform | Guide | | - | - | | AI SDK | [Connect AI SDK to Slack](/agents/get-started/ai-sdk) | | LangChain | [Connect LangChain to Slack](/agents/get-started/langchain) | | Mastra | [Connect Mastra to Slack](/agents/get-started/mastra) | | Claude managed agent | [Connect Claude managed agent](/agents/get-started/claude-managed) | | AWS Claude managed agent | [Connect AWS Claude managed agent](/agents/get-started/aws-claude) | ## Connect component Use `SlackConnectButton` from `@novu/react` so end users can install the Slack app and link it to your agent from your product UI. Render it on an authenticated page and pass the signed-in user's id as `subscriberId`. See [Connect components in production](/agents/custom-code-agent/connect-components#use-connect-components-in-production). ```tsx theme={null} import { NovuProvider, SlackConnectButton } from '@novu/react'; // userId: the signed-in user's id from your app's auth session export function SlackConnect({ userId }: { userId: string }) { const subscriberId = userId; const integrationIdentifier = 'slack-integration-identifier'; const agentIdentifier = 'agent-identifier'; return ( { // Workspace linked }} onConnectError={(error: unknown) => { console.error(error); }} /> ); } ``` Props and appearance options: [Connect components](/agents/custom-code-agent/connect-components#slack-connect-button). ## Related > [card] [Reply](/agents/custom-code-agent/building-blocks/reply) > > Plain text, markdown, and interactive cards. > [card] [Typing indicator](/agents/custom-code-agent/building-blocks/typing-indicator) > > Custom status text while the handler runs. > [card] [Tool approval](/agents/custom-code-agent/building-blocks/tool-approval) > > Approve / Deny before tools execute. > [card] [Edit sent messages](/agents/custom-code-agent/building-blocks/edit-sent-messages) > > Update a sent message in place. > [card] [Connect components](/agents/custom-code-agent/connect-components) > > SlackConnectButton props and appearance. # Telegram Source: https://docs.novu.co/agents/channels/telegram Connect your agent to Telegram: threading, typing indicators, inline keyboards, edit-in-place plans, and tool approval. Use Telegram as a messaging channel for your agent. Novu keeps conversation context, shows typing during the turn, can update a plan card in place, and uses inline keyboard buttons for choices and tool approval. ## Capabilities | Capability | Support | | - | - | | Full context history | Yes | | Threaded replies | Yes | | Live typing indicator (custom status text) | Yes | | React with eyes on inbound messages | Yes | | Plan card (markdown edit-in-place) | Yes | | Rich text / markdown | Yes | | Tap-to-respond buttons (inline keyboard) | Yes | | Emoji reactions | Yes | | Message edits in place | Yes | | Action / MCP tool approval | Yes | | MCP connect card | Yes | | Resolve conversation | Yes | | File sharing | Not yet | | Streaming word-by-word | Yes | | Quote reply | Native | Full matrix: [Channels overview](/agents/channels/overview). ## Examples ### Inbound message A user messages the bot. Novu adds an eyes reaction, shows typing with optional custom status text, updates a plan card while tools run, then replies with inline keyboard buttons. ### Tool approval Gated tools post Approve once / Deny / Always allow. The handler resumes after the user selects an option. ## Setup | Framework / Platform | Guide | | - | - | | Custom code agent | Follow a [connect guide](/agents/get-started/ai-sdk), then add Telegram as another provider | | Managed agent | [Claude](/agents/get-started/claude-managed) or [AWS Claude](/agents/get-started/aws-claude), then link Telegram in the dashboard | ## Connect component Use `TelegramConnectButton` from `@novu/react` so end users can link their Telegram chat to your agent. The button issues a `t.me/?start=` deep link, opens it, and polls until the user presses **Start** in Telegram. Render it on an authenticated page and pass the signed-in user's id as `subscriberId`. See [Connect components in production](/agents/custom-code-agent/connect-components#use-connect-components-in-production). ```tsx theme={null} import { NovuProvider, TelegramConnectButton } from '@novu/react'; // userId: the signed-in user's id from your app's auth session export function TelegramConnect({ userId }: { userId: string }) { const subscriberId = userId; const integrationIdentifier = 'telegram-integration-identifier'; return ( { console.log('Connected', endpointIdentifier); }} onConnectError={(error: unknown) => { console.error(error); }} onDisconnectSuccess={() => { // Chat unlinked }} /> ); } ``` Props and appearance options: [Connect components](/agents/custom-code-agent/connect-components#telegram-connect-button). ## Related > [card] [Reply](/agents/custom-code-agent/building-blocks/reply) > > Plain text, markdown, and interactive cards. > [card] [Typing indicator](/agents/custom-code-agent/building-blocks/typing-indicator) > > Custom status text while the handler runs. > [card] [Tool approval](/agents/custom-code-agent/building-blocks/tool-approval) > > Approve / Deny before tools execute. > [card] [Edit sent messages](/agents/custom-code-agent/building-blocks/edit-sent-messages) > > Update a sent message in place. > [card] [Connect components](/agents/custom-code-agent/connect-components) > > TelegramConnectButton props and appearance. # Web Chat Source: https://docs.novu.co/agents/channels/web-chat Add the Web Chat channel, install @novu/react, and send a first message in your product UI. Web Chat is how you embed an agent inside your own app. It is an [Agent Communication Infrastructure (ACI)](/agents/get-started/what-is-aci) channel, the same layer Slack and Teams use, except you own the surface: message list, composer, and layout. The React client is [`useWebChat`](/platform/sdks/react/hooks/use-web-chat) from `@novu/react`. There is no prebuilt `` component. If you are not on React, use [`conversation()`](/platform/sdks/javascript#web-chat) from `@novu/js`. ## Setup Create an agent and keep it **active**. Then add the channel in the dashboard: 1. Open the agent in the Novu dashboard. 2. Add **Web Chat**. Novu creates the `novu-web-chat` integration if it is missing. ## Install Collect these values from the dashboard, then install `@novu/react`: * Application identifier from [API Keys](https://dashboard.novu.co/api-keys) * A [subscriber](/platform/additional-resources/glossary) id for the signed-in person * The public agent identifier from the agent page ```package-install theme={null} npm install @novu/react ``` > [!NOTE] > > `@novu/react` requires React 18 or later (`^18.0.0` or `^19.0.0`). Place `NovuProvider` above the chat. `useWebChat` gets the Novu client from that context. > [tab] US > > ```tsx theme={null} > import { NovuProvider } from '@novu/react'; > > export function App() { > return ( > applicationIdentifier="YOUR_APPLICATION_IDENTIFIER" > subscriber="YOUR_SUBSCRIBER_ID" > > > > > ); > } > ``` > [tab] EU > > ```tsx theme={null} > import { NovuProvider } from '@novu/react'; > > export function App() { > return ( > applicationIdentifier="YOUR_APPLICATION_IDENTIFIER" > subscriber="YOUR_SUBSCRIBER_ID" > apiUrl="https://eu.api.novu.co" > socketUrl="wss://eu.socket.novu.co" > > > > > ); > } > ``` `NovuProvider` signs the subscriber in. `useWebChat` selects which agent to talk to. > [!NOTE] > > Replace `YOUR_*` placeholders with values from [API Keys](https://dashboard.novu.co/api-keys) and [Subscribers](/platform/additional-resources/glossary). Add Novu Web Chat to my React app # Add Novu Web Chat to a React app Install `@novu/react`. Wrap the app in `NovuProvider`. Call `useWebChat` and render your own message list and composer. There is no prebuilt `` component. Canonical example: [https://docs.novu.co/agents/channels/web-chat](https://docs.novu.co/agents/channels/web-chat) ALWAYS: * Detect the project's package manager and use it for installation * Use `NovuProvider` from `@novu/react` (not a second Novu client) * Pass the dashboard agent identifier as `agentId` * Disable the composer while `isRunning` or `isLoading` is true * Use TypeScript, no comments, no empty props NEVER: * Invent a `` component from `@novu/react`. It does not exist. * Use `useChat` from `@ai-sdk/react`. Web Chat uses `useWebChat`. * Compute HMAC hashes in the browser * Hardcode real API keys ## Send a first message Call `useWebChat` inside `NovuProvider`. Render text parts, then send with `sendMessage`. ```tsx theme={null} const { messages, sendMessage, isRunning, isLoading, error } = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER', }); ``` ```tsx theme={null} {error ?

{error.message}

: null}
    {messages.map((message) => (
  • {message.role}{' '} {message.parts.map((part, index) => part.type === 'text' ? ( {part.text} ) : null )}
  • ))}
``` ```tsx theme={null}
{ event.preventDefault(); const form = event.currentTarget; const input = form.elements.namedItem('text') as HTMLInputElement; void sendMessage(input.value); form.reset(); }} > ``` Omit `conversationId` to start a new chat. The first successful send creates the conversation. ## What to read next > [card] [Messages](/agents/channels/web-chat/messages) > > Render message parts in the timeline. > [card] [Tools](/agents/channels/web-chat/tools) > > Tool calls, approval, and MCP connect. > [card] [Generative UI](/agents/channels/web-chat/generative-ui) > > Custom data parts and structured UI. > [card] [Conversations](/agents/channels/web-chat/conversations) > > Resume chats, load history, and reconnect. > [card] [assistant-ui](/agents/channels/web-chat/recipes/assistant-ui) > > Build with the assistant-ui library. > [card] [Security](/agents/channels/web-chat/security) > > HMAC hashes before you ship to production. > [card] [useWebChat](/platform/sdks/react/hooks/use-web-chat) > > Hook props, return value, and callbacks. > [card] [JavaScript SDK](/platform/sdks/javascript#web-chat) > > Call `loadWebChat(novu)`, then `novu.webChat.conversation()` in `@novu/js`. # Conversations Source: https://docs.novu.co/agents/channels/web-chat/conversations List, resume, page, reconnect, and retry Web Chat conversations. Start from [Send a first message](/agents/channels/web-chat#send-a-first-message). This page covers listing conversations, resuming them, paging history, reconnect, and retry. `useWebChat` has no list helper. Use `novu.webChat.listConversations` to build a conversation sidebar or history screen. ## List Call `novu.loadWebChat()`, then `novu.webChat.listConversations` on the client from [`useNovu`](/platform/sdks/react/hooks/use-novu). `useWebChat` loads Web Chat for the chat UI only. Each row is a `WebChatConversation` with these fields: `identifier`, `title`, `status`, `agentIdentifier`, `lastActivityAt`, and `createdAt`. ```tsx theme={null} const novu = useNovu(); await novu.loadWebChat(); const { data, error } = await novu.webChat.listConversations({ limit: 10, orderBy: 'lastActivityAt', orderDirection: 'DESC', }); ``` `data.conversations` is the page. Use `data.next` and `data.previous` with `after` and `before` to page older lists. When a row is selected, pass `item.identifier` as `conversationId` and `item.agentIdentifier` as `agentId` on `useWebChat`. Match the agent to the conversation. ## Start or resume Pass `conversationId` so the hook loads history on mount. ```tsx theme={null} function Chat({ conversationId }: { conversationId?: string }) { const { sendMessage } = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER', conversationId, }); async function onSend(text: string) { const { data } = await sendMessage(text); if (data?.conversationId) { storeConversationId(data.conversationId); } } } ``` Store the `conversationId` that `sendMessage` returns, or the `conversationId` field on the hook result. On the next visit, pass that id back in, or pick a row from [List](#list). To start another chat without a `conversationId` prop, call `startNewConversation()` from the hook. It clears the current timeline and opens an empty chat in place, so the component does not remount. The next `sendMessage` creates the new server conversation. ```tsx theme={null} const { startNewConversation } = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER', }); ``` `startNewConversation()` is a no-op when you pass `conversationId` or a shared `conversation` runtime. In those cases, switch chats by changing the `conversationId` you pass in, or remount the component. `agentId` selects the agent. If the identifier changes, remount with the new `agentId`. Omit `conversationId` unless that conversation belongs to the new agent. A conversation id from a different agent does not resume. ## Older messages If `pagination.hasMore` is true, call `pagination.fetchMore()` to load an older page. ```tsx theme={null} const { pagination } = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER', conversationId, }); {pagination.hasMore ? ( ) : null} ``` Overlapping `fetchMore` calls do not run. ## Reconnect The hook reconnects and applies missed events on its own. Show a banner from these fields. ```tsx theme={null} const { isRecovering, catchUpError } = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER', conversationId, }); {isRecovering ?

Reconnecting…

: null} {catchUpError ?

{catchUpError.message}

: null} ``` `catchUpError` is separate from send and fetch `error`. `conversationStatus` does not become an error state when recovery fails. ## Retry If `message.status` is `failed`, call `retryMessage` with that message id. Retry reuses the original idempotency key. It does not create a second message with the same text. ```tsx theme={null} const { messages, retryMessage } = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER', }); {messages.map((message) => (
  • {message.parts.map((part, index) => part.type === 'text' ? {part.text} : null )} {message.status === 'failed' ? ( ) : null}
  • ))} ``` ## Resolved `conversationStatus` on `useWebChat` is `active` or `resolved`. Do not use it to disable the composer. The agent marks a conversation resolved with [`ctx.resolve()`](/agents/custom-code-agent/building-blocks/signals#resolve-a-conversation). `conversationStatus` becomes `resolved`. When the subscriber sends the next message, the conversation reopens and `conversationStatus` becomes `active` again. Use `conversationStatus` for badges or labels in your UI. Keep the composer enabled unless `isRunning` or `isLoading` is true. Inspect resolved conversations in the [Novu dashboard](/agents/conversations). # Generative UI Source: https://docs.novu.co/agents/channels/web-chat/generative-ui Render Web Chat cards, handle card buttons, and show custom data parts. Handle structured assistant output in Web Chat: cards and custom data parts. See [Messages](/agents/channels/web-chat/messages) for the timeline. See [Tools](/agents/channels/web-chat/tools) for approvals. ## Cards A Card is a structured reply. It can include a title, text, images, links, and buttons. When the agent sends a Card, the message includes a part with `type: 'card'`. The payload is on `part.card`. Agents create Cards with JSX or `Card({…})`. That authoring API is shared with Slack and the other [Agent Communication Infrastructure (ACI)](/agents/get-started/what-is-aci) channels: [Interactive cards](/agents/custom-code-agent/building-blocks/reply#interactive-cards). You can also post the JSON with [Send an agent reply](/api-reference/agents/send-an-agent-reply). `part.card` is `Record`. Read the fields that you support. Skip child types that you do not use. Render `title` and the `text` children that you support: ```tsx theme={null} const { messages } = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER', }); {messages.map((message) => message.parts.map((part, i) => { if (part.type !== 'card') { return null; } const title = typeof part.card.title === 'string' ? part.card.title : null; const children = Array.isArray(part.card.children) ? part.card.children : []; return (
    {title ?

    {title}

    : null} {children.map((child, j) => child?.type === 'text' ? (

    {child.content}

    ) : null )}
    ); }) )} ``` ## Card buttons If the subscriber clicks a button, call `sendAction`. The agent receives the click in `onAction`. Do not send the button label with `sendMessage`. That call creates a new chat message. Do not call `respondToAction`. That function is for tool approval only. In the same `children` loop, handle `type === 'actions'`: ```tsx theme={null} const { sendAction } = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER', }); {child?.type === 'actions' ? child.children?.map((button) => ( )) : null} ``` ## Custom data The agent sends a named payload with [`ctx.emit`](/agents/custom-code-agent/building-blocks/emit). Web Chat adds it to the in-flight assistant message as `part.type === 'data'`. The fields are `name` and `data`. See [Emit custom events](/agents/custom-code-agent/building-blocks/emit) for the handler API, size limit, and other channels. Render parts whose `name` your UI handles: ```tsx theme={null} const { messages } = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER', }); {messages.map((message) => message.parts.map((part, index) => { if (part.type !== 'data') { return null; } return (
            {part.name}: {JSON.stringify(part.data)}
          
    ); }) )} ``` Skip `data` parts with names that your UI does not handle. The part stays on the message. # Messages Source: https://docs.novu.co/agents/channels/web-chat/messages Render the Web Chat timeline: hook state, errors, text, and thinking. Start from [Send a first message](/agents/channels/web-chat#send-a-first-message). This page covers the timeline after that first bubble. `messages` is the ordered timeline. Each message has `role` (`user` or `assistant`) and `parts`. A part is one block in the message, such as text or thinking. See [`useWebChat`](/platform/sdks/react/hooks/use-web-chat) for the full type list. ## State Use these fields to drive the composer, spinner, and error banner: | Field | What you do | | - | - | | `isLoading` | First history fetch. False when there is no `conversationId`. Show a spinner. | | `isRunning` | Agent turn in progress. Disable the composer. `typing` is optional status text. | | `conversationStatus` | Conversation is `active` or `resolved`. Do not use it to disable the composer. | | `error` | Last load, send, retry, action, or run error. Show the message. | | `message.status` | `sending`, `sent`, or `failed`. If `failed`, call `retryMessage`. See [Retry](/agents/channels/web-chat/conversations#retry). | ## Errors `error` is the last failure from load, send, retry, or action. Show `error.message`. `sendMessage`, `respondToAction`, `sendAction`, and `retryMessage` do not throw. A `try/catch` around them does not run. Wait for the result and read `error` on that call: ```tsx theme={null} const result = await sendMessage(text); if (result.error) { return result.error.message; } ``` When the organization is over a plan limit, `error` is a [`WebChatPlanLimitError`](/platform/sdks/react/hooks/use-web-chat#plan-limit-error). The HTTP status is `402`. Read `reason` (`agents`, `channels`, or `conversations`) and show `message`. ## Text Start with `type === 'text'`. That is the visible body of the row. ```tsx theme={null} const { messages } = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER' }); {messages.map((message) => (
  • {message.parts.map((part, index) => part.type === 'text' ? {part.text} : null )}
  • ))} ``` ## Thinking `isRunning` is true for the whole agent turn. `typing` is present only while the agent types. Assistant messages can also include `thinking` parts before text arrives. `run` is an alias for the same snapshot: `isRunning` is `run.isRunning`, and `typing` is `run.typing`. Show a status line while the turn runs: ```tsx theme={null} const { messages, isRunning, typing } = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER', }); {isRunning ?

    {typing?.status ?? 'Working…'}

    : null} ``` Then render `thinking` parts next to text: ```tsx theme={null} {messages.map((message) => message.parts.map((part, index) => { if (part.type === 'thinking') { return {part.text}; } if (part.type === 'text') { return {part.text}; } return null; }) )} ``` The first event of a turn can create an empty assistant message before any text arrives. Keep that row in the list. Then fill it as parts arrive. # Use assistant-ui Source: https://docs.novu.co/agents/channels/web-chat/recipes/assistant-ui Use assistant-ui components with useWebChat. Novu holds the conversation; assistant-ui draws the UI. [assistant-ui](https://www.assistant-ui.com/) is a React library for chat UIs. Novu does not ship a `` component, so you can keep [`useWebChat`](/platform/sdks/react/hooks/use-web-chat) as the conversation and use any assistant-ui primitive, element, or part renderer you want on top. The sections below are hints for common pieces (`Thread`, composer, reasoning, tools, custom UI). They are not the full assistant-ui surface. ## The split `useWebChat` holds the conversation: `messages`, `sendMessage`, `respondToAction`, `sendAction`, `isRunning`, and `isLoading`. assistant-ui draws whatever you mount: `Thread`, `ThreadList`, composer, action bars, tool UIs, attachments, your own `makeAssistantDataUI` renderers, and the rest of the library. `useExternalStoreRuntime` is the glue. assistant-ui normally talks to its own backend. This runtime lets you feed it Novu instead. ## Thread Convert Novu messages into assistant-ui thread messages, then wrap `Thread` in that runtime. Add a Thread UI from assistant-ui first (their [Thread](https://www.assistant-ui.com/docs/primitives/thread), or `npx shadcn@latest add @assistant-ui/thread`). Change the `Thread` import path to match your app. Start with text. Add `reasoning`, `tool-call`, or `data` cases as you need them: ```tsx theme={null} import type { AgentMessage } from '@novu/react'; import type { ThreadMessageLike } from '@assistant-ui/react'; function toThreadMessage(message: AgentMessage): ThreadMessageLike { const text = message.parts .filter((part) => part.type === 'text') .map((part) => part.text) .join(''); return { id: message.id, role: message.role, createdAt: new Date(message.createdAt), content: [{ type: 'text', text }], }; } ``` ```tsx theme={null} import { useWebChat } from '@novu/react'; import { AssistantRuntimeProvider, useExternalMessageConverter, useExternalStoreRuntime, } from '@assistant-ui/react'; import { Thread } from '@/components/assistant-ui/thread'; const chat = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER' }); const messages = useExternalMessageConverter({ callback: toThreadMessage, messages: chat.messages, isRunning: chat.isRunning, joinStrategy: 'none', }); const runtime = useExternalStoreRuntime({ messages, isRunning: chat.isRunning, isLoading: chat.isLoading, onNew: async (message) => { /* see Composer */ }, }); return ( ); ``` ## Composer When the subscriber sends, assistant-ui calls `onNew`. Read the text and pass it to Novu. Do not start a second chat client. ```tsx theme={null} onNew: async (message) => { const text = message.content .filter((part) => part.type === 'text') .map((part) => part.text) .join(''); if (text.trim()) await chat.sendMessage(text); }, ``` Disable the composer with `isRunning` or `isLoading` on the runtime (`isDisabled`) if you want the same behavior as the [first-message](/agents/channels/web-chat#send-a-first-message) form. ## Reasoning A Novu `thinking` part is the agent's reasoning while the turn runs. Map it to assistant-ui `reasoning` so `Thread` can collapse it. ```tsx theme={null} if (part.type === 'thinking' && part.text.trim()) { return { type: 'reasoning', text: part.text }; } ``` See [Thinking](/agents/channels/web-chat/messages#thinking) for the Novu fields. ## Tool UI A `tool` part is a call that already ran. Map it to `tool-call` and let assistant-ui `ToolFallback` (or your own tool renderer) show the name, args, and result. ```tsx theme={null} if (part.type === 'tool') { return { type: 'tool-call', toolCallId: part.toolUseId, toolName: part.toolName, argsText: JSON.stringify(part.input ?? {}), result: part.output, }; } ``` A pending `approval` is the same `tool-call` shape, plus an `approval` object. When the subscriber picks Approve or Deny, `onRespondToToolApproval` must call `respondToAction`: ```tsx theme={null} onRespondToToolApproval: async ({ approvalId, approved }) => { await chat.respondToAction({ approvalId, decision: approved ? 'approved' : 'denied', }); }, ``` See [Tools](/agents/channels/web-chat/tools) for the Novu actions. For MCP connect, open `authorizeUrl` in a custom part UI. Do not send that through `respondToAction`. ## Custom UI Novu cards and `ctx.emit` payloads are not assistant-ui types. Send them through as named `data` items and register a renderer with `makeAssistantDataUI`. ```tsx theme={null} if (part.type === 'card') { return { type: 'data', name: 'novu-card', data: { ...part, sourceMessageId: message.id }, }; } ``` ```tsx theme={null} const NovuCardUI = makeAssistantDataUI({ name: 'novu-card', render: ({ data }) => ( void chat.sendAction({ actionId, value, sourceMessageId: data.sourceMessageId, }) } /> ), }); ``` Mount `NovuCardUI` next to `Thread` (assistant-ui picks it up by `name`). Button clicks must call `sendAction`, not `sendMessage`. See [Generative UI](/agents/channels/web-chat/generative-ui). The same slot works for your own `ctx.emit` names. Register one `makeAssistantDataUI` per `name` you want to draw. ## Full example The [Web Chat connect template](https://github.com/novuhq/novu/tree/next/packages/novu/src/commands/connect/templates/web-chat/ts) is a complete reference: converter, Thread, cards, approvals, and a sidebar. Run `npx novu connect --channel web-chat` to copy it into an app. The `WebChat` component in that output is scaffold code. It is not exported from `@novu/react`. # Security Source: https://docs.novu.co/agents/channels/web-chat/security Turn on HMAC for Web Chat before you ship: subscriberHash on NovuProvider, agentHash on useWebChat, and contextHash to pass context to your agent. HMAC (Hash-based Message Authentication Code) is off by default. Turn it on before you ship. Web Chat can require up to three hashes, controlled by two dashboard toggles. | Hash | Toggle | Input | Where the client passes it | | - | - | - | - | | `subscriberHash` | **Novu In-App** integration | `subscriberId` | `NovuProvider` | | `contextHash` | **Novu In-App** integration | `context` | `NovuProvider`, only when you pass `context` | | `agentHash` | **Web Chat** integration | agent identifier | `useWebChat` | All hashes use the environment API secret from [API Keys](https://dashboard.novu.co/api-keys). Compute them on your server. Do not compute them in the browser. Pass the hashes for the toggles that are on. With **Novu In-App** HMAC on, `subscriberHash` is always required, and `contextHash` is required whenever you pass `context`. ## subscriberHash `subscriberHash` authenticates the signed-in subscriber. Without it, another person can guess a `subscriberId` and open that subscriber's session, including Web Chat. If **Security HMAC encryption** is on for **Novu In-App**, pass `subscriberHash` to `NovuProvider`. The hash is `HMAC-SHA256(secretKey, subscriberId)` as a lowercase hex string. ```tsx theme={null} ``` Generation recipes (Node.js, Python, and more): [Secure your Inbox with HMAC](/platform/inbox/prepare-for-production#secure-your-inbox-with-hmac-encryption). ## agentHash `agentHash` authenticates which agent the subscriber can talk to. Without it, a client can send any public agent identifier that is linked to Web Chat. If **Security HMAC encryption** is on for **Web Chat**: 1. Open [Integrations](https://dashboard.novu.co/integrations). 2. Select the **Web Chat** integration. 3. Enable **Security HMAC encryption**. 4. On your server, compute `HMAC-SHA256(secretKey, agentIdentifier)` as a lowercase hex string. 5. Pass that value as `agentHash` to `useWebChat`. ```tsx theme={null} useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER', agentHash: 'YOUR_AGENT_HASH', }); ``` ## Context You can pass a `context` (for example, `tenant`) to `NovuProvider`. Your agent receives it as `ctx.context` on Web Chat turns only when **Security HMAC encryption** is on for **Novu In-App**. | Novu In-App HMAC | What you pass to `NovuProvider` | `ctx.context` in your agent | | - | - | - | | On | `context` and `contextHash` | The context | | Off | `context` | `null`. The context is not forwarded. | With HMAC off, any client could send any context, so Novu does not pass it to your agent. With HMAC on, Novu rejects a session whose `contextHash` does not match its `context`. Before your agent uses the context to scope what it reads and changes: * **Trust the context `id`, not its `data`.** Novu sends the `data` stored on the context, not the `data` you signed. That stored `data` was written when the context was first created, by your server through the Contexts API or by an earlier session. Look up anything else you need on your server, from the `id`. * **Check that the subscriber belongs to that tenant.** A `contextHash` is the same for every subscriber, so a subscriber who has another tenant's hash can reuse it. * **Handle both value shapes.** Each context value is either `{ id, data }` or, when it has no `data`, the `id` as a plain string. ```tsx theme={null} ``` ```ts theme={null} onMessage: async (message, ctx) => { const tenant = ctx.context?.tenant; const tenantId = typeof tenant === 'string' ? tenant : tenant?.id; const subscriberId = ctx.subscriber?.subscriberId; // `isTenantMember` is your own lookup. if (!tenantId || !subscriberId || !(await isTenantMember(subscriberId, tenantId))) { await ctx.reply('Please sign in again.'); return; } // Scope reads and writes to `tenantId`. }, ``` To compute `contextHash` on your server, see [Secure your Inbox with HMAC](/platform/inbox/prepare-for-production#secure-your-inbox-with-hmac-encryption). > [!NOTE] > > Every active **Novu In-App** integration in the environment must have HMAC on. If one does not, `ctx.context` stays `null` on Web Chat. # Tools Source: https://docs.novu.co/agents/channels/web-chat/tools Render tool calls, resolve tool approvals, and complete MCP connect in Web Chat. When the agent calls a tool, the assistant message includes a part with `type: 'tool'`. Tool approval and Model Context Protocol (MCP) connect are separate. They block the turn until the subscriber acts. See [Tool approval](/agents/custom-code-agent/building-blocks/tool-approval) for the agent-side API. ## Tool calls A tool part shows the call and its result. This is not approval. Do not call `respondToAction` for tool parts. Fields on `part.type === 'tool'`: | Field | Meaning | | - | - | | `toolUseId` | ID for this tool use. | | `toolName` | Tool that ran. | | `input` | Arguments the agent sent. | | `output` | Result blocks when the call finishes. | | `state` | `input-streaming`, `input-available`, `output-available`, or `output-error`. | Render the tool name, then input or output from `state`: ```tsx theme={null} const { messages } = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER' }); {messages.map((message) => message.parts.map((part, index) => { if (part.type !== 'tool') { return null; } return (
    {part.toolName} {part.state === 'output-error' ? (

    Tool failed

    ) : part.output ? (
    {JSON.stringify(part.output, null, 2)}
    ) : (
    {JSON.stringify(part.input, null, 2)}
    )}
    ); }) )} ``` ## Tool approval `pendingActions` lists waits that block the turn. Do not mix the two action types. | `action.type` | What to do | | - | - | | `approval` | Call `respondToAction` with `action.approvalId` and `approved` or `denied`. | | `mcp-connection` | Open `action.authorizeUrl` in the browser. Do not call `respondToAction`. | Show an Approve button for each pending approval: ```tsx theme={null} const { pendingActions, respondToAction } = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER', }); {pendingActions.map((action) => { if (action.type !== 'approval') { return null; } return ( ); })} ``` Pass `action.approvalId` from `pendingActions`. Do not invent approve or deny ids. ## MCP connect An `mcp-connection` action asks the subscriber to authorize an MCP server. Open `authorizeUrl`. Do not call `respondToAction`. ```tsx theme={null} const { pendingActions } = useWebChat({ agentId: 'YOUR_AGENT_IDENTIFIER', }); {pendingActions.map((action) => { if (action.type !== 'mcp-connection') { return null; } return ( Connect {action.displayName} ); })} ``` # WhatsApp Source: https://docs.novu.co/agents/channels/whatsapp Connect your agent to WhatsApp Business: session context, typing indicators, quick-reply buttons, and tool approval. Use WhatsApp Business as a messaging channel for your agent. Novu keeps session context, shows a typing indicator during the turn, and uses native quick-reply buttons for choices and tool approval. ## Capabilities | Capability | Support | | - | - | | Full context history | Yes | | Threaded replies (within session window) | Yes | | Live typing indicator | Yes (fixed text) | | React with eyes on inbound messages | Yes | | Plan card | No | | Rich text | Bold / italics only | | Tap-to-respond buttons | Yes (up to 3 per message) | | Emoji reactions | Yes | | Message edits in place | Yes | | Action / MCP tool approval | Yes (quick-reply buttons) | | MCP connect card | Yes (short authorize URL) | | Resolve conversation | Yes | | File sharing | Not yet | | Streaming word-by-word | Not yet | | Quote reply | Native | Full matrix: [Channels overview](/agents/channels/overview). ## Examples ### Inbound message A user messages the bot. Novu adds an eyes reaction, shows typing, then delivers a complete reply with up to three quick-reply buttons. ### Tool approval Gated tools use Approve / Deny quick replies. The handler resumes after the user taps a button. ## Setup | Framework / Platform | Guide | | - | - | | Custom code agent | Follow a [connect guide](/agents/get-started/ai-sdk), then add WhatsApp as another provider | | Managed agent | [Claude](/agents/get-started/claude-managed) or [AWS Claude](/agents/get-started/aws-claude), then link WhatsApp in the dashboard | WhatsApp Business credentials are configured in the Novu dashboard when you add the provider. ## Connect component `@novu/react` does not ship a WhatsApp connect button yet. Link WhatsApp Business in the Novu dashboard when you add the provider to the agent, or use the [channel endpoints API](/api-reference/channel-endpoints/create-a-channel-endpoint) if you need programmatic subscriber endpoints. For Slack, Teams, and Telegram embeddable buttons, see [Connect components](/agents/custom-code-agent/connect-components). ## Related > [card] [Reply](/agents/custom-code-agent/building-blocks/reply) > > Plain text and interactive buttons. > [card] [Typing indicator](/agents/custom-code-agent/building-blocks/typing-indicator) > > Typing bubble while the handler runs. > [card] [Tool approval](/agents/custom-code-agent/building-blocks/tool-approval) > > Approve / Deny before tools execute. > [card] [Channels overview](/agents/channels/overview) > > Compare providers. # Agent Conversations Source: https://docs.novu.co/agents/conversations View, inspect, and manage agent conversations in the Novu dashboard, including lifecycle state, message history, metadata, and per-channel activity. Novu provides full observability for agent conversations across both managed agents and custom code agents. You can view and manage conversations in the Novu dashboard. Go to the Activity Feed page and switch to the **Agent Conversations** tab. ## Conversation lifecycle Every agent conversation follows the same state machine, regardless of agent type: ![Agent conversation lifecycle](https://mintcdn.com/novu-c5de82d9/GgsvkDH1Mx055NRY/images/agents/conversations/lifecycle.png?fit=max\&auto=format\&n=GgsvkDH1Mx055NRY\&q=85\&s=4d698b86e4ce2361d065ab371cec5668) Agent conversation lifecycle states: Active, Resolved, and Reopened. | State | What it means | | - | - | | **Active** | The conversation is ongoing. Messages increment the count, metadata can be updated, and the last activity timestamp is refreshed. | | **Resolved** | The conversation has been closed. For custom code agents, this happens when the handler calls `ctx.resolve()` and the `onResolve` handler fires. For managed agents, the platform can resolve the conversation based on its reasoning. An optional summary is stored. | | **Reopened** | If a user sends a new message after the conversation was resolved, it automatically reopens and becomes active again. | ## What the dashboard shows View an agent conversation history from the agent's detail page, or from the Activity Feed by switching to the **Agent Conversations** tab. The list shows status, the last message, the message count, and the last activity time. Open a row for the full timeline.

    Open dashboard , ); ``` * **`Table`** takes `headers` (column labels) and `rows` (an array of cell-string arrays). Optional `caption` labels the table, and `pageSize` sets rows per page on channels that paginate (Slack: 1-100, default 5). * **`Chart`** takes a `title` and a `chart` definition. Use `type: 'bar' | 'line' | 'area'` with `categories` and `series`, or `type: 'pie'` with `segments`. On Slack the title is capped at 50 characters, and series and categories are capped at 12. * **`LinkButton`** renders a button that opens a `url`, unlike `CardLink`, which renders an inline link. Place it inside `Actions`. > [!NOTE] > > On Slack, `Table` ignores per-column `align`. A chart or table that exceeds the platform limits falls back to a plain-text section. ## Related > [card] [Edit sent messages](/agents/custom-code-agent/building-blocks/edit-sent-messages) > > Update a message in place after sending it with `ReplyHandle`. > [card] [Signals](/agents/custom-code-agent/building-blocks/signals) > > Metadata, workflow triggers, and conversation resolution. > [card] [Emit custom events](/agents/custom-code-agent/building-blocks/emit) > > Send a named payload. Web Chat renders it as a `data` part. > [card] [AI SDK](/agents/custom-code-agent/frameworks/ai-sdk) > > Build end to end with `@novu/framework/ai-sdk`. > [card] [Send an agent reply API](/api-reference/agents/send-an-agent-reply) > > Send replies from your backend without a bridge handler. > [card] [Web Chat cards](/agents/channels/web-chat/generative-ui#cards) > > Render `part.type === 'card'` in your product UI and call `sendAction`. # Signals Source: https://docs.novu.co/agents/custom-code-agent/building-blocks/signals Use signals in custom code agent handlers to update metadata, trigger Novu workflows, and mark conversations resolved from your agent runtime. Signals let you change conversation state without sending another chat message. [Replies](/agents/custom-code-agent/building-blocks/reply) go to the user; signals update metadata, fire workflows, or mark a thread resolved. Use `ctx.reply()` when the user should see something. Use signals when you only need to persist data, trigger a Novu workflow, or close the conversation. Use [`ctx.emit`](/agents/custom-code-agent/building-blocks/emit) when your client needs a named payload during the turn. That call is not a signal. ## Channel support | Capability | Slack | Teams | WhatsApp | Telegram | Email | | - | - | - | - | - | - | | Resolve conversation | Yes | Yes | Yes | Yes | Yes | | Metadata / trigger signals | Yes | Yes | Yes | Yes | Yes | Resolve and other signals are channel-agnostic. Novu applies them to the conversation regardless of provider. See [Channels overview](/agents/channels/overview). ## Signal types | Signal | What it does | Method | | - | - | - | | Metadata | Store key-value data on the conversation (persists across messages) | `ctx.metadata.set(key, value)` | | Trigger | Fire a Novu workflow (email, push, SMS, multi-step) | `ctx.trigger(workflowId, options)` | | Resolve | Mark the conversation as resolved, with an optional summary | `ctx.resolve(summary?)` | You can combine both in one handler turn: reply to the user, set metadata, call `ctx.trigger()` for an escalation email, and `ctx.resolve()` when the issue is done. ## How signals are delivered Signals are not sent the instant you call them. They are queued in memory and batched with your next `ctx.reply()` in a single HTTP request. That batches work into one request instead of several round trips. ![Signal delivery flow](https://mintcdn.com/novu-c5de82d9/GgsvkDH1Mx055NRY/images/agents/custom-code-agent/setup-your-agent/signals.png?fit=max\&auto=format\&n=GgsvkDH1Mx055NRY\&q=85\&s=a2dfeee8e67fc67367885700b6638996) If your handler finishes without calling `ctx.reply()`, pending signals are still sent automatically. ## Set metadata Store key-value data on the conversation (up to 64 KB cumulative). Metadata persists across messages and is available in `ctx.conversation.metadata` on every subsequent handler call. ```tsx theme={null} ctx.metadata.set('sentiment', 'positive'); ctx.metadata.set('ticketId', 'JIRA-1234'); ``` Use metadata for intent, ticket IDs, escalation flags, or any state your agent needs across turns. ## Trigger a workflow Start any Novu workflow from a handler, the same workflows you use for email, push, or SMS elsewhere in your account. ```tsx theme={null} ctx.trigger('escalation-email', { to: ctx.subscriber?.subscriberId, payload: { reason: 'User requested human support' }, }); ``` Common patterns: * Escalation emails * CSAT surveys after resolution * Alerting on-call teams ## Resolve a conversation Mark the conversation as resolved with an optional summary. This sets status to `resolved`, fires `onResolve`, and stores the summary as signal activity. ```tsx theme={null} ctx.resolve('Issue resolved - billing adjustment applied.'); ``` Resolved conversations automatically reopen if the user sends a new message. ## Example: all three signals in one turn ```tsx theme={null} import { agent } from '@novu/framework'; export const myAgent = agent('my-agent', { onMessage: async (message, ctx) => { const response = await callLLM(message.text ?? '', ctx.history); ctx.metadata.set('lastIntent', response.intent); if (response.needsEscalation) { ctx.trigger('escalation-workflow', { to: ctx.subscriber?.subscriberId, payload: { reason: response.reason }, }); } if (response.done) { ctx.resolve(response.summary); } await ctx.reply(response.text); }, }); ``` ## Related > [card] [Reply](/agents/custom-code-agent/building-blocks/reply) > > Send plain text, markdown, attachments, and interactive cards. > [card] [Handlers and context](/agents/custom-code-agent/building-blocks/handle-events) > > Event handlers and the context object your agent receives on every turn. > [card] [AI SDK](/agents/custom-code-agent/frameworks/ai-sdk) > > Build end to end with `@novu/framework/ai-sdk`. # Tool approval Source: https://docs.novu.co/agents/custom-code-agent/building-blocks/tool-approval Pause an agent turn and ask the user to approve or deny a tool call before it runs, then resume with the decision. Some tool calls should not run without user approval (refunds, deletes, payments). Tool approval posts an **Approve / Deny** card in the conversation and pauses the turn until the user decides. This page covers `ctx.toolApproval.request()`, the `onToolApproval` handler, and card customization. How you gate a tool depends on your runtime. Asking a human a question (`ctx.ask` / `ctx.approve` / `ctx.choose` / `ctx.tell`) is a different flow. On managed agents the equivalent is the `novu_human` tool plus the Novu HITL skill — see [Add skills](/agents/managed-agent/add-skills#novu-hitl-skill). ## Channel support | Capability | Slack | Teams | WhatsApp | Telegram | Email | | - | - | - | - | - | - | | Action / tool approval | Yes (native block) | Yes (Adaptive Card) | Yes (quick replies) | Yes | Yes (action links) | | MCP tool approval | Yes | Yes | Yes | Yes | Yes | | MCP connect card | Yes | Yes | Yes | Yes | Yes | See [Channels overview](/agents/channels/overview) for the full matrix. > [tab] AI SDK > > Set `needsApproval: true` on an AI SDK tool. When the model calls it, Novu posts the approval card and pauses the turn. After the user clicks **Approve** or **Deny**, Novu re-runs `onMessage` so `generateText` continues the tool loop - no `ctx.toolApproval.request()` needed. > > ```typescript theme={null} > import { agent, toModelMessages } from '@novu/framework/ai-sdk'; > import { openai } from '@ai-sdk/openai'; > import { generateText, tool } from 'ai'; > import { z } from 'zod'; > > export const myAgent = agent('my-agent', { > onMessage: async (message, ctx) => { > return generateText({ > model: openai('gpt-4o'), > messages: toModelMessages(ctx), > tools: { > issueRefund: tool({ > inputSchema: z.object({ orderId: z.string() }), > needsApproval: true, > execute: async ({ orderId }) => refund(orderId), > }), > }, > }); > }, > }); > ``` > > See [AI SDK](/agents/custom-code-agent/frameworks/ai-sdk#automatic-tool-approval) for auto-resume and optional `onToolApproval` hooks. > [tab] LangChain > > Set `needsApproval` on a `LangChainAgentConfig`. When the model calls a gated tool, Novu posts the approval card and pauses the turn. After the user clicks **Approve** or **Deny**, Novu re-runs `onMessage` and resumes from `ctx.history` - no `ctx.toolApproval.request()` needed. > > ```typescript theme={null} > import { tool } from '@langchain/core/tools'; > import { agent } from '@novu/framework/langchain'; > import { z } from 'zod'; > > const issueRefund = tool( > async ({ orderId }) => refund(orderId), > { > name: 'issueRefund', > description: 'Issue a refund for an order', > schema: z.object({ orderId: z.string() }), > }, > ); > > export const myAgent = agent('my-agent', { > onMessage: async (message, ctx) => ({ > model: 'openai:gpt-4o', > tools: [issueRefund], > needsApproval: (toolCall) => toolCall.name === 'issueRefund', > }), > }); > ``` > > See [LangChain](/agents/custom-code-agent/frameworks/langchain#automatic-tool-approval) for auto-resume and optional `onToolApproval` hooks. > [tab] Custom code > > Call `ctx.toolApproval.request()` with the tool call and return it from `onMessage`. This posts the approval card and ends the turn: > > ```typescript theme={null} > import { agent } from '@novu/framework'; > > export const myAgent = agent('my-agent', { > onMessage: async (message, ctx) => { > const toolCall = { id: 'call_1', name: 'issueRefund', input: { orderId: 'A-123' } }; > > if (needsApproval(toolCall)) { > return ctx.toolApproval.request(toolCall); // posts the card, pauses the turn > } > > // ...run the tool and reply normally > }, > }); > ``` > > `request()` takes an `AgentToolCall`: > > | Field | Type | Description | > | - | - | - | > | `id` | `string` | Your identifier for this tool call | > | `name` | `string` | Tool name shown on the card | > | `input` | `Record` (optional) | Arguments, available to card customization | ## Default behavior When you **do not** register an `onToolApproval` handler, Novu handles the click for you: * The user clicks **Approve** or **Deny**. * Novu deletes the approval card and restarts the typing indicator. See [Typing indicator](/agents/custom-code-agent/building-blocks/typing-indicator). * The decision is recorded in `ctx.history`. If several tools need approval in the same turn, they surface one at a time - the next card appears after the current one is resolved. > [!NOTE] > > If the user sends a new message while a card is pending, Novu auto-denies the pending tool(s), deletes the card, and processes the new message. This is the simplest path - post the card and let Novu clean it up. On the **Custom code** path, handle the decision in `onToolApproval` when you need to run the tool or post a reply after the click. ## Handle the decision with `onToolApproval` Register `onToolApproval` when you need to act on the click - run the tool, post a result, edit the card, or audit the decision. It receives a `decision`: > [tab] AI SDK > > ```typescript theme={null} > import { agent, toModelMessages } from '@novu/framework/ai-sdk'; > import { openai } from '@ai-sdk/openai'; > import { generateText, tool } from 'ai'; > import { z } from 'zod'; > > export const myAgent = agent('my-agent', { > onMessage: async (message, ctx) => { > return generateText({ > model: openai('gpt-4o'), > messages: toModelMessages(ctx), > tools: { > issueRefund: tool({ > inputSchema: z.object({ orderId: z.string() }), > needsApproval: true, > execute: async ({ orderId }) => refund(orderId), > }), > }, > }); > }, > > onToolApproval: async (decision, ctx) => { > if (!decision.approved) { > await decision.approvalMessage.delete(); > return 'No problem - I did not issue the refund.'; > } > > await decision.approvalMessage.delete(); > // return nothing → onMessage auto-resumes > }, > }); > ``` > [tab] LangChain > > ```typescript theme={null} > import { tool } from '@langchain/core/tools'; > import { agent } from '@novu/framework/langchain'; > import { z } from 'zod'; > > const issueRefund = tool( > async ({ orderId }) => refund(orderId), > { > name: 'issueRefund', > description: 'Issue a refund for an order', > schema: z.object({ orderId: z.string() }), > }, > ); > > export const myAgent = agent('my-agent', { > onMessage: async (message, ctx) => ({ > model: 'openai:gpt-4o', > tools: [issueRefund], > needsApproval: (toolCall) => toolCall.name === 'issueRefund', > }), > > onToolApproval: async (decision, ctx) => { > if (!decision.approved) { > await decision.approvalMessage.delete(); > return 'No problem - I did not issue the refund.'; > } > > await decision.approvalMessage.delete(); > // return nothing → onMessage auto-resumes > }, > }); > ``` > [tab] Custom code > > ```typescript theme={null} > import { agent } from '@novu/framework'; > > export const myAgent = agent('my-agent', { > onMessage: async (message, ctx) => { > return ctx.toolApproval.request({ id: 'call_1', name: 'issueRefund', input: { orderId: 'A-123' } }); > }, > > onToolApproval: async (decision, ctx) => { > // decision.toolCall - { id, name, input? } > // decision.approved - true | false > // decision.approvalMessage - ReplyHandle to the card (edit/delete) > > if (!decision.approved) { > await decision.approvalMessage.delete(); > return 'No problem - I did not issue the refund.'; > } > > const result = await issueRefund(decision.toolCall.input); > await decision.approvalMessage.delete(); > > return `Refund issued for order ${result.orderId}.`; > }, > }); > ``` > > On the **Custom code** path, you run the tool yourself in `onToolApproval` - there is no automatic model resume. > [!WARNING] > > When you register `onToolApproval`, **you own card cleanup.** Novu no longer auto-deletes the card - call `decision.approvalMessage.edit()` or `decision.approvalMessage.delete()` yourself. The `decision` object: | Field | Type | Description | | - | - | - | | `toolCall` | `AgentToolCall` | The gated tool (`id`, `name`, `input?`) | | `approved` | `boolean` | `true` if approved, `false` if denied | | `approvalMessage` | `ReplyHandle` | Handle to the card - `edit()` or `delete()` it. See [Edit sent messages](/agents/custom-code-agent/building-blocks/edit-sent-messages) | ### Edit the card in place Instead of deleting, edit the card to reflect the outcome so the thread keeps a record: ```typescript theme={null} onToolApproval: async (decision, ctx) => { if (!decision.approved) { await decision.approvalMessage.edit('Refund request denied.'); return; } await decision.approvalMessage.edit('Refund approved - processing…'); const result = await issueRefund(decision.toolCall.input); await decision.approvalMessage.edit(`Refund issued for order ${result.orderId}.`); }, ``` ## Customize the card By default Novu renders an **Approve / Deny** card. Customize it with `toolApproval.renderApproval`. Novu always supplies the action ids and wires the buttons unless you build a fully custom card. ```typescript theme={null} export const myAgent = agent('my-agent', { toolApproval: { renderApproval: ({ toolCall, actionIds, approvalCard }) => approvalCard({ // icon: omit → matched from the tool name against the Novu MCP catalog // icon: 'stripe' → catalog id or server-name lookup // icon: 'https://…' → your own image URL (Slack only, 32×32 recommended) subtitle: `${toolCall.name} - order ${toolCall.input?.orderId}`, approveLabel: 'Yes, refund', denyLabel: 'Cancel', }), }, onMessage: async (message, ctx) => { return ctx.toolApproval.request({ id: 'call_1', name: 'issueRefund', input: { orderId: 'A-123' } }); }, }); ``` `renderApproval` receives: | Arg | Description | | - | - | | `toolCall` | The gated tool (`id`, `name`, `input`) | | `actionIds` | `{ approve, deny }` - wire these to your own buttons for a fully custom card | | `approvalCard(overrides?)` | Helper returning Novu's native card descriptor | `approvalCard()` fields (channel support noted): | Field | Channels | Description | | - | - | - | | `title` | All | Card title. Defaults to `Tool approval required` | | `subtitle` | All | Subtitle; auto-generated from the tool when omitted | | `approveLabel` / `denyLabel` | All | Button labels. Default `Approve` / `Deny` | | `icon` | Slack only | Catalog id, `https://` URL (32×32), or omit to auto-match the tool name | | `body` | Slack only | Optional markdown body (e.g. argument preview) | For a fully custom card, wire the action ids onto your own buttons: ```tsx theme={null} toolApproval: { renderApproval: ({ actionIds }) => ( ); } export function renderEmail(inputs) { return render(); } ``` **4. Write your workflow** Define your workflow using the above template ```tsx theme={null} workflow('new-signup', async ({ step, payload }) => { await step.email('send-email', async (inputs) => { return { subject: `Welcome to Remix and React E-mail`, body: renderEmail(inputs), } }); }); ``` # Svelte Email Source: https://docs.novu.co/framework/content/svelte-email Use Svelte Email components with the Novu Framework to build responsive, reusable transactional email templates in your Svelte or SvelteKit project. Integrating Novu Framework with [Svelte email](https://react.email/) for your Svelte application can be done in three steps. If you don't have an app, you can [clone our Svelte example](https://github.com/novuhq/novu-svelte-email). **1. Install Svelte email components** ```bash theme={null} npm install svelte-email ``` **2. Create email templates folder** Create a new folder called `emails` in your `src` folder. **3. Write your email** Create a new file called `test-email.svelte` in your `emails` folder. ```svelte theme={null} Welcome to Svelte Email

    Welcome, {name}!

    Thanks for trying Svelte Email. We're thrilled to have you on board.

    ``` Create a new file called `test-email.ts` in your `emails` folder. ```typescript theme={null} export function renderEmail(name: string) { return render({ template: TestEmail, props: { name, }, }); } ``` **4. Write your workflow** Define your workflow using the above template ```typescript theme={null} export const testWorkflow = workflow('test-workflow', async ({ step, payload }) => { await step.email('send-email', async (controls) => { return { subject: controls.subject, body: renderEmail(payload.userName), }; }, { controlSchema: z.object({ subject: z.string().default('A Successful Test on Novu from {{userName}}'), }), }); }, { payloadSchema: z.object({ userName: z.string().default('John Doe'), }), }); ``` # Vue Email Source: https://docs.novu.co/framework/content/vue-email Design responsive email templates for Novu workflows with Vue Email components and render them from your Framework email step at trigger time. You can integrate Novu Framework with [Vue Email](https://vuemail.net/) in a few simple steps. This guide will walk you through the process of creating a new email template using Vue Email and Nuxt. For a Quickstart Boilerplate project using Nuxt.js, and Vue Email, check out the [Vue Email Starter repository](https://github.com/novuhq/novu-framework-nuxt-example/) ## Quickstart **1. Install Vue.Email components** ```bash theme={null} npm install @vue-email/components ``` **2. Create templates folder** Create a new folder called `emails` in your `src` folder. **3. Update nuxt.config.ts File** ```typescript theme={null} export default defineNuxtConfig({ build: { transpile: ['@vue/email'], }, nitro: { esbuild: { options: { target: 'esnext', }, }, }, }); ``` **4. Write your email** ```vue theme={null} ``` **5. Write your workflow** ```typescript theme={null} export const testWorkflow = workflow('test-workflow', async ({ step, payload }) => { await step.email('send-email', async (controls) => { return { subject: controls.subject, body: renderEmail(payload.userName), }; }, { controlSchema: z.object({ subject: z.string().default('A Successful Test on Novu from {{userName}}'), }), }); }, { payloadSchema: z.object({ userName: z.string().default('John Doe'), }), }); ``` ## Learn More To learn more, refer to [Vue Email documentation](https://vuemail.net/). # Controls Source: https://docs.novu.co/framework/controls Use Controls in Novu Framework workflows to expose configurable options to non-developers, validated by Zod or JSON Schema at runtime. Controls are defined using [JSON Schema](/framework/schema/json-schema) or [Zod](https://zod.dev), providing a strong run-time validation system for your workflows. This ensures that you as the developer and your non-technical peers are speaking the same language. Those responsible for styling and copy can edit with confidence, knowing their changes are tested in code. ## Controls vs Payload **Control Schema** - For Non-Technical Peers and Developers. Managed in the Novu Dashboard UI, defined by developers and used by non-technical peers. **Payload Schema** - For Developers. Passed during the `novu.trigger` method, and controlled by the developer. ## Common usecases * **Content** - Modify any static content: email subject, email body, push notification title, etc... * **Styling** - Modify the styling of the content: button color, background color, font size, etc... * **Behaviour** - Modify the behaviour of the content: show/hide a section, show/hide a button, etc... * **Order** - Modify the order of the content: the order of the email sections, the order of the buttons, etc... * **Actions** - Modify the behaviour of actions: digest duration, etc... * **Other** - Any other use case that should be controller without modifying code ## Step Controls Step Control schema defines the control passed during the `step` method. These controls can be modified and persisted in the Novu Dashboard UI. The snippet below shows a configuration for the Step Control schema. If you don't provide a schema, Typescript will infer the data type to `unknown`, reminding you of the best practice to specify your schema. > [tab] Zod Schema > > ```tsx theme={null} > import { z } from 'zod'; > import { render } from 'react-email'; > import { ReactEmailContent } from './ReactEmailContent'; > > workflow('new-signup', async ({ step, payload }) => { > await step.email( > 'send-email', > async (controls) => { > return { > subject: controls.subject, > body: render( > > ), > }; > }, > { > controlSchema: z.object({ > hideBanner: z.boolean().default(false), > subject: z.string().default('Hi {{subscriber.firstName | capitalize}}'), > components: z.array( > z.object({ > type: z.enum(['header', 'cta-row', 'footer']), > content: z.string(), > }) > ), > }), > } > ); > }); > ``` > [tab] Class-Validator Schema > > ```tsx theme={null} > import { IsString, IsNotEmpty, IsOptional, IsBoolean } from 'class-validator'; > import { Type } from 'class-transformer'; > import { render } from 'react-email'; > import { ReactEmailContent } from './ReactEmailContent'; > > class NewSignUpComponent { > @IsString() > subject: string; > > @IsString() > content: string; > } > class NewSignUpControlSchema { > @IsBoolean() > hideBanner: boolean; > > @IsString() > @IsNotEmpty() > @IsOptional() > subject?: string; > > // Allowing no code control over the component in the Dashboard UI > @Type(() => NewSignUpComponent) > @NestedValidation({ each: true }) > @IsOptional() > components?: NewSignUpComponent[]; > } > > workflow('new-signup', async ({ step, payload }) => { > await step.email( > 'send-email', > async (controls) => { > return { > subject: controls.subject, > body: render( > > ), > }; > }, > { > // Learn about Class-Validator Schema here: https://github.com/typestack/class-validator > controlSchema: NewSignUpControlSchema, > } > ); > }); > ``` > [tab] JSON Schema > > ```tsx theme={null} > workflow("new-signup", async ({ step, payload }) => { > await step.email( > "send-email", > async (controls) => { > return { > subject: controls.subject, > body: render( > hideBanner={controls.hideBanner} > components={controls.components} > /> > ), > }; > }, > { > // Learn about JSON Schema here: https://json-schema.org/specification > controlSchema: { > // Always `object` > type: "object", > // Specify the properties to validate. Supports deep nesting. > properties: { > hideBanner: { type: "boolean", default: false }, > subject: { type: "string", default: 'Hi {{subscriber.firstName | capitalize}}' }, > // Allowing no code control over the component in the Dashboard UI > components: { > type: "array", > items: { > type: "object", > }, > properties: { > subject: { type: "string" }, > content: { type: "string" }, > } > }, > }, > // Specify the array of which properties are required. > required: ["hideBanner"], > // Used to enforce full type strictness, with no rogue properties. > additionalProperties: false, > // The `as const` is important to let Typescript know that this > // type won't change, enabling strong typing on `inputs` via type > // inference of the provided JSON Schema. > } as const, > } > ); > }); > ``` For the full list of parameters, check out the [full SDK reference](/framework/typescript/steps). ## Schema Validation & IDE IntelliSense You can use **Zod, Class-Validator or JSON Schema** based on your needs. > [tab] Zod > > **[Zod](https://zod.dev/)** - A TypeScript-first schema declaration and validation library. *(Novu supports Zod v3)* > [tab] Class-Validator > > **[Class-Validator](https://github.com/typestack/class-validator)** - A TypeScript-first validation library using decorators for OOP-style applications. > [tab] JSON Schema > > **[JSON Schema](/framework/schema/json-schema)** - The most popular schema language for defining JSON data structures. If you only want local IDE IntelliSense, you are able to pass plain JS Classes, which will not provide any Schema Definition useable by Novu Platform. All provided **Zod** and **Class-Transformer** Schemas are compiled into **JSON Schema** which is passed to Novu. This ensures a consistent validation approach and UX by managing Payload and Control Data directly from the Platform. > [!WARNING] > > There may be inconsistencies when using Class-Transformer especially with nested schema objects. > Please check out the guidelines on converting Class-Transformer classes to JSON Schema before > using it here: > [class-validator-jsonschema](https://www.npmjs.com/package/class-validator-jsonschema). ## Using Variables To facilitate the use of variables in the control schema, enclose the variable name in double curly braces using the `{{variableName}}` syntax. For example, `{{subscriber.firstName | capitalize}}` will be dynamically replaced with the actual value of the subscriber's first name at runtime. You can use variables in any step control value, whether set by the developer or within the Novu Dashboard UI. To facilitate this, the Novu Dashboard UI offers auto-completion for variables. Simply start typing `{{` to view a list of all available variables.