How to Build a ChatGPT-Style Chat UI in Plain HTML, CSS and JavaScript
You don't need React, a bundler or a component library to build a good chat interface. A chat screen is a scrolling list of messages and a text box. The tricky parts are streaming text as it arrives, rendering markdown safely, and keeping scrolling and keyboard behaviour pleasant. This guide covers each one with plain HTML, CSS and JavaScript.
1. The HTML structure
Three regions: a header, the message thread and the composer.
<div class="chat">
<header class="chat-head">Assistant</header>
<main id="thread" class="thread" aria-live="polite"></main>
<form id="composer" class="composer">
<label for="msg" class="sr-only">Message</label>
<textarea id="msg" rows="1" placeholder="Ask anything"></textarea>
<button type="submit" id="send">Send</button>
</form>
</div>
Use a real <form> so the submit button works with the keyboard and screen readers. The aria-live="polite" region tells assistive technology that new content appears there.
2. The CSS layout
A full-height column where only the thread scrolls:
.chat { display: flex; flex-direction: column; height: 100dvh; }
.thread { flex: 1; overflow-y: auto; padding: 1rem; }
.composer { display: flex; gap: .5rem; padding: .75rem;
border-top: 1px solid #ddd; }
.composer textarea { flex: 1; resize: none; max-height: 40vh; }
.msg { max-width: 70ch; margin: 0 auto 1rem; line-height: 1.55; }
.msg.user { background: #eef2ff; border-radius: 12px; padding: .6rem .9rem; }
100dvh (dynamic viewport height) avoids the mobile issue where the browser's address bar hides the composer. Limit message width to around 70 characters for readability, and use CSS custom properties for colours so a theme is one block of variables.
3. Sending a message
Handle submit, Enter to send and Shift+Enter for a new line:
const form = document.getElementById('composer');
const input = document.getElementById('msg');
const thread = document.getElementById('thread');
const history = [];
let controller; // used by the Stop button
input.addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) {
e.preventDefault();
form.requestSubmit();
}
});
form.addEventListener('submit', e => {
e.preventDefault();
const text = input.value.trim();
if (!text) return;
input.value = '';
addMessage('user', text);
history.push({ role: 'user', content: text });
streamReply();
});
Checking isComposing matters for people typing Japanese, Chinese or Korean: Enter confirms a character there, and shouldn't send the message.
Auto-grow the textarea by setting its height to auto and then to scrollHeight on every input event, capped by the CSS max-height.
4. Streaming the reply
Never put an API key in front-end code — anyone can read it. Send messages to your own small server endpoint, which adds the key and forwards the request to the model provider. Most providers can stream responses as server-sent events (SSE): lines starting with data: separated by blank lines.
In the browser, read the response body as a stream:
async function streamReply() {
const el = addMessage('assistant', '');
let text = '';
const res = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages: history }),
signal: (controller = new AbortController()).signal
});
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 events = buffer.split('\n\n');
buffer = events.pop();
for (const ev of events) {
const line = ev.split('\n').find(l => l.startsWith('data:'));
if (!line) continue;
const data = line.slice(5).trim();
if (data === '[DONE]') continue;
text += JSON.parse(data).delta || '';
render(el, text);
}
}
history.push({ role: 'assistant', content: text });
}
Three details make this robust:
{ stream: true }indecodekeeps multi-byte characters (accents, emoji) intact when they're split across chunks.- Keep the incomplete last event in
buffer. Network chunks don't line up with events. - The
deltafield is your own format. Have your server translate the provider's event format into something simple, so the front end doesn't change if you switch models.
A stop button
Keep the AbortController in a variable and call controller.abort() when the user clicks Stop. Wrap the loop in try/catch and treat an AbortError as a normal end, keeping the partial text.
5. Rendering markdown safely
Models reply in markdown: code blocks, lists, bold. The danger is that model output can contain HTML, and inserting it with innerHTML unescaped is an injection risk. The safe order is escape first, then format:
const esc = s => s.replace(/[&<>"']/g, c =>
({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
function md(src) {
const parts = src.split('```');
return parts.map((p, i) => {
if (i % 2) { // inside a code fence
const body = p.replace(/^[^\n]*\n/, '');
return `<pre><code>${esc(body)}</code></pre>`;
}
return esc(p)
.replace(/`([^`]+)`/g, '<code>$1</code>')
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
.replace(/\n{2,}/g, '</p><p>')
.replace(/^/, '<p>').replace(/$/, '</p>');
}).join('');
}
While streaming, the text often ends mid-fence. Splitting on the fence marker handles that naturally: an unclosed fence simply renders as a code block until the closing marker arrives. If you allow links, only accept http: and https: URLs, and add rel="noopener".
Re-rendering the whole message on every chunk is fine for typical reply lengths. If replies get very long, throttle rendering to once per animation frame with requestAnimationFrame.
6. Copy buttons on code blocks
After rendering, add a button to each pre:
el.querySelectorAll('pre').forEach(pre => {
const b = document.createElement('button');
b.type = 'button';
b.textContent = 'Copy';
b.onclick = () => navigator.clipboard.writeText(pre.innerText);
pre.prepend(b);
});
The Clipboard API needs a secure context (HTTPS or localhost). Give feedback by changing the label to "Copied" for a second.
7. Scrolling that doesn't fight the user
Auto-scroll to new text only if the user is already near the bottom. If they've scrolled up to reread something, leave them there:
const nearBottom = () =>
thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80;
Check nearBottom() before rendering each chunk, and scroll afterwards only if it was true.
8. Saving the conversation
For a simple single-user app, store history in localStorage after each reply and restore it on load. Keep it small: trim old messages, and remember that the model needs the history too, which costs tokens.
9. Accessibility checklist
| Item | Why |
|---|---|
Real <form>, <button>, <label> | Keyboard and screen-reader support for free |
aria-live="polite" on the thread | New messages are announced |
Set aria-busy="true" while streaming | Avoids announcing every token |
| Visible focus styles | Keyboard users can see where they are |
| Colour contrast of at least 4.5:1 for text | Readable in light and dark themes |
prefers-reduced-motion | Turn off typing animations for those who ask |
Skip the boilerplate
If you'd rather start from working code, Nimbus Lite is a free, single-screen chat UI in plain HTML, CSS and JS: header, thread and composer, starter prompts, copy-to-clipboard, a conversation saved in the browser and Enter / Shift+Enter handling. It runs with demo replies, so no API key is needed; to connect a model, replace the marked replyTo() function in js/nimbus-lite.js with a fetch() to your endpoint. The code is open source on GitHub and there's a live demo.
The paid Nimbus AI Chat UI Kit is the fuller version: streaming messages, code blocks with copy buttons, a model dropdown, light and dark mode, 5 accent colours and a README showing where to plug in your API. If you're building agent tooling, Aether is a six-screen agent dashboard in the same no-build style, including a conversation view and run traces.
Frequently asked questions
Can I build a ChatGPT-like interface without React?
Yes. A chat UI is a form and a scrolling list. Plain HTML, CSS and the browser's fetch streaming API cover everything, including token-by-token streaming.
How do I stream an OpenAI or Anthropic response in the browser?
Call your own server endpoint, which holds the API key and forwards the request with streaming enabled. In the browser, read the response with response.body.getReader() and a TextDecoder, and append each text delta to the message.
Is it safe to put my API key in JavaScript?
No. Anything in front-end code is visible to users. Keep the key on a server or serverless function and call that from the browser.
How do I render markdown from an LLM safely?
Escape all HTML in the model's output first, then convert a small set of markdown patterns such as code fences, inline code and bold. Never insert unescaped model output with innerHTML.
How do I stop the chat from jumping while I scroll?
Only auto-scroll when the user is already near the bottom of the thread before each update.