Building a Streaming AI Chat Web App with Modern Frontend Frameworks
This article presents a practical architecture for building reusable AI chat interfaces with modern frontend frameworks. It covers streaming communication, rich-text rendering, theme support, state management, security, accessibility, performance, testing, and deployment, with an emphasis on creating chat applications that are responsive, maintainable, and extensible.
As large language models continue to mature, web-based AI chat has become a common entry point for enterprise applications, knowledge assistants, and internal tools. A reusable chat template should be more than a combination of an input field and a message list. It should address the complete workflow, including streaming communication, rich-text rendering, theme adaptation, state management, security controls, and production delivery.
This article discusses a general technical approach to building a streaming AI chat web application with modern frontend frameworks and provides a practical design that can be implemented in real projects.
1. Goals and Overall Architecture
The main goals of a conversational web application can be summarized as follows:
- Fast response: Minimize time to first token and display incremental output as it arrives.
- Stable presentation: Ensure that long conversations, code blocks, formulas, and charts do not cause layout instability.
- Easy extensibility: Allow model services, rendering capabilities, and theme settings to be replaced or extended.
- Controlled security: Keep API keys out of the client, sanitize content, and redact sensitive information from logs.
A layered architecture is recommended:
- View layer: Handles the conversation list, message bubbles, input area, settings panel, and mobile layouts.
- State layer: Centrally manages conversations, messages, streaming fragments, loading states, errors, and user preferences.
- Service layer: Encapsulates streaming requests, cancellation, retries, heartbeats, and error normalization.
- Rendering layer: Processes lightweight markup, code highlighting, formula rendering, chart rendering, and security sanitization.
- Engineering layer: Manages build splitting, route-level lazy loading, testing, monitoring, and deployment.
The main value of this separation is decoupling. The view layer should not directly assemble protocol data, the service layer should not depend on UI state, and the rendering layer should not trust model output. When the model service changes, rendering capabilities are upgraded, or the theme system is redesigned, the scope of required changes remains manageable.
2. Implementing Streaming Conversations
Streaming conversations are commonly implemented with chunked transfer or server-sent events. The frontend must handle incremental data, message boundaries across chunks, abnormal interruptions, and user cancellation.
It is recommended to encapsulate the request in an independent service that exposes a consistent set of events, such as start, delta, done, error, and cancel.
Example pseudocode:
async function streamChat({ sessionId, messages, signal, onDelta, onDone, onError }) {const res = await fetch('/api/chat/stream', {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ sessionId, messages }),signal});if (!res.ok) throw new Error('request_failed');const reader = res.body.getReader();const decoder = new TextDecoder();let buffer = '';while (true) {const { value, done } = await reader.read();if (done) break;buffer += decoder.decode(value, { stream: true });const parts = buffer.split('\n\n');buffer = parts.pop() || '';for (const part of parts) {const line = part.split('\n').find(l => l.startsWith('data:'));if (!line) continue;const payload = line.slice(5).trim();if (payload === '[DONE]') return onDone();onDelta(JSON.parse(payload).text || '');}}onDone();}
Several implementation details are important:
- Create an
AbortControllerfor each request so that the request can be stopped immediately when the user switches conversations or clicks a stop button. - Filter out empty chunks and heartbeat messages.
- Normalize low-level errors into messages that can be shown to users.
- Store generated fragments separately from the final message to avoid triggering full-list re-renders for every incremental update.
3. Building a Rich-Text Rendering Pipeline
Model responses often contain headings, lists, links, code blocks, formulas, and chart descriptions. The rendering pipeline should follow the sequence of parse first, sanitize next, and enhance afterward.
During parsing, convert the text into an intermediate structure. During sanitization, remove dangerous tags and event attributes. During enhancement, add code highlighting, copy buttons, formula rendering, and chart rendering.
The pipeline can be divided into synchronous and asynchronous stages:
- The synchronous stage renders the basic structure so that content becomes visible quickly.
- The asynchronous stage handles more expensive enhancements, such as formulas and charts.
For code blocks, the copy button should use the original text rather than the highlighted HTML. For long conversations, use virtual scrolling or collapsible sections to avoid rendering a large number of DOM nodes at once.
Security must be built in by default because model output is untrusted:
- Never insert unsanitized HTML directly.
- Validate link protocols.
- Escape code block content.
- Restrict executable expressions in chart configurations.
- Provide a plain-text fallback for copying and exporting content.
4. Themes, Interactions, and Accessibility
A theme system should be based on design tokens. Colors, font sizes, spacing, border radii, and shadows should all be managed through variables, with light and dark themes switching token values rather than requiring separate component implementations.
Both themes should be tested across message bubbles, the input area, code blocks, quoted content, and error messages. This helps prevent insufficient contrast in individual components.
The interaction layer should provide features such as:
- Keyboard shortcuts for sending messages
- Stop generation
- Regenerate response
- Copy message
- Clear conversation
- Theme switching
- Safe-area support on mobile devices
For accessibility, message update regions should use an appropriate live-announcement strategy. Buttons need readable labels, keyboard focus must remain visible, and color contrast should meet generally accepted accessibility guidelines.
5. State Management and Persistence
The state layer should be divided by domain, including:
- Conversation metadata
- Message lists
- Streaming fragments
- Request status
- User settings
Persistence should store only necessary fields, such as conversation titles, message summaries, and theme preferences. Sensitive content and temporary streaming fragments should not be written to long-term local storage.
Include a version number and migration functions in the persistence model. This prevents outdated data structures from causing a blank screen after the template is upgraded.
Cleanup policies are equally important. The application should support:
- Clearing all local data with one action
- Deleting individual conversations
- Cleaning up data on sign-out
- Storage limits and fallback behavior
- Reverting to in-memory state when persistence fails, while notifying the user
6. Performance, Testing, and Deployment
Performance improvements should be applied in combination rather than relying on a single optimization. Useful techniques include route-level lazy loading, on-demand loading of rendering components, virtualization for long lists, request concurrency limits, and caching strategies.
Monitoring should track metrics such as:
- Time to first token
- Streaming completion rate
- Error rate
- Rendering duration
- Cancellation rate
Logs must be sanitized and should not contain complete prompts or API keys.
Testing should cover:
- Streaming chunk boundaries
- Cancellation and retry behavior
- Abnormal responses
- Rich-text sanitization
- Theme switching
- Persistence migrations
- Mobile layouts
For deployment, a general cloud environment such as Baidu AI Cloud can organize the application around common capabilities, including container execution, object storage, logging, monitoring, and alerting. Frontend static assets and backend streaming APIs should be deployed separately to support gradual releases and elastic scaling.
Conclusion
The value of a high-quality streaming AI chat template does not come from accumulating isolated features. It comes from coordinating communication, rendering, state management, security, and engineering practices as one system.
By focusing on five principles—cancellable streaming, sanitized rendering, migratable state, observable performance, and scalable deployment—developers can build conversational web applications that are stable today and easier to evolve over time.
