100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
HomeBlogBuild a React Chatbot with the OpenAI API
Programming

Build a React Chatbot with the OpenAI API

SV

SkillVeris Team

Engineering Team

Dec 8, 2024 11 min read
Share:
Build a React Chatbot with the OpenAI API
Key Takeaway

A production-safe React chatbot never calls the OpenAI API directly from the browser — the key must live behind a backend proxy.

In this guide, you'll learn:

  • Streaming responses token-by-token dramatically improves perceived speed even when total response time is unchanged.
  • Conversation history must be resent with every request because the API itself is stateless between calls.
  • Rate limiting and per-user request caps are what actually control your OpenAI bill, not client-side throttling alone.
  • A minimal working chatbot needs only three pieces: a message-list component, an input form, and one backend route.

1What Does It Take to Build a React Chatbot with the OpenAI API?

Building a React chatbot with the OpenAI API takes three components working together: a React frontend for the chat interface, a lightweight backend proxy that holds your API key and forwards requests, and a state layer that tracks conversation history so the model has context across turns.

This is different from wiring the OpenAI API into a script or notebook. A real chatbot needs to handle streaming output so replies feel instant, manage growing conversation history without blowing past token limits, and protect your API key from ever reaching a user's browser — where anyone with dev tools open could steal it and run up your bill.

This tutorial builds that system from scratch: the UI, the proxy, the streaming logic, and the security layer around it. By the end you will have a working chatbot you understand completely, not a black-box wrapper around someone else's boilerplate.

2Setting Up the Project: Why You Need a Backend Proxy

You need a backend proxy because the OpenAI API key must never be embedded in frontend JavaScript, since anything shipped to the browser — including environment variables prefixed for client use — is visible to anyone who opens the network tab or view-source.

Start with two folders: a React app (created with Vite or Create React App) for the frontend, and a small Node.js/Express server for the backend. The frontend only ever talks to your own backend, using a relative path like /api/chat. Your backend is the only thing that holds the real OPENAI_API_KEY, stored in a server-side .env file that is never bundled into the client build.

This separation matters for a second reason beyond security: it gives you a place to add logic OpenAI doesn't provide, like rate limiting, logging, content moderation, or swapping models without redeploying the frontend. Treat the backend as the actual 'brain' of your chatbot and the React app as purely presentational.

  • Frontend: React app, handles UI state and rendering only
  • Backend: Node/Express server, holds the API key and calls OpenAI
  • Environment: .env file on the server, never referenced by client code
  • Communication: frontend calls your backend, backend calls OpenAI

3Building the Chat UI: Message List and Input

The chat UI needs exactly two working parts: a scrollable message list that renders an array of message objects, and a form that captures user input and appends new messages to that array.

Model your state as an array of objects shaped like role and content, where role is 'user' or 'assistant'. Each new user message gets pushed to this array immediately on submit, followed by an empty placeholder assistant message that gets filled in as the streamed response arrives. Keep this array in a single useState hook (or a reducer if the app grows) so the message list and the API call logic share one source of truth.

For styling, distinguish user and assistant bubbles visually — alignment, color, or an avatar — and auto-scroll the container to the bottom on every new message using a ref and a scrollIntoView call inside a useEffect that fires when the message array changes. Disable the submit button while a response is streaming so users can't fire overlapping requests.

4Calling the OpenAI Chat Completions API from Your Backend

Your backend calls the OpenAI Chat Completions (or Responses) API by sending the accumulated message array plus a system prompt to OpenAI's endpoint using the official SDK, then relaying the result back to the frontend.

On the Express route handling POST requests to /api/chat, initialize the OpenAI client once at server startup using the API key from process.env. On each incoming request, take the messages array sent from the frontend, prepend a system message that defines the assistant's persona and constraints, and pass the whole array to the chat completions call along with your chosen model.

Keep the model and default parameters (temperature, max tokens) configured server-side, not accepted as arbitrary input from the client — this prevents users from manipulating cost or behavior by tampering with request payloads. Validate and cap the incoming message array length before forwarding it, since an unbounded array is both a cost risk and a token-limit risk.

5Handling Streaming Responses and Conversation History

Streaming works by having your backend request a streamed completion from OpenAI and forward each chunk to the frontend as it arrives, typically over Server-Sent Events or a chunked HTTP response, so the user sees words appear incrementally instead of waiting for the full reply.

