# Feedback

Collect feedback on your pages.

`@vuesho/feedback` adds a form under each page, where readers rate the page and leave a message, and a popup to comment on selected text. The feedback goes to a handler on your server, to GitHub Discussions or to email.

## Setup [#setup]

### Install the Package [#install-the-package-step]

```npm
npm i @vuesho/feedback
```

### Choose Where Feedback Goes [#choose-where-feedback-goes-step]

Each plugin sends both kinds of feedback to one place:

<Tabs :items='["Your server","GitHub Discussions","Email"]'>
<Tab value="Your server">
`feedbackPlugin()` runs your handlers on the server, and each form shows only when its handler is set. When a handler returns a `githubUrl`, the form shows a link to it after the reader sends the form:

```ts title="vuesho.config.ts"
import { feedbackPlugin } from "@vuesho/feedback";
import { createSite, recommendedPreset } from "vuesho/config";
import { createDiscussion, track } from "./server/feedback";

export default createSite(docs.toSource()).plugins(
  recommendedPreset(),
  feedbackPlugin({
    async onPageFeedbackAction({ opinion, url, message }) {
      await track("page-feedback", { opinion, url, message });
      return {};
    },
    async onTextFeedbackAction({ url, blockId, blockBody, message }) {
      const discussion = await createDiscussion({ url, blockId, blockBody, message });
      return { githubUrl: discussion.url };
    },
  }),
);
```

A handler can throw a `Response` to send it as the answer, like a `400` that rejects a message.
</Tab>

<Tab value="GitHub Discussions">
`githubFeedbackPlugin()` posts the feedback through a GitHub App, as comments on one discussion per page:

1. Create a GitHub App that can read and write Discussions, and [generate a private key](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/managing-private-keys-for-github-apps).
2. Install the app on your repository.
3. Create a `Feedback` category in the repository's Discussions.

```ts tab="vuesho.config.ts"
import { githubFeedbackPlugin } from "@vuesho/feedback/github";

createSite(docs.toSource()).plugins(
  recommendedPreset(),
  // [!code ++:5]
  githubFeedbackPlugin({
    appId: process.env.GITHUB_APP_ID!,
    privateKey: process.env.GITHUB_PRIVATE_KEY!,
    storage: { owner: "acme", repo: "docs", category: "Feedback" },
  }),
);
```

```dotenv tab=".env.local"
GITHUB_APP_ID=...
GITHUB_PRIVATE_KEY=...
```

<Callout type="warn">
GitHub doesn't filter spam, and every visitor posts as your app. Add [rate limiting](#rate-limiting), or choose another destination.
</Callout>
</Tab>

<Tab value="Email">
`emailFeedbackPlugin()` sends the feedback by email through [Resend](https://resend.com). Create a Resend API key, and verify the `from` address's domain in Resend:

```ts tab="vuesho.config.ts"
import { emailFeedbackPlugin } from "@vuesho/feedback";

createSite(docs.toSource()).plugins(
  recommendedPreset(),
  // [!code ++:6]
  emailFeedbackPlugin({
    apiKey: process.env.RESEND_API_KEY!,
    from: "Docs <feedback@acme.dev>",
    to: ["team@acme.dev", "docs@acme.dev"],
    subjectPrefix: "[Docs feedback]",
  }),
);
```

```dotenv tab=".env.local"
RESEND_API_KEY=re_...
```
</Tab>
</Tabs>

### Deploy With a Server [#deploy-with-a-server-step]

The forms send to the API routes `/api/feedback/page` and `/api/feedback/text`, which need a [server](/deploying), so a static build fails. On a static site, [send the feedback from the browser](#static-sites) instead.

`.env.local` isn't deployed, so set the keys in your host's environment variables. Without them, the build succeeds, but each request fails with an error that names the missing key.

## Rate Limiting [#rate-limiting]

<Callout type="warn">
The routes are public, and don't limit the length of a message. Add rate limiting and bot protection before the site goes live.
</Callout>

A plugin's [`middleware`](/routes#middleware) can reject requests before they reach the routes:

```ts title="vuesho.config.ts"
import { isRateLimited } from "./server/rate-limit"; // [!code ++]

createSite(docs.toSource()).plugins(
  recommendedPreset(),
  feedbackPlugin({ onPageFeedbackAction }),
  // [!code ++:8]
  {
    name: "site:rate-limit",
    middleware: {
      async handle(request, next, { page }) {
        if (page.startsWith("/api/feedback/") && (await isRateLimited(request)))
          return new Response("Too Many Requests", { status: 429 });
        return next();
      },
    },
  },
);
```

## Static Sites [#static-sites]

`Feedback` and `FeedbackText` from `@vuesho/feedback/ui` are the forms. Their `action` prop takes a URL or a function, so a static site can send the feedback to another service from the browser:

```vue title="src/components/PageFeedback.vue"
<script setup lang="ts">
import { Feedback, type ActionResponse, type PageFeedback } from "@vuesho/feedback/ui";

async function send(feedback: PageFeedback): Promise<ActionResponse> {
  await fetch("https://feedback.acme.dev", { method: "POST", body: JSON.stringify(feedback) });
  return {};
}
</script>

<template>
  <Feedback :action="send" />
</template>
```

Put the form in the `page-bottom` slot of your [theme](/theme#slots), without a feedback plugin:

```ts title="src/theme.ts"
import { defineAsyncComponent } from "vue";
import { defineTheme } from "vuesho/theme";
import defaultTheme from "vuesho/theme/default";

export default defineTheme({
  extends: defaultTheme,
  slots: {
    "page-bottom": defineAsyncComponent(() => import("./components/PageFeedback.vue")),
  },
});
```

Put `FeedbackText` in the `page-content` slot, around the content, and add [`blockId`](/markdown-extensions#block-ids) from `vuesho/markdown`, so its popup opens on each block:

```ts title="vuesho.config.ts"
import { blockId } from "vuesho/markdown"; // [!code ++]

createSite(docs.toSource()).config({
  markdown: { markdownItPlugins: [[blockId, { addDataAttribute: "feedback" }]] }, // [!code ++]
});
```

To translate the forms, also add `feedbackPlugin()` without handlers. It adds the forms' [translations](#translations), without forms or routes.

## Customizing the UI [#customizing-the-ui]

The page form shows in the `page-bottom` slot, and the text popup wraps `page-content`. To place the forms yourself and keep the routes, replace the plugin's `theme` with your own [theme module](/plugin-api#theme-module):

```ts title="vuesho.config.ts"
createSite(docs.toSource()).plugins(
  recommendedPreset(),
  feedbackPlugin({ onPageFeedbackAction }), // [!code --]
  // [!code ++:4]
  {
    ...feedbackPlugin({ onPageFeedbackAction }),
    theme: "/src/feedback-theme.ts",
  },
);
```

Your theme module puts the form in another slot, like `toc-footer` under the table of contents:

```ts title="src/feedback-theme.ts"
import { defineAsyncComponent } from "vue";
import type { PluginTheme } from "vuesho/client";

export default {
  slots: {
    "toc-footer": defineAsyncComponent(() => import("./components/PageFeedback.vue")),
  },
} satisfies PluginTheme;
```

`page.pageData.feedback` holds the routes' URLs. Pass one to the form as its `action`:

```vue title="src/components/PageFeedback.vue"
<script setup lang="ts">
import { computed } from "vue";
import { Feedback } from "@vuesho/feedback/ui";
import { usePage } from "vuesho/client";
import type app from "../../vuesho.config";

const page = usePage<typeof app>();
const action = computed(() =>
  page.value.kind === "content" ? page.value.pageData.feedback?.page : undefined,
);
</script>

<template>
  <Feedback v-if="action" :action="action" />
</template>
```

### Wrapping Each Block [#wrapping-each-block]

To show a feedback button beside each paragraph instead, wrap each block that has an ID in a component, with a markdown-it rule and `createVueElement()` from `vuesho/markdown`, as in [Markdown Extensions](/markdown-extensions#inserting-components):

<Accordions>
<Accordion title="A rule that wraps each paragraph">
The rule wraps each paragraph in `<FeedbackBlock>`, a component from [`src/components/content/`](/markdown/components#custom-components). Install `markdown-it@15` as a dev dependency for its types:

```ts title="vuesho.config.ts"
import type { MarkdownIt } from "markdown-it";
import { createVueElement } from "vuesho/markdown";

function feedbackBlocks(md: MarkdownIt) {
  md.core.ruler.push("feedback_blocks", (state) => {
    const tokens = state.tokens;
    for (let i = tokens.length - 1; i >= 0; i--) {
      const token = tokens[i]!;
      const id = token.type === "paragraph_open" && token.attrGet("id");
      if (!id || token.hidden) continue;
      // A paragraph is an open, an inline and a close token.
      tokens.splice(i + 3, 0, createVueElement(state, "FeedbackBlock", {}, -1, token));
      tokens.splice(i, 0, createVueElement(state, "FeedbackBlock", { id: String(id) }, 1, token));
    }
  });
}

export default createSite(docs.toSource())
  .plugins(recommendedPreset(), feedbackPlugin({ onTextFeedbackAction }))
  // The rules of the site run after the rules of plugins, so the blocks already have ids.
  .config({ markdown: { markdownItPlugins: [feedbackBlocks] } }); // [!code highlight]
```
</Accordion>
</Accordions>

## Translations [#translations]

The forms have language packs for `zh-CN` and `zh-TW`. For another language, or to change a label, set `ui.translations`, as in [Internationalization](/i18n):

```ts title="vuesho.config.ts"
createSite(docs.toSource(), { i18n }).config({
  ui: {
    translations: { fr: { "How is this guide?(feedback)": "Ce guide vous a-t-il aidé ?" } }, // [!code highlight]
  },
});
```

## Options [#options]

### `feedbackPlugin()` [#feedbackplugin]

### FeedbackPluginOptions

| Prop                    | Type                                                                  | Description                                                                                           |
| ----------------------- | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| `onPageFeedbackAction?` | `((feedback: PageFeedback) => Promise<ActionResponse>) \| undefined`  | Handles page feedback on the server, at `/api/feedback/page`. A thrown `Response` becomes the answer. |
| `onTextFeedbackAction?` | `((feedback: BlockFeedback) => Promise<ActionResponse>) \| undefined` | Handles feedback on selected text, like `onPageFeedbackAction`, at `/api/feedback/text`.              |

### `githubFeedbackPlugin()` [#githubfeedbackplugin]

### GitHubFeedbackPluginOptions

| Prop         | Type                                                 | Description                                                                         |
| ------------ | ---------------------------------------------------- | ----------------------------------------------------------------------------------- |
| `storage`    | `{ owner: string; repo: string; category: string; }` | The repository that stores feedback.                                                |
| `appId`      | `string`                                             | The ID of the GitHub App installed on the repository, which writes the discussions. |
| `privateKey` | `string`                                             | The GitHub App's private key, in PKCS#1 as GitHub gives it, or in PKCS#8.           |

### `emailFeedbackPlugin()` [#emailfeedbackplugin]

### EmailFeedbackPluginOptions

| Prop             | Type                  | Description                                                                                                                           |
| ---------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `apiKey`         | `string`              | Your Resend API key, from the [Resend dashboard](https://resend.com/api-keys). Keep it secret: read it from the server's environment. |
| `from`           | `string`              | The sender, an address on a domain verified in Resend, like `Docs <feedback@example.com>`.                                            |
| `to`             | `string \| string[]`  | The address or addresses that receive feedback.                                                                                       |
| `subjectPrefix?` | `string \| undefined` | Text before every email's subject. Default: `"[Docs feedback]"`                                                                       |

### What a Handler Receives [#what-a-handler-receives]

### PageFeedback

| Prop      | Type              | Description                                          |
| --------- | ----------------- | ---------------------------------------------------- |
| `opinion` | `"good" \| "bad"` |                                                      |
| `url`     | `string`          | The full URL of the page the feedback was sent from. |
| `message` | `string`          |                                                      |

### BlockFeedback

| Prop        | Type     | Description                                          |
| ----------- | -------- | ---------------------------------------------------- |
| `url`       | `string` | The full URL of the page the feedback was sent from. |
| `blockId`   | `string` |                                                      |
| `message`   | `string` |                                                      |
| `blockBody` | `string` | The text the reader selected in the block.           |
