Executive Verdict & Key Takeaways
Build a Next.js Chatbot with OpenAI Responses API
Create a small, working web chatbot with the Next.js App Router, the official OpenAI JavaScript SDK, and the Responses API. The browser sends a message to your own server route; that route, not the browser, calls OpenAI.
What you will build
This tutorial builds a request-and-response chatbot. A visitor writes a message, Next.js posts it to /api/chat, and the server route calls the OpenAI Responses API. The returned text is appended to the chat window. This is deliberately a compact foundation: it proves the data flow and protects the API key without pretending to include production features such as user accounts, saved conversations, streaming, or a knowledge base.
The verified OpenAI developer resources surface the Responses API, conversation state, streaming, token counting, background mode, webhooks, and a migration guide as separate topics. That separation matters. A basic chatbot does not need every advanced capability on day one. Start with a reliable server-side call, then choose conversation state, streaming, and other features only when a product requirement justifies them.
The example selects gpt-5.6, which appears in the current OpenAI developer resource navigation. The model is configured through an environment variable so the application code does not need to change when your team adopts a different permitted model.
Prerequisites
Building internal business apps or AI workflows from scratch?
Skip boilerplate schemas and CRUD setup. Generate a live PostgreSQL-backed Micro-ERP in minutes.
- Node.js 18 or later.
- An OpenAI API key available through your OpenAI platform account.
- Basic familiarity with JavaScript, React, and the command line.
- A new or existing Next.js project using the App Router.
Do not put an OpenAI key in client-side code, a component marked with 'use client', a public repository, or an environment variable beginning with NEXT_PUBLIC_. Variables with that prefix are designed for browser exposure. In this project, only the route handler reads OPENAI_API_KEY.
Step 1: Create the Next.js project
Create a fresh application, enter its directory, and install the official OpenAI JavaScript SDK. When prompted by create-next-app, choose JavaScript and enable the App Router. The code below assumes the default app directory structure.
npx create-next-app@latest nextjs-openai-chatbot
cd nextjs-openai-chatbot
npm install openai
npm run devOpen http://localhost:3000. The starter screen confirms that Next.js is running before you add any AI integration. Stop the server with Ctrl+C before changing configuration if your local workflow requires it.
The resulting files relevant to this tutorial are:
nextjs-openai-chatbot/
├── app/
│ ├── api/
│ │ └── chat/
│ │ └── route.js
│ ├── globals.css
│ ├── layout.js
│ └── page.js
├── .env.local
└── package.jsonUsing the App Router avoids the routing mismatch in the original draft. Route handlers belong in app/api/.../route.js and can export methods such as POST. The older pages/api convention uses a different handler shape.
Step 2: Add server-only environment variables
At the project root, create .env.local. Replace the example key with your real key. Keep the model in a separate variable so it can be changed without editing route logic.
OPENAI_API_KEY=your_openai_api_key
OPENAI_MODEL=gpt-5.6Never commit .env.local. If you use source control, check that the file is ignored before adding files. Restart npm run dev after adding or editing environment variables so Next.js loads the current values.
There is intentionally no NEXT_PUBLIC_API_ENDPOINT in this setup. The client does not call an OpenAI endpoint directly. It calls the relative internal endpoint /api/chat, while the server-side SDK handles the OpenAI request.
Step 3: Create the Responses API route
Create app/api/chat/route.js. This complete route validates the incoming JSON shape, limits the conversation sent by this demo to the latest 20 messages, calls the Responses API, and returns plain JSON. The message limit is an application choice to keep the example bounded; it is not an OpenAI platform limit.
import OpenAI from 'openai';
export const runtime = 'nodejs';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
export async function POST(request) {
if (!process.env.OPENAI_API_KEY) {
return Response.json(
{ error: 'OPENAI_API_KEY is not configured on the server.' },
{ status: 500 }
);
}
try {
const body = await request.json();
const messages = Array.isArray(body.messages) ? body.messages : null;
if (!messages || messages.length === 0) {
return Response.json(
{ error: 'Send a non-empty messages array.' },
{ status: 400 }
);
}
const input = messages.slice(-20).map((message) => ({
role: message.role === 'assistant' ? 'assistant' : 'user',
content: String(message.content || '').slice(0, 4000),
}));
if (input.some((message) => message.content.trim().length === 0)) {
return Response.json(
{ error: 'Every message must contain text.' },
{ status: 400 }
);
}
const response = await openai.responses.create({
model: process.env.OPENAI_MODEL || 'gpt-5.6',
input,
});
const content = response.output_text.trim();
return Response.json({
message: {
role: 'assistant',
content: content || 'I could not generate a text response.',
},
});
} catch (error) {
console.error('Chat route error:', error);
return Response.json(
{ error: 'The chat request could not be completed.' },
{ status: 500 }
);
}
}This uses the modern SDK client pattern: instantiate OpenAI with an options object, then call openai.responses.create(). It does not use deprecated global SDK methods. The route returns only the text needed by the interface and does not return secrets or raw server errors to the browser.
For a multi-user product, do not treat the browser-supplied array as durable conversation storage. The verified OpenAI resources include conversation-state guidance. Review that guidance when you are ready to introduce durable history or server-managed continuity.
Step 4: Build the chat interface
Replace app/page.js with the following client component. It keeps messages in browser memory for this session. It disables the form while a request is in progress, handles unsuccessful API responses, and uses a form submit event so both Enter and the Send button work.
'use client';
import { useState } from 'react';
export default function Home() {
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState('');
async function sendMessage(event) {
event.preventDefault();
const text = input.trim();
if (!text || isLoading) return;
const userMessage = { role: 'user', content: text };
const nextMessages = [...messages, userMessage];
setMessages(nextMessages);
setInput('');
setError('');
setIsLoading(true);
try {
const response = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ messages: nextMessages }),
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Request failed.');
}
setMessages((currentMessages) => [
...currentMessages,
data.message,
]);
} catch (requestError) {
setError(requestError.message || 'Something went wrong.');
} finally {
setIsLoading(false);
}
}
return (
<main className="chat-shell">
<section className="chat-card" aria-labelledby="chat-title">
<h1 id="chat-title">Next.js OpenAI Chatbot</h1>
<p className="intro">
A minimal chatbot powered by a server-side Responses API route.
</p>
<div className="messages" aria-live="polite">
{messages.length === 0 ? (
<p className="empty-state">Ask a question to start the conversation.</p>
) : (
messages.map((message, index) => (
<article
className={`message message--${message.role}`}
key={`${message.role}-${index}-${message.content}`}
>
<strong>{message.role === 'user' ? 'You' : 'Assistant'}</strong>
<p>{message.content}</p>
</article>
))
)}
{isLoading && (
<p className="loading">Assistant is responding…</p>
)}
</div>
<form className="composer" onSubmit={sendMessage}>
<label htmlFor="message">Your message</label>
<textarea
id="message"
value={input}
onChange={(event) => setInput(event.target.value)}
placeholder="Type your question"
rows="4"
disabled={isLoading}
/>
<button type="submit" disabled={isLoading || !input.trim()}>
{isLoading ? 'Sending…' : 'Send'}
</button>
</form>
{error && <p className="error" role="alert">{error}</p>}
</section>
</main>
);
}SWR is not needed here. The chat is not polling a server-owned message feed; it is making one API request after the user submits a message. Polling would add repeated requests and does not create token-by-token output. If your product needs streamed output, consult the verified OpenAI streaming documentation and implement streaming across both the route and the browser UI.
Step 5: Add readable styles
Replace the contents of app/globals.css with this small stylesheet. It is presentation only; it does not change the API behavior.
* { box-sizing: border-box; }
body {
margin: 0;
background: #f4f7fb;
color: #172033;
font-family: Arial, sans-serif;
}
.chat-shell {
min-height: 100vh;
display: grid;
place-items: center;
padding: 24px;
}
.chat-card {
width: min(760px, 100%);
background: #ffffff;
border: 1px solid #d9e0ea;
border-radius: 16px;
padding: 24px;
box-shadow: 0 12px 35px rgba(23, 32, 51, 0.08);
}
.intro, .empty-state, .loading { color: #526075; }
.messages {
min-height: 260px;
margin: 24px 0;
display: grid;
gap: 12px;
}
.message {
border-radius: 12px;
padding: 12px 16px;
max-width: 85%;
}
.message p { margin: 8px 0 0; white-space: pre-wrap; }
.message--user { justify-self: end; background: #dcecff; }
.message--assistant { justify-self: start; background: #eef1f5; }
.composer { display: grid; gap: 10px; }
textarea {
width: 100%;
resize: vertical;
padding: 12px;
border: 1px solid #aeb9c9;
border-radius: 8px;
font: inherit;
}
button {
width: fit-content;
padding: 10px 16px;
border: 0;
border-radius: 8px;
background: #155eef;
color: white;
font: inherit;
cursor: pointer;
}
button:disabled { opacity: 0.55; cursor: not-allowed; }
.error { color: #b42318; margin: 16px 0 0; }Step 6: Test the chatbot
Start the development server:
npm run devVisit http://localhost:3000, enter a short question, and select Send. In a successful flow, your message appears immediately, the interface displays a temporary responding state, and the assistant response appears after the route returns JSON.
If you receive the message that OPENAI_API_KEY is not configured, confirm that .env.local is at the project root, the variable name is exact, and you restarted the development server. If the browser reports that the request could not be completed, inspect the terminal running Next.js. The route logs the underlying error there, while the browser receives a generic message.
GCC and Middle East implementation considerations
A chatbot intended for organizations in Saudi Arabia, the UAE, or the wider GCC should be tested with the actual languages and workflows its users need. For example, test Arabic prompts, English prompts, mixed Arabic-English terms, regional names, dates, and product vocabulary. Do not assume that an English-only evaluation represents the user experience of a regional audience.
Before collecting customer, employee, or applicant messages, define what information users may submit, how long conversation data is retained, who can access it, and how users are informed. Review the requirements that apply to your organization and deployment location. This tutorial stores messages only in browser memory during the open page session, but any later addition of a database, authentication system, analytics, or support workflow changes the data-handling scope.
For Arabic-first interfaces, consider right-to-left layout and localized interface copy as explicit product work. The code above uses a neutral layout and does not claim full right-to-left support. Treat localization as a testable requirement rather than a cosmetic afterthought.
What to build next
- Conversation state: evaluate the official conversation-state guidance before persisting or reusing context across visits.
- Streaming: use the official streaming documentation when users need incremental output rather than waiting for a complete response.
- Token management: use token-counting guidance before allowing long chat histories, large pasted documents, or high-volume usage.
- Authentication and storage: add these only with a clear ownership model for conversations and a documented retention policy.
- Abuse and cost controls: add server-side rate limiting, input rules, monitoring, and an operational process before public launch.
- Deployment: deploy to a hosting environment that can run your Next.js route handler and configure
OPENAI_API_KEYas a server-side secret in that environment.
You now have a clean baseline for a Next.js OpenAI chatbot: a browser interface, a protected server endpoint, the modern Responses API, and a configurable model. Keep the first version small, test it with representative GCC user prompts where relevant, and add advanced architecture only when you can validate the need.