# Mention people in comments

> Let people type @ in a comment, read who was mentioned, and send a Google Chat notification from your server.



Typing `@` in a comment suggests people from the list your application provides. The comment keeps each mentioned
person's identity, and your application decides whether to notify them. SuperDoc does not send notifications itself.

Start with [Comments](/editor/comments) if you have not added comments to your project yet.

## Provide the people who can be mentioned [#provide-the-people-who-can-be-mentioned]

Pass the current user as `user` and everyone who can be mentioned as `users`. Each entry needs a `name` or `email`; add a
stable `id` so your server can match the person without relying on display text.

The suggestion list shows up to eight people whose name or email starts with the text after `@`. People with
`role: 'viewer'` are not suggested. On internal comments, only people with `access: 'internal'` are suggested. Load
`users` from your own access list; the browser list is a convenience, not an access check.

## Read mentions from comment events [#read-mentions-from-comment-events]

`onCommentsUpdate` runs when a comment is added or changed. For `add` and `update` events, `event.comment.mentions` lists
the people mentioned in that comment. Each entry has the `id`, `name`, and `email` you provided; when a person has no
name, the email is used as the name.

This example sets up the mention list and sends the mentioned people to your server:

```ts
import { SuperDoc, type SuperDocCommentsUpdatePayload } from 'superdoc';
import 'superdoc/style.css';

type MentionedPerson = { id?: string; name?: string; email?: string };

function readMentions(comment: SuperDocCommentsUpdatePayload['comment']): MentionedPerson[] {
  const mentions = comment?.['mentions'];
  if (!Array.isArray(mentions)) return [];

  return mentions.flatMap((mention: unknown) => {
    if (typeof mention !== 'object' || mention === null) return [];
    const id: unknown = Reflect.get(mention, 'id');
    const name: unknown = Reflect.get(mention, 'name');
    const email: unknown = Reflect.get(mention, 'email');
    const person: MentionedPerson = {
      ...(typeof id === 'string' ? { id } : {}),
      ...(typeof name === 'string' ? { name } : {}),
      ...(typeof email === 'string' ? { email } : {}),
    };
    return person.id || person.email ? [person] : [];
  });
}

async function reportMentions(event: SuperDocCommentsUpdatePayload) {
  if (event.rejected || (event.type !== 'add' && event.type !== 'update')) return;

  const commentId = event.comment?.commentId;
  const mentioned = readMentions(event.comment);
  if (typeof commentId !== 'string' || mentioned.length === 0) return;

  const response = await fetch('/api/comment-mentions', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    credentials: 'same-origin',
    body: JSON.stringify({ documentId: 'sample', commentId, mentioned }),
  });
  if (!response.ok) throw new Error(`Mention notification failed: ${response.status}`);
}

const superdoc = new SuperDoc({
  selector: '#editor',
  document: '/sample.docx',
  user: { id: 'u-alex', name: 'Alex Rivera', email: 'alex@example.com' },
  users: [
    { id: 'u-alex', name: 'Alex Rivera', email: 'alex@example.com' },
    { id: 'u-sam', name: 'Sam Patel', email: 'sam@example.com' },
    { id: 'u-jordan', name: 'Jordan Lee', email: 'jordan@example.com', role: 'viewer' },
  ],
  onCommentsUpdate: (event) => {
    reportMentions(event).catch((error) => console.error('Could not report mentions.', error));
  },
});

window.addEventListener('beforeunload', () => superdoc.destroy());

```

Ignore events with `rejected: true`. The change did not reach the document.

Editing a comment's text sends an `update` event with the comment's full mention list, including people who were already
mentioned. Decide who is new on the server, not in the browser.

## Notify mentioned people in Google Chat [#notify-mentioned-people-in-google-chat]

In Google Chat, create an incoming webhook for the space that should receive notifications. The webhook URL can post to
that space, so keep it on your server and never send it to the browser.

Your server should:

1. Identify the signed-in author from the request, not from the request body.
2. Check that the author may comment on the document.
3. Look up each mentioned person in your own records for that document. Skip anyone you do not recognize.
4. Record a key made of document ID, comment ID, and person ID before sending, and skip keys you have already recorded.
5. Post one message that names everyone new. If any step fails before Google Chat accepts the message, remove the keys
   so a later event can try again.

This handler uses the standard `Request` and `Response` types, so it fits most server frameworks. Supply the lookups
and the record of sent notifications from your own storage:

```ts
type Person = { id: string; name: string };

type MentionNotifier = {
  googleChatWebhookUrl: string;
  currentUser(request: Request): Promise<Person | null>;
  canComment(user: Person, documentId: string): Promise<boolean>;
  findMember(documentId: string, mention: { id?: string; email?: string }): Promise<Person | null>;
  claimOnce(key: string): Promise<boolean>;
  releaseClaim(key: string): Promise<void>;
};

function readText(value: unknown, key: string): string | undefined {
  if (typeof value !== 'object' || value === null) return undefined;
  const field: unknown = Reflect.get(value, key);
  return typeof field === 'string' && field !== '' ? field : undefined;
}

export async function handleCommentMentions(request: Request, notifier: MentionNotifier): Promise<Response> {
  const author = await notifier.currentUser(request);
  if (!author) return new Response('Sign in required', { status: 401 });

  const body: unknown = await request.json().catch(() => null);
  const documentId = readText(body, 'documentId');
  const commentId = readText(body, 'commentId');
  const mentioned: unknown = typeof body === 'object' && body !== null ? Reflect.get(body, 'mentioned') : null;
  if (!documentId || !commentId || !Array.isArray(mentioned)) {
    return new Response('Invalid request', { status: 400 });
  }
  if (!(await notifier.canComment(author, documentId))) return new Response('Forbidden', { status: 403 });

  const claimedKeys: string[] = [];
  let sent = false;
  try {
    const recipients: Person[] = [];
    for (const mention of mentioned.slice(0, 20)) {
      const id = readText(mention, 'id');
      const email = readText(mention, 'email');
      const member = await notifier.findMember(documentId, { ...(id ? { id } : {}), ...(email ? { email } : {}) });
      if (!member || member.id === author.id) continue;
      const key = `${documentId}:${commentId}:${member.id}`;
      if (!(await notifier.claimOnce(key))) continue;
      recipients.push(member);
      claimedKeys.push(key);
    }
    if (recipients.length === 0) return new Response(null, { status: 204 });

    const names = recipients.map((member) => member.name).join(', ');
    const response = await fetch(notifier.googleChatWebhookUrl, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json; charset=UTF-8' },
      body: JSON.stringify({ text: `${author.name} mentioned ${names} in a comment on ${documentId}.` }),
    });
    sent = response.ok;
  } finally {
    if (!sent) await Promise.all(claimedKeys.map((key) => notifier.releaseClaim(key)));
  }

  return sent
    ? new Response(null, { status: 204 })
    : new Response('Google Chat did not accept the message', { status: 502 });
}

```

The handler sends one message per comment rather than one per person, because Google Chat limits how often a webhook
can post to a space. When the handler returns an error, the browser example logs it; a production app can queue and
retry on the server instead.

The webhook posts to a space, not to one person. Use the Google Chat API instead when each person should get a direct
message.

## Mentions in the DOCX [#mentions-in-the-docx]

Mentions are saved with the comment when you export the DOCX. When the file is opened in Microsoft Word and saved, the
mention data stays with the comment and SuperDoc reads it back on the next load.

Code that uses the [Document API](/document-api/comments) can attach mentions when it creates a comment by passing
`metadata: { mentions: [{ name, email }] }` to `comments.create()`.

## Verify mentions [#verify-mentions]

1. Add a comment, type `@`, and choose a person from the list.
2. Confirm your server receives the comment ID and that person's `id` and `email`.
3. Edit the comment text. No second notification should be sent.
4. Export the DOCX, reopen it, and confirm the comment still lists the person.
