---
url: https://talkjs.com/docs/Guides/Approval_Workflows/
title: "Approval workflows | Guides | TalkJS Docs"
---

For AI agents: Find a documentation index at https://talkjs.com/llms.txt (full content at https://talkjs.com/llms-full.txt). Get a markdown version of any page by appending .md to its URL path.

# Approval workflows

Let users approve or reject requests inside the chat.

Many apps want users to discuss a request, and approve or deny it. This guide puts the decision in the chat, so the person reviewing the request can approve or reject it where they’re discussing it. In this example, Jamie asks their manager Alex to approve a €120 design workshop.

## Send an approval request

When your backend receives Jamie’s workshop request, send a message on Jamie’s behalf to the chat with Alex. Put the request details in the message’s custom data. [Send a message with the REST API](https://talkjs.com/docs/REST_API/Messages/#send-a-message-on-behalf-of-a-user)

```http
POST https://api.talkjs.com/v1/<APP_ID>/conversations/{conversationId}/messages
Authorization: Bearer <ADMIN_JWT>
Content-Type: application/json

[
  {
    "sender": "jamie",
    "type": "UserMessage",
    "text": "Can I book the €120 design workshop on 12 December?",
    "custom": {
      "kind": "approval",
      "requestId": "request_1042",
      "approverId": "alex",
      "status": "pending"
    }
  }
]
```

TalkJS returns the new message ID, for example `[{"id": "msg_abc123"}]`. Save that ID and the conversation ID with the approval request in your database. When Alex makes a decision, your backend will use them to update the card.

## Create the approval card

Jamie and Alex both see the workshop request, but only Alex can approve it. We’ll use the [TalkJS theme system](https://talkjs.com/docs/UI_Components/Theme/Overview/) to give each of them the right view of the same message.

Here’s what Alex sees while the request is pending.

![An approval request shown as a message in Alex's chat, with Approve and Reject buttons](https://talkjs.com/docs/approval-workflow-pending.png)

Create an `ApprovalCard` component that shows Jamie’s question. For a pending request, it compares the viewer’s TalkJS user ID with the `approverId` on the message. Alex gets the decision buttons, which we’ll build next. Everyone else in the chat, including Jamie, sees “Awaiting a decision”. Once Alex approves or rejects the request, everyone sees the result.

**React**

```jsx
import { ApprovalButtons } from './ApprovalButtons.jsx';

export function ApprovalCard({ approval, text, currentUserId, onDecision }) {
  const { requestId, approverId, status } = approval;
  const canDecide = currentUserId === approverId;
  const statusLabel = { approved: 'Approved', rejected: 'Rejected' }[status];

  return (
    <article className="approval-card" aria-label="Approval request">
      <p className="approval-card-label">Approval request</p>
      <p className="approval-card-text">{text}</p>

      {status === 'pending' && canDecide && (
        <ApprovalButtons
          onDecision={decision => onDecision(requestId, decision)}
        />
      )}

      {status === 'pending' && !canDecide && (
        <p className="approval-card-status">Awaiting a decision</p>
      )}

      {status !== 'pending' && (
        <p className="approval-card-status" role="status">
          {statusLabel || 'Status unavailable'}
        </p>
      )}
    </article>
  );
}
```

**Web Components**

```javascript
import { html } from '@talkjs/web-components';
import { ApprovalButtons } from './ApprovalButtons.js';

export function ApprovalCard({ approval, text, currentUserId, onDecision }) {
  const { requestId, approverId, status } = approval;
  const canDecide = currentUserId === approverId;
  const statusLabel = { approved: 'Approved', rejected: 'Rejected' }[status];

  return html`
    <article className="approval-card" aria-label="Approval request">
      <p className="approval-card-label">Approval request</p>
      <p className="approval-card-text">${text}</p>

      ${status === 'pending' && canDecide && html`
        <${ApprovalButtons}
          onDecision=${decision => onDecision(requestId, decision)}
        />
      `}

      ${status === 'pending' && !canDecide && html`
        <p className="approval-card-status">Awaiting a decision</p>
      `}

      ${status !== 'pending' && html`
        <p className="approval-card-status" role="status">
          ${statusLabel || 'Status unavailable'}
        </p>
      `}
    </article>
  `;
}
```

## Add the decision buttons

When Alex clicks Approve, the buttons tell the card which choice Alex made. The card knows which request it belongs to, so it can give your app both pieces of information, for example `onDecision('request_1042', 'approved')`. Disable the buttons while your app saves the decision. If saving fails, show Alex an error and let them try again.

**React**

```jsx
import { useState } from 'react';

export function ApprovalButtons({ onDecision }) {
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  async function decide(decision) {
    setSaving(true);
    setError('');

    try {
      await onDecision(decision);
    } catch {
      setError("Couldn't finish updating the request. Please try again.");
    } finally {
      setSaving(false);
    }
  }

  return (
    <>
      <div className="approval-card-actions">
        <button className="approval-card-approve" disabled={saving}
          onClick={() => decide('approved')}>
          Approve
        </button>
        <button disabled={saving} onClick={() => decide('rejected')}>
          Reject
        </button>
      </div>
      {saving && <p role="status">Saving…</p>}
      {error && <p role="alert">{error}</p>}
    </>
  );
}
```

**Web Components**

```javascript
import { html, Preact } from '@talkjs/web-components';

const { useState } = Preact;

export function ApprovalButtons({ onDecision }) {
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState('');

  async function decide(decision) {
    setSaving(true);
    setError('');

    try {
      await onDecision(decision);
    } catch {
      setError("Couldn't finish updating the request. Please try again.");
    } finally {
      setSaving(false);
    }
  }

  return html`
    <div className="approval-card-actions">
      <button className="approval-card-approve" disabled=${saving}
        onClick=${() => decide('approved')}>
        Approve
      </button>
      <button disabled=${saving} onClick=${() => decide('rejected')}>
        Reject
      </button>
    </div>
    ${saving && html`<p role="status">Saving…</p>`}
    ${error && html`<p role="alert">${error}</p>`}
  `;
}
```

## Style the card

To give the card the appearance shown above, save these styles in `approval-card.css`.

Card styles

approval-card.css

```css
.approval-card {
  align-self: flex-start;
  width: min(360px, 100%);
  box-sizing: border-box;
  margin: 8px 0;
  padding: 20px;
  border: 1px solid #d6deeb;
  border-radius: 12px;
  background: white;
  color: #1e293b;
  font: 14px/1.5 system-ui, sans-serif;
}

.t-theme-message .t-message-body:has(.approval-card) {
  padding: 0;
  background: transparent;
}

.approval-card-label {
  margin: 0 0 8px;
  color: #64748b;
  font-size: 12px;
  font-weight: 600;
}

.approval-card-text { margin: 0 0 16px; }
.approval-card-actions { display: flex; gap: 8px; }
.approval-card-status { margin: 0; font-weight: 600; }

.approval-card button {
  padding: 8px 16px;
  border: 1px solid #cbd5e1;
  border-radius: 6px;
  background: white;
  color: #334155;
  font: inherit;
  cursor: pointer;
}

.approval-card .approval-card-approve {
  border-color: #2563eb;
  background: #2563eb;
  color: white;
}

.approval-card button:disabled { opacity: 0.6; cursor: wait; }
.approval-header { padding: 0 12px; }
```

Load the card styles in the same place you load the TalkJS stylesheet, just after it.

**React**

```javascript
import '@talkjs/react-components/default.css';
import './approval-card.css';
```

**Next.js**

```javascript
import '@talkjs/react-components/default.css';
import './approval-card.css';
```

**HTML**

```html
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@talkjs/web-components@0.3.14/default.css">
<link rel="stylesheet" href="./approval-card.css">
```

**Angular**

```css
@import '@talkjs/web-components/default.css';
@import './app/approval-card.css';
```

**Vue**

```javascript
import '@talkjs/web-components/default.css';
import './approval-card.css';
```

**Svelte**

```html
<script>
  import '@talkjs/web-components/default.css';
  import './approval-card.css';
</script>
```

## Use the card inside a message

Now that we have the card, we need TalkJS to show it whenever someone sends an approval request. TalkJS uses a theme component called `TextBlock` to display the text inside a message. Replacing that component lets us put the card where Jamie’s question would normally appear, with Jamie’s avatar and the time still visible.

Create `ApprovalTextBlock` to choose what to show. If the message has `kind: 'approval'`, it reads the request details from the message and gives them to the card. TalkJS also supplies the ID of the person viewing the chat, so the card knows whether to show the buttons. For any other message, use the usual TalkJS text block.

**React**

```jsx
import { defaultTheme } from '@talkjs/react-components';
import { ApprovalCard } from './ApprovalCard.jsx';

export function ApprovalTextBlock(props) {
  if (props.message.custom.kind !== 'approval') {
    return <defaultTheme.TextBlock {...props} />;
  }

  return (
    <ApprovalCard
      approval={props.message.custom}
      text={props.message.plaintext}
      currentUserId={props.common.currentUser.id}
      onDecision={props.common.themeCustom.onDecision}
    />
  );
}
```

**Web Components**

```javascript
import { html, defaultTheme } from '@talkjs/web-components';
import { ApprovalCard } from './ApprovalCard.js';

export function ApprovalTextBlock(props) {
  if (props.message.custom.kind !== 'approval') {
    return html`<${defaultTheme.TextBlock} ...${props} />`;
  }

  return html`
    <${ApprovalCard}
      approval=${props.message.custom}
      text=${props.message.plaintext}
      currentUserId=${props.common.currentUser.id}
      onDecision=${props.common.themeCustom.onDecision}
    />
  `;
}
```

## Send the decision to your backend

Alex’s choice needs to reach the app that owns the workshop request. Write an `onDecision` function that sends the choice and request ID to your backend. Use your app’s usual way of making authenticated requests. The example below uses `fetch`.

approval-api.js

```javascript
export async function onDecision(requestId, decision) {
  const response = await fetch(
    `/api/approval-requests/${encodeURIComponent(requestId)}/decision`,
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ decision }),
    }
  );

  if (!response.ok) {
    throw new Error('Could not update the approval request.');
  }
}
```

### Use the new component in your chat

In your existing chatbox, set the theme’s `TextBlock` to `ApprovalTextBlock` and pass `onDecision` in `themeCustom`.

**React**

```jsx
'use client';

import { Chatbox } from '@talkjs/react-components';
import { ApprovalTextBlock } from './ApprovalTextBlock.jsx';
import { onDecision } from './approval-api.js';

export function ApprovalChat({ appId, userId, conversationId }) {
  return (
    <Chatbox
      appId={appId}
      userId={userId}
      conversationId={conversationId}
      theme={{ TextBlock: ApprovalTextBlock }}
      themeCustom={{ onDecision }}
    />
  );
}
```

**HTML**

```html
<script type="module">
  import '@talkjs/web-components';
  import { ApprovalTextBlock } from './ApprovalTextBlock.js';
  import { onDecision } from './approval-api.js';

  const chatbox = document.querySelector('t-chatbox');
  chatbox.theme = { TextBlock: ApprovalTextBlock };
  chatbox.themeCustom = { onDecision };
</script>
```

**Angular**

```typescript
import { Component, CUSTOM_ELEMENTS_SCHEMA, Input } from '@angular/core';
import '@talkjs/web-components';
import { ApprovalTextBlock } from './ApprovalTextBlock.js';
import { onDecision } from './approval-api.js';

@Component({
  selector: 'approval-chat',
  standalone: true,
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
  template: `
    <t-chatbox
      [app-id]="appId"
      [user-id]="userId"
      [conversation-id]="conversationId"
      [theme]="{ TextBlock: ApprovalTextBlock }"
      [themeCustom]="{ onDecision: onDecision }"
    ></t-chatbox>
  `,
})
export class ApprovalChat {
  @Input() appId = '';
  @Input() userId = '';
  @Input() conversationId = '';

  ApprovalTextBlock = ApprovalTextBlock;
  onDecision = onDecision;
}
```

**Vue**

```html
<script setup>
  import '@talkjs/web-components';
  import { ApprovalTextBlock } from './ApprovalTextBlock.js';
  import { onDecision } from './approval-api.js';

  defineProps(['appId', 'userId', 'conversationId']);

</script>

<template>
  <t-chatbox
    :app-id="appId"
    :user-id="userId"
    :conversation-id="conversationId"
    :theme.prop="{ TextBlock: ApprovalTextBlock }"
    :themeCustom.prop="{ onDecision }"
  />
</template>
```

**Svelte**

```html
<script>
  import { onMount } from 'svelte';
  import { onDecision } from './approval-api.js';

  export let appId;
  export let userId;
  export let conversationId;

  let ApprovalTextBlock;

  onMount(async () => {
    ApprovalTextBlock = (await import('./ApprovalTextBlock.js')).ApprovalTextBlock;
  });
</script>

{#if ApprovalTextBlock}
  <t-chatbox
    app-id={appId}
    user-id={userId}
    conversation-id={conversationId}
    theme={{ TextBlock: ApprovalTextBlock }}
    themeCustom={{ onDecision }}
  ></t-chatbox>
{/if}
```

## Save the decision and update the chat

When your backend receives Alex’s choice, look up the request and check that the signed-in user is allowed to decide it. Save the decision in your app. Then use the conversation and message IDs you stored with the request to [edit Jamie’s message](https://talkjs.com/docs/REST_API/Messages/#edit-a-message). If Alex approved the workshop, set its status to `approved`.

```http
PUT https://api.talkjs.com/v1/<APP_ID>/conversations/{conversationId}/messages/{messageId}
Authorization: Bearer <ADMIN_JWT>
Content-Type: application/json

{
  "custom": {
    "status": "approved"
  }
}
```

If Alex rejected the request, use `rejected`. Make this call from your backend with an [Admin JWT](https://talkjs.com/docs/REST_API/#authentication). Once TalkJS has updated the message, return success to the browser.

If the TalkJS update fails after you’ve saved the decision, return an error so Alex can retry. On the next attempt, read the decision you already saved and use it to update the message.

TalkJS sends the updated message to both people. Alex’s buttons and Jamie’s “Awaiting a decision” now show the same result, including when either of them opens the chat again.

![The same request after approval, showing Approved in place of the buttons](https://talkjs.com/docs/approval-workflow-approved.png)

## One conversation per approval request

An approval message works well when Jamie occasionally asks for approval in an ongoing chat with Alex. If your app opens a new conversation for each request, put the card in the chat header so it stays visible as the discussion grows. In that version, the request details and status belong to the conversation itself.

![An approval request fixed below the conversation header, with the discussion underneath](https://talkjs.com/docs/approval-workflow-conversation.png)

Set the approval details in the conversation’s custom data.

```javascript
await conversation.set({
  subject: 'Design workshop',
  custom: {
    kind: 'approval',
    requestId: 'request_1042',
    approverId: 'alex',
    status: 'pending',
    description: 'Can I book the €120 design workshop on 12 December?',
  },
});
```

Save the conversation ID with the workshop request. You can reuse the card and buttons you already built. This time, create a `ChatHeader` component that reads the request from the conversation’s custom data and displays the card just below the title.

**React**

```jsx
import { defaultTheme } from '@talkjs/react-components';
import { ApprovalCard } from './ApprovalCard.jsx';

export function ApprovalHeader(props) {
  const { common } = props;
  const approval = common.conversation.custom;

  if (approval.kind !== 'approval') {
    return <defaultTheme.ChatHeader {...props} />;
  }

  return (
    <>
      <defaultTheme.ChatHeader {...props} />
      <div className="approval-header">
        <ApprovalCard
          approval={approval}
          text={approval.description}
          currentUserId={common.currentUser.id}
          onDecision={common.themeCustom.onDecision}
        />
      </div>
    </>
  );
}
```

**Web Components**

```javascript
import { html, defaultTheme } from '@talkjs/web-components';
import { ApprovalCard } from './ApprovalCard.js';

export function ApprovalHeader(props) {
  const { common } = props;
  const approval = common.conversation.custom;

  if (approval.kind !== 'approval') {
    return html`<${defaultTheme.ChatHeader} ...${props} />`;
  }

  return html`
    <${defaultTheme.ChatHeader} ...${props} />
    <div className="approval-header">
      <${ApprovalCard}
        approval=${approval}
        text=${approval.description}
        currentUserId=${common.currentUser.id}
        onDecision=${common.themeCustom.onDecision}
      />
    </div>
  `;
}
```

Set the chatbox’s `theme` to `{ ChatHeader: ApprovalHeader }` and keep the same `themeCustom.onDecision` callback.

After your backend saves Alex’s choice, [update the conversation](https://talkjs.com/docs/REST_API/Conversations/#setting-conversation-data) using the ID you stored with the request. For an approval, the update looks like this.

```http
PUT https://api.talkjs.com/v1/<APP_ID>/conversations/{conversationId}
Authorization: Bearer <ADMIN_JWT>
Content-Type: application/json

{
  "custom": {
    "status": "approved"
  }
}
```

For a rejection, set the status to `rejected`. Jamie and Alex will see the decision at the top of the chat, with their discussion underneath.