On the backend, enable streaming in the API call, then as each chunk arrives, write it directly to the HTTP response stream without buffering. On the frontend, read the response body as a stream (using the Fetch API's reader), decode each chunk, and append it to the current assistant message's content in state — this is what produces the familiar typewriter effect.

Conversation history has to be managed explicitly because the API is stateless: it has no memory of previous calls. Every request must include the full relevant history. To avoid exceeding context limits on long conversations, truncate or summarize older turns once the history grows past a reasonable size — keeping the system prompt and the most recent several exchanges is usually enough for a general-purpose chatbot.

6Deployment and Security: Rate Limiting and Key Rotation

Deploying a React chatbot safely means adding rate limiting on your backend route, rotating your API key periodically, and scoping keys to the minimum permissions needed so a leak has limited impact.

Add per-IP or per-user rate limiting middleware on your /api/chat route to prevent a single client from sending unlimited requests and running up costs, and consider a daily or monthly usage cap enforced server-side as a hard stop. Log request volume so unusual spikes are visible before they become a large bill.

For key hygiene, generate a dedicated API key per project or environment rather than reusing one key everywhere, store it only in server environment variables or a secrets manager (never in source control), and rotate it on a schedule or immediately if you suspect exposure. Deploy the frontend as static files (Vercel, Netlify, or similar) and the backend as a separate service with its own environment variables — this keeps the key isolated from the deployed client bundle entirely. Once you're comfortable with this request-and-respond pattern, SkillVeris's AI Agents & Agentic Workflows course is a natural next step for learning how to give a chatbot like this tools, memory, and the ability to take multi-step actions on its own.

7Frequently Asked Questions

Q: Can I call the OpenAI API directly from React without a backend? A: Technically yes, but you should never do this in production because your API key would be visible in the browser's network requests, letting anyone extract it and use it at your expense.

Q: Which OpenAI model should I use for a chatbot? A: Choose based on your latency and cost requirements; smaller, faster models work well for casual conversation, while larger models are better for complex reasoning, and you can switch models server-side without touching the frontend.

Q: How do I keep the conversation on-topic? A: Use a system prompt that clearly defines the assistant's role, scope, and tone, and consider adding a moderation check on user input before it's sent to the model.

Q: Why does my chatbot forget earlier messages? A: The API doesn't retain memory between calls, so if your backend isn't resending the full (or summarized) conversation history with each request, the model has no way to know what was said before.

Q: How do I handle errors like rate limits or timeouts from OpenAI? A: Wrap your API call in a try/catch on the backend, return a clear error status to the frontend, and show the user a friendly retry prompt rather than a raw error message.

Q: Do I need a database to store chat history? A: Not for a basic session-based chatbot, since state can live in memory on the frontend, but a database becomes necessary if you want conversations to persist across page reloads or across devices for the same user.

📄

Get The Print Version

Download a PDF of this article for offline reading.

About the Publisher

SV

SkillVeris Team

Engineering Team

Our engineering writers turn abstract code concepts into hands-on, project-driven learning experiences.

View all posts

Never miss an update

Get the latest tutorials and guides delivered to your inbox.

No spam. Unsubscribe anytime.

Frequently Asked Questions

21 categories · pick one to explore

Does SkillVeris have a tech blog, and what does it cover?
Yes, the SkillVeris blog has over 500 articles covering AI and machine learning, programming, web development, DevOps, cloud, security, databases and career guidance. Articles are practical and answer-first, and many use the Learn Through Hobbies approach, teaching technical concepts through cricket, music, gaming or cooking analogies. Everything is free to read.
What is the SkillVeris tech glossary and how big is it?
The SkillVeris glossary is a free reference of roughly 2,000-plus technology terms, each with a clear plain-language definition. It spans AI, programming, web, DevOps, cloud, security and database vocabulary, so whenever a lesson, article or job description uses jargon you do not recognise, the glossary gives you a fast, reliable answer.
Are the developer cheat sheets on SkillVeris free to download?
The cheat sheets are completely free to use, like everything else on SkillVeris. Each sheet condenses a language or tool into its essential syntax, commands and patterns for quick reference while coding. They are designed for rapid lookup during real work, complementing the deeper explanations found in study notes and courses.
Which programming references and cheat sheets are available?
Cheat sheets cover the platform's main domains, including programming languages, AI and ML tooling, web development, DevOps, cloud, security and databases, matching the topics of the 37 live courses. Each sheet lists related reading links and hashtags, so you can jump from a quick reference into fuller study notes or blog articles.
How do I find the meaning of a technical term quickly?
Search the SkillVeris glossary, which holds around 2,000-plus terms with concise, plain-language definitions. Each entry gets to the point in its first sentence, then links to related reading like blog posts or study notes for deeper context. It is faster and more consistent than sifting through scattered search results.
Is the SkillVeris blog good for beginners learning to code?
Yes, many blog articles are written specifically for beginners, and the Learn Through Hobbies style makes them unusually approachable: you might learn Python concepts through cricket or understand APIs through cooking. With 500-plus articles across skill levels, beginners can start with fundamentals and keep reading as they advance, entirely free.
Can cheat sheets replace full courses for learning a language?
No, cheat sheets are references, not teaching tools; they assume you already understand the concepts and just need syntax or commands fast. To actually learn a language, take a structured SkillVeris course with its 24–40 lessons and assessments, then keep the cheat sheet beside you while practising in Code Lab.
How often are new blog articles published on SkillVeris?
The blog grows regularly and already exceeds 500 articles, with new posts added as courses launch and technologies evolve. Topics track the platform's catalogue across AI, programming, web development, DevOps, cloud and security, so checking the Blog section periodically surfaces fresh tutorials, explainers and career-focused pieces, all free to read.
Does the glossary cover AI and machine learning terms?
Yes, AI and machine learning vocabulary is a major part of the roughly 2,000-plus term glossary, covering everything from foundational terms to modern concepts around LLMs, RAG and MLOps. Definitions are plain-language and answer-first, which helps when dense AI papers or course lessons throw unfamiliar jargon at you.
Are there cheat sheets for interview preparation?
Cheat sheets work well as interview-day refreshers because they compress syntax, commands and key concepts into scannable references. For dedicated preparation, combine them with the SkillVeris interview questions feature, which includes readiness scoring, plus study notes for depth. Reviewing a relevant cheat sheet just before an interview steadies recall under pressure.
Can I read the tech blog without signing up?
Yes, the blog is freely readable, and SkillVeris never charges for content. All 500-plus articles are open, covering tutorials, concept explainers and career advice. Creating a free account adds value elsewhere on the platform, like course progress tracking and certificates, but reading the blog requires no commitment at all.
How is the SkillVeris glossary different from Wikipedia?
The glossary is purpose-built for learners: definitions are short, plain-language and answer-first, sized for a quick lookup mid-lesson rather than a deep encyclopedic read. Entries also cross-link to related SkillVeris study notes, blog posts and courses, so a definition becomes a doorway into structured learning instead of a dead end.
Do blog articles use the Learn Through Hobbies method?
Many blog articles teach technical topics through hobby analogies, a hallmark of the SkillVeris blog, so you will find articles explaining programming through cricket, machine learning through music, or system design through cooking. The analogy is the teaching device; the article still delivers the real technical concept underneath.
Where can I find quick programming references while coding?
Open the SkillVeris cheat sheets, which are built exactly for that moment: compact, scannable references for syntax, commands and common patterns across languages and tools. Keep the relevant sheet in a browser tab while you work in Code Lab or your own editor, and dip into the glossary for terminology.
Is there a glossary entry for terms I meet in job descriptions?
Very likely yes, with roughly 2,000-plus terms across AI, programming, web, DevOps, cloud, security and databases, the glossary covers most jargon that appears in tech job descriptions. Decoding a listing this way helps you judge role fit honestly and prepares you to discuss those terms in interviews.
Are the blog articles written for the Indian tech audience?
The blog serves Indian learners plus a worldwide audience. Content stays globally relevant while acknowledging realities that matter in India, such as free access being essential for students and freshers, and career guidance that connects naturally to the SkillVeris jobs portal, which aggregates roles across India, UK, USA, Germany and Remote.
Can I suggest a topic for the blog or glossary?
SkillVeris content grows in response to what learners need, so feedback is welcome through the platform's support channels. If a term is missing from the glossary or a topic deserves an article, telling the team helps prioritise it. Meanwhile, the AI Mentor can answer the question immediately, 24/7, at any depth.
Do cheat sheets and glossary entries link to deeper learning?
Yes, every cheat sheet and glossary entry carries related reading links into study notes, blog articles and courses, plus concept hashtags for discovering similar content. This cross-linking means a thirty-second lookup can smoothly become a structured learning session whenever you decide you want more than a quick answer.
What makes SkillVeris programming references trustworthy?
The references are written to strict internal quality standards, kept consistent with the platform's 37 live courses, and never padded with invented statistics or hype. Definitions and cheat sheets are reviewed against the same content contracts that govern courses, and the answer-first style makes any inaccuracy easy to spot and correct.
How do the blog, glossary and cheat sheets fit into my learning routine?
Use them as satellites around your main course: read blog articles for context and motivation, hit the glossary the instant jargon appears, and keep cheat sheets open while coding. Together with study notes, Code Lab and the 24/7 AI Mentor, they turn passive reading into a complete, free learning system.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse