Building a Web-Based AI Chat Assistant with Vite and Vue 3

    This article explains how to build a web-based AI chat assistant with Vite, Vue 3, Pinia, and Arco Design Vue. It covers the message data model, a fetch-based SSE parser, secure Markdown and math rendering, Mermaid diagrams, theme switching, streaming performance optimizations, and deployment security considerations.

    1. Version Selection and Dependencies

    A web-based AI chat assistant frontend needs to handle four concerns: receiving streaming model output, rendering Markdown into safe HTML, supporting dark and light themes, and recovering state when network errors occur. This article uses the following stack:

    • Vite: The build tool for the development server, hot module replacement, and production bundling. The examples in this article are based on the Vite 7 series, which requires Node.js 20.19 or 22.12 and above.
    • Vue 3.5: Provides the Composition API and reactivity system.
    • Pinia: The officially recommended state management library, used to store conversations and message lists.
    • Arco Design Vue: An enterprise-grade UI component library that provides layout, button, and settings panel components.

    The table below lists the dependencies used in this example. These were the mainline versions at the time of writing. Before installing, verify the latest version with npm view <package-name> version and follow each project’s README.

    Dependency Purpose
    vue View layer
    pinia State management
    @arco-design/web-vue UI components
    markdown-it Markdown parsing
    highlight.js Code highlighting
    katex, @mdit/plugin-katex Math formulas
    mermaid Flowcharts and sequence diagrams
    dompurify HTML sanitization

    2. Project Initialization

    Create the project with the official scaffold and install dependencies:

    1. npm create vite@latest ai-chat -- --template vue-ts
    2. cd ai-chat
    3. npm i pinia @arco-design/web-vue markdown-it highlight.js katex @mdit/plugin-katex mermaid dompurify
    4. npm i -D @types/markdown-it

    The recommended directory structure separates the network layer, business logic, and UI:

    1. src/
    2. ├── api/ # API requests and SSE parsing
    3. ├── components/ # Message list, input box, settings panel
    4. ├── composables/ # Composable functions such as useChat and useTheme
    5. ├── stores/ # Pinia state modules
    6. ├── utils/ # Markdown rendering, Mermaid rendering
    7. └── App.vue

    Configure a path alias in vite.config.ts and proxy /api to the backend. The backend address only appears in the proxy configuration, and no model API keys appear in frontend code.

    1. import { defineConfig } from 'vite';
    2. import vue from '@vitejs/plugin-vue';
    3. import { fileURLToPath, URL } from 'node:url';
    4. export default defineConfig({
    5. plugins: [vue()],
    6. resolve: {
    7. alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) },
    8. },
    9. server: {
    10. proxy: {
    11. '/api': { target: 'http://localhost:8787', changeOrigin: true },
    12. },
    13. },
    14. });

    3. Message Structure and SSE Streaming Parsing

    Messages are the core data in a chat application. Define a unified message type so the frontend and backend exchange data using the same structure:

    1. export interface ChatMessage {
    2. id: string;
    3. role: 'user' | 'assistant' | 'system';
    4. content: string;
    5. createTime: number;
    6. status: 'pending' | 'streaming' | 'done' | 'error';
    7. meta: {
    8. reasoning: string;
    9. model?: string;
    10. usage?: { inputTokens: number; outputTokens: number };
    11. };
    12. }

    The backend returns data in SSE (Server-Sent Events) format. Each event consists of several lines, and events are separated by a blank line (\n\n). This article uses the following event types:

    • event: reasoning: Incremental text for the reasoning process.
    • event: answer: Incremental text for the final answer.
    • event: usage: Token statistics for the current call.
    • event: error: A server-side error.
    • event: done: The stream has ended.

    A data chunk may be split at any position, so the parser must first buffer incomplete content and parse a complete event only when it encounters a blank line. The following is a pure fetch implementation that does not depend on Axios:

    1. export interface SSEEvent {
    2. event: string;
    3. data: any;
    4. }
    5. function parseBlock(block: string): SSEEvent | null {
    6. let event = 'message';
    7. const dataLines: string[] = [];
    8. for (const line of block.split('\n')) {
    9. if (!line || line.startsWith(':')) continue; // Skip empty lines and comment lines
    10. const sep = line.indexOf(':');
    11. const field = sep === -1 ? line : line.slice(0, sep);
    12. let value = sep === -1 ? '' : line.slice(sep + 1);
    13. if (value.startsWith(' ')) value = value.slice(1);
    14. if (field === 'event') event = value;
    15. else if (field === 'data') dataLines.push(value);
    16. }
    17. if (dataLines.length === 0) return null;
    18. const raw = dataLines.join('\n');
    19. if (raw === '[DONE]') return { event: 'done', data: null };
    20. try {
    21. return { event, data: JSON.parse(raw) };
    22. } catch {
    23. console.warn('Unparseable SSE data ignored:', raw);
    24. return null;
    25. }
    26. }
    27. export async function* readSSE(response: Response): AsyncGenerator<SSEEvent> {
    28. if (!response.ok || !response.body) {
    29. throw new Error(`Request failed, HTTP ${response.status}`);
    30. }
    31. const reader = response.body.getReader();
    32. const decoder = new TextDecoder('utf-8');
    33. let buffer = '';
    34. while (true) {
    35. const { done, value } = await reader.read();
    36. if (done) break;
    37. buffer += decoder.decode(value, { stream: true });
    38. buffer = buffer.replace(/\r\n/g, '\n'); // Normalize line endings
    39. let idx: number;
    40. while ((idx = buffer.indexOf('\n\n')) !== -1) {
    41. const block = buffer.slice(0, idx);
    42. buffer = buffer.slice(idx + 2);
    43. const evt = parseBlock(block);
    44. if (evt) yield evt;
    45. }
    46. }
    47. // Process any remaining content after the stream ends
    48. buffer += decoder.decode();
    49. if (buffer.trim()) {
    50. const evt = parseBlock(buffer);
    51. if (evt) yield evt;
    52. }
    53. }

    When sending a request, pass the signal from an AbortController to fetch. When the user clicks “Stop generating”, the request can be aborted.

    1. export async function sendChat(
    2. messages: { role: string; content: string }[],
    3. assistant: ChatMessage,
    4. signal: AbortSignal,
    5. ) {
    6. const res = await fetch('/api/chat', {
    7. method: 'POST',
    8. headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream' },
    9. body: JSON.stringify({ messages }),
    10. signal,
    11. });
    12. assistant.status = 'streaming';
    13. for await (const evt of readSSE(res)) {
    14. switch (evt.event) {
    15. case 'reasoning':
    16. assistant.meta.reasoning += evt.data.delta;
    17. break;
    18. case 'answer':
    19. assistant.content += evt.data.delta;
    20. break;
    21. case 'usage':
    22. assistant.meta.usage = evt.data;
    23. break;
    24. case 'error':
    25. throw new Error(evt.data.message);
    26. case 'done':
    27. assistant.status = 'done';
    28. return;
    29. }
    30. }
    31. assistant.status = 'done';
    32. }

    Reasoning content and the final answer are written to different fields. In the UI, display meta.reasoning in a collapsible panel that is collapsed by default and can be expanded when needed.

    4. Markdown, Math, and Code Highlighting

    The rendering pipeline has three steps: parse text with Markdown-it, process formulas with a plugin, and sanitize HTML with DOMPurify. The html option must be set to false, so raw HTML tags produced by the model are displayed as plain text.

    1. import MarkdownIt from 'markdown-it';
    2. import hljs from 'highlight.js';
    3. import { katex } from '@mdit/plugin-katex';
    4. import 'katex/dist/katex.min.css';
    5. import DOMPurify from 'dompurify';
    6. const md: MarkdownIt = new MarkdownIt({
    7. html: false,
    8. linkify: true,
    9. highlight(str, lang) {
    10. // Mermaid code blocks are handled by the dedicated renderer
    11. if (lang === 'mermaid') {
    12. return `<pre class="mermaid-placeholder" data-mermaid="${md.utils.escapeHtml(str)}"></pre>`;
    13. }
    14. if (lang && hljs.getLanguage(lang)) {
    15. const code = hljs.highlight(str, { language: lang, ignoreIllegals: true }).value;
    16. return `<pre class="hljs"><code>${code}</code></pre>`;
    17. }
    18. return `<pre class="hljs"><code>${md.utils.escapeHtml(str)}</code></pre>`;
    19. },
    20. });
    21. md.use(katex, { throwOnError: false });
    22. export function renderMarkdown(src: string): string {
    23. return DOMPurify.sanitize(md.render(src));
    24. }

    Markdown-it outputs the return value of highlight as-is, provided the return value starts with <pre. Therefore, all three branches above return <pre> tags. throwOnError: false means that if formula syntax is invalid, KaTeX displays the original formula as red text instead of failing to render the entire message. For other plugin options, follow the README of @mdit/plugin-katex.

    Use v-html in the Vue component to display the result. The output has already been sanitized with DOMPurify before rendering, so it is safe here. If even one path bypasses sanitization, v-html introduces a cross-site scripting (XSS) vulnerability, so never bind unsanitized strings directly to v-html.

    1. <script setup lang="ts">
    2. import { computed } from 'vue';
    3. import { renderMarkdown } from '@/utils/markdown';
    4. import type { ChatMessage } from '@/stores/chat';
    5. const props = defineProps<{ message: ChatMessage }>();
    6. const html = computed(() => renderMarkdown(props.message.content));
    7. </script>
    8. <template>
    9. <div class="markdown-body" v-html="html" />
    10. </template>

    5. Mermaid Diagram Rendering

    Mermaid has a relatively large dependency, so load it on demand. Render diagrams only after the message status becomes done to avoid repeatedly parsing incomplete syntax during streaming.

    1. import DOMPurify from 'dompurify';
    2. import type mermaidType from 'mermaid';
    3. type MermaidApi = typeof mermaidType;
    4. let mermaidPromise: Promise<MermaidApi> | null = null;
    5. let seq = 0;
    6. function loadMermaid(dark: boolean): Promise<MermaidApi> {
    7. if (!mermaidPromise) {
    8. mermaidPromise = import('mermaid').then(({ default: m }) => {
    9. m.initialize({
    10. startOnLoad: false,
    11. securityLevel: 'strict', // Disable scripts and click events in diagrams
    12. theme: dark ? 'dark' : 'default',
    13. });
    14. return m;
    15. });
    16. }
    17. return mermaidPromise;
    18. }
    19. export async function renderMermaid(code: string, container: HTMLElement, dark = false) {
    20. const m = await loadMermaid(dark);
    21. const id = `mermaid-${Date.now()}-${seq++}`; // Use a unique id for each render
    22. try {
    23. const { svg, bindFunctions } = await m.render(id, code);
    24. container.innerHTML = DOMPurify.sanitize(svg, {
    25. USE_PROFILES: { svg: true, svgFilters: true },
    26. });
    27. bindFunctions?.(container);
    28. } catch (err) {
    29. container.textContent = `Mermaid syntax error: ${(err as Error).message}`;
    30. }
    31. }

    There are three points to note:

    1. mermaid.render requires a unique container id. If parsing fails, Mermaid may leave temporary nodes in the page, so production environments should clean them up periodically.
    2. mermaid.initialize only needs to be called once during initialization. After switching themes, reinitialize and rerender existing diagrams.
    3. The SVG returned by render is a string. It must be sanitized before being inserted directly with innerHTML. securityLevel: 'strict' reduces risk, but DOMPurify is still the second line of defense.

    In the component, find placeholder elements and render them after the message is complete:

    1. <script setup lang="ts">
    2. import { nextTick, ref, watch } from 'vue';
    3. import { renderMermaid } from '@/utils/mermaid';
    4. import type { ChatMessage } from '@/stores/chat';
    5. const props = defineProps<{ message: ChatMessage; dark: boolean }>();
    6. const root = ref<HTMLElement>();
    7. watch(
    8. () => props.message.status,
    9. async (status) => {
    10. if (status !== 'done') return;
    11. await nextTick();
    12. root.value?.querySelectorAll<HTMLElement>('pre.mermaid-placeholder').forEach((el) => {
    13. renderMermaid(el.dataset.mermaid ?? '', el, props.dark);
    14. });
    15. },
    16. );
    17. </script>
    18. <template>
    19. <div ref="root" class="markdown-body" v-html="html" />
    20. </template>

    6. Theme Switching

    Theme state includes both the user’s manual choice and the system preference. The user’s choice takes priority; if no choice has been made, follow the system. Arco Design’s dark mode is controlled by the arco-theme attribute on body. This project also sets data-theme on html for custom CSS variables.

    1. import { computed, onMounted, onUnmounted, ref, watchEffect } from 'vue';
    2. type Theme = 'light' | 'dark';
    3. const STORAGE_KEY = 'theme';
    4. const mql = window.matchMedia('(prefers-color-scheme: dark)');
    5. const userPref = ref<Theme | null>(readStored());
    6. const systemTheme = ref<Theme>(mql.matches ? 'dark' : 'light');
    7. const theme = computed<Theme>(() => userPref.value ?? systemTheme.value);
    8. function readStored(): Theme | null {
    9. const value = localStorage.getItem(STORAGE_KEY);
    10. return value === 'light' || value === 'dark' ? value : null;
    11. }
    12. function applyTheme(t: Theme) {
    13. document.documentElement.setAttribute('data-theme', t);
    14. if (t === 'dark') {
    15. document.body.setAttribute('arco-theme', 'dark');
    16. } else {
    17. document.body.removeAttribute('arco-theme');
    18. }
    19. }
    20. const onSystemChange = (e: MediaQueryListEvent) => {
    21. systemTheme.value = e.matches ? 'dark' : 'light';
    22. };
    23. export function useTheme() {
    24. onMounted(() => mql.addEventListener('change', onSystemChange));
    25. onUnmounted(() => mql.removeEventListener('change', onSystemChange));
    26. watchEffect(() => applyTheme(theme.value));
    27. function setTheme(t: Theme | null) {
    28. userPref.value = t;
    29. if (t) localStorage.setItem(STORAGE_KEY, t);
    30. else localStorage.removeItem(STORAGE_KEY);
    31. }
    32. return { theme, setTheme };
    33. }

    The matchMedia listener is removed with removeEventListener when the component unmounts. If it is not removed, every mount adds another callback, and long-running usage accumulates memory and duplicate calculations. localStorage reads and writes may throw due to private mode or storage quotas, so production code should wrap them in try/catch.

    7. Performance and Reliability

    1. Throttle streaming rendering: Model output may arrive dozens of times per second, and rerendering Markdown on every update can cause jank. The batcher below merges updates within the same frame and updates at most once per frame:
    1. export function createBatcher(flush: (text: string) => void) {
    2. let pending = '';
    3. let frame = 0;
    4. const schedule = () => {
    5. if (frame) return;
    6. frame = requestAnimationFrame(() => {
    7. frame = 0;
    8. if (pending) {
    9. flush(pending);
    10. pending = '';
    11. }
    12. });
    13. };
    14. return {
    15. push(text: string) {
    16. pending += text;
    17. schedule();
    18. },
    19. // Call when the stream ends or is interrupted to ensure the last part is not lost
    20. flushNow() {
    21. if (frame) {
    22. cancelAnimationFrame(frame);
    23. frame = 0;
    24. }
    25. if (pending) {
    26. flush(pending);
    27. pending = '';
    28. }
    29. },
    30. };
    31. }
    1. Virtual list: When there are many historical messages, use a virtual scrolling component to render only message items in the visible area.
    2. Request abort: When the user stops generation, call controller.abort() and call flushNow() in finally, then set the status to done or error.
    3. Token statistics: Display the input and output token counts from meta.usage so users can understand the cost of a call.
    4. Error retry: Show a “Retry” button on network errors or timeouts. When retrying, rebuild the message history from the original user input instead of asking the user to type it again.

    8. Deployment and Security

    Frontend static files can be hosted on any web server or object storage. The backend forwards model requests and handles the response headers required for SSE. For example, with Node.js, an SSE response needs the following headers, and buffering in the reverse proxy must be disabled; otherwise, streaming content will be accumulated into a single large chunk before being returned:

    1. res.writeHead(200, {
    2. 'Content-Type': 'text/event-stream; charset=utf-8',
    3. 'Cache-Control': 'no-cache, no-transform',
    4. Connection: 'keep-alive',
    5. 'X-Accel-Buffering': 'no', // Disable buffering when using an Nginx reverse proxy
    6. });

    For security, note the following:

    • Model API keys should only be stored in backend environment variables or a secrets management service. Do not write them into frontend code or logs.
    • All model output must be sanitized with DOMPurify before rendering with v-html, including Markdown, formulas, and SVG generated by Mermaid.
    • The backend should add sensitive-word filtering, per-user rate limiting, and audit logs, and enforce an upper limit on input message length.
    • Message history sent from the client is also untrusted data. The backend should validate the role field to prevent users from forging system messages and changing model behavior.

    Following these steps, you can build a web-based AI chat assistant that supports streaming output, reasoning display, formula and diagram rendering, theme switching, and basic security protection.