Skip to content
01Home 02Capability Matrix 03Tools 04Benchmark Rankings 05Tracks 06About Us
Code Under Repair · AI coverage organised as a matrix of capability × stage. Not sorted by tool, but by where you are right now.
Updated every Wednesday

Build a Full-Stack AI App With TypeScript and an LLM API

Build a full-stack AI app with TypeScript, Next.js, React, and an LLM API. Create a working chat interface, protect your API key, connect a backend route, and prepare the app for production.

Nov 10, 2026
Build a Full-Stack AI App With TypeScript and an LLM API LLM Apps & Agent Engineering

A successful AI prototype can fit inside a single script. A useful AI product needs more: a frontend where users can interact with it, a backend that protects credentials, and a reliable connection to the model API.

In this tutorial, we'll build a small full-stack AI chat application with TypeScript, Next.js, React, and the OpenAI Responses API. The frontend will collect a user's message and display the response. A server-side route will validate the request, call the model, and return the result.

The architecture is intentionally simple. We'll avoid adding a database, authentication system, or streaming infrastructure before the basic application works. The goal is to understand how the frontend, backend, and LLM fit together—and where each responsibility belongs.


Table of Contents

  • Understand the Application Architecture

  • Create the Next.js Project

  • Configure the LLM API on the Server

  • Create the Backend API Route

  • Build the Interactive Chat Interface

  • Test the Application

  • Prepare the App for Production


Understand the Application Architecture

Before writing code, decide which parts of the application belong on the client and which belong on the server.

Our app has three main components:

  • Frontend: Displays the chat interface, accepts user input, and shows responses.

  • Backend: Validates incoming requests and communicates with the LLM API.

  • LLM provider: Processes the prompt and generates the response.

Full-stack AI app architecture

The request flow is straightforward:

  1. The user enters a message in the browser.

  2. The frontend sends the message to a Next.js API route.

  3. The backend calls the model using a server-side API key.

  4. The backend returns the generated text as JSON.

  5. The frontend adds the response to the conversation.

One design decision is especially important: the browser should never call the model provider with your private API key. Keep the key on the server and let the backend handle provider requests.


Create the Next.js Project

We'll use the Next.js App Router because it provides a convenient way to organize pages and backend route handlers in one TypeScript project.

Create the project:

npx create-next-app@latest ai-chat-app
cd ai-chat-app

Choose TypeScript and App Router when prompted. Then install the OpenAI SDK:

npm install openai

Our project will use this structure:

ai-chat-app/
├── app/
│   ├── api/
│   │   └── chat/
│   │       └── route.ts
│   ├── page.tsx
│   └── globals.css
├── .env.local
└── package.json

The page handles the user interface, while app/api/chat/route.ts handles requests from the browser.


Configure the LLM API on the Server

Create a .env.local file in the project root:

OPENAI_API_KEY=your_api_key_here
OPENAI_MODEL=your_supported_model

Use a model available to your API account that supports the Responses API. Keeping the model name in an environment variable makes it easier to change models without editing application code.

Do not prefix the secret with NEXT_PUBLIC_. In Next.js, variables with that prefix are exposed to the browser bundle. Your API key must remain server-side.

We'll initialize the SDK inside the backend route, so the frontend never needs direct access to the provider credentials.


Create the Backend API Route

Create app/api/chat/route.ts. A Next.js Route Handler lets you define a custom HTTP endpoint using a standard request and response interface.

import OpenAI from "openai";

const apiKey = process.env.OPENAI_API_KEY;
const model = process.env.OPENAI_MODEL;

if (!apiKey || !model) {
  throw new Error("Missing OpenAI environment configuration");
}

const client = new OpenAI({
  apiKey,
});

export async function POST(request: Request) {
  try {
    const body = await request.json();
    const message = body?.message;

    if (
      typeof message !== "string" ||
      message.trim().length === 0 ||
      message.length > 4000
    ) {
      return Response.json(
        { error: "Enter a valid message." },
        { status: 400 }
      );
    }

    const response = await client.responses.create({
      model,
      instructions:
        "You are a helpful assistant. Give clear, practical answers.",
      input: message.trim(),
    });

    if (response.status !== "completed") {
      return Response.json(
        { error: "The model did not complete the response." },
        { status: 502 }
      );
    }

    return Response.json({
      answer: response.output_text,
    });
  } catch (error) {
    console.error("Chat request failed:", error);

    return Response.json(
      { error: "Unable to generate a response right now." },
      { status: 500 }
    );
  }
}
Next.js OpenAI API route

This route does four jobs:

  1. Reads the message sent by the frontend.

  2. Checks that the input is a non-empty string within the allowed length.

  3. Sends the request to the model through the server-side SDK.

  4. Returns the generated text or a controlled error response.

Notice that the API key is never returned to the browser. Also, the application does not expose raw provider errors to the user. Detailed errors can be recorded in server logs while the frontend receives a safer message.


Build the Interactive Chat Interface

Now create app/page.tsx. This component needs browser-side state and event handlers, so it should be a Client Component.

"use client";
import { FormEvent, useState } from "react";
type Message = { role: "user" | "assistant"; content: string; };
export default function Home() {
  const [messages, setMessages] = useState<Message[]>([]);
  const [input, setInput] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");
  async function handleSubmit(event: FormEvent) {
    event.preventDefault();
    const text = input.trim();
    if (!text || loading) return;
    setMessages((current) => [...current, { role: "user", content: text }]);
    setInput("");
    setError("");
    setLoading(true);
    try {
      const response = await fetch("/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ message: text }),
      });
      const data = await response.json();
      if (!response.ok) throw new Error(data.error || "Request failed");
      setMessages((current) => [...current, { role: "assistant", content: data.answer }]);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Something went wrong.");
    } finally {
      setLoading(false);
    }
  }
  return (
    <main className="max-w-2xl mx-auto p-6">
      <h1 className="text-2xl font-bold mb-2">AI Chat Assistant</h1>
      <p className="text-gray-500 mb-6">Ask a question and get an AI-generated response.</p>
      <div className="space-y-4 mb-6">
        {messages.map((message, index) => (
          <div key={index} className={`p-3 rounded-lg ${message.role === "user" ? "bg-blue-100" : "bg-gray-100"}`}>
            <div className="font-semibold text-sm text-gray-700">{message.role === "user" ? "You" : "Assistant"}</div>
            <div className="mt-1 whitespace-pre-wrap">{message.content}</div>
          </div>
        ))}
        {loading && <div className="text-gray-400 italic">Assistant is thinking...</div>}
        {error && <div className="text-red-500">{error}</div>}
      </div>
      <form onSubmit={handleSubmit} className="flex gap-2">
        <input value={input} onChange={(event) => setInput(event.target.value)} placeholder="Ask something..." maxLength={4000} disabled={loading} className="flex-1 border rounded px-3 py-2" />
        <button type="submit" disabled={loading} className="bg-blue-600 text-white px-4 py-2 rounded disabled:opacity-60">
          {loading ? "Sending..." : "Send"}
        </button>
      </form>
    </main>
  );
}
TypeScript AI chat interface

The frontend stores the conversation in React state and sends only the latest message to the backend. This is enough for a basic request-response demonstration, but it is not yet a true multi-turn AI conversation: previous messages are not being sent to the model.

That distinction matters. If you want the assistant to remember earlier messages, you need to preserve conversation history or use a supported conversation-state approach. We'll return to that in the production section.


Test the Application

Start the development server:

npm run dev

Open http://localhost:3000 in your browser. Enter a question and click Send.

If everything is configured correctly, the browser should send a request to /api/chat, the backend should contact the model, and the generated response should appear in the conversation.

If the request fails, check the problem in layers:

  • Frontend: Open the browser's Network panel and confirm that the request reaches /api/chat.

  • Backend: Check the terminal for server-side errors.

  • Configuration: Confirm that the API key and model name are available to the server.

  • Provider: Check account access, model availability, rate limits, and API usage.

Testing each layer separately is usually faster than changing several files at once.


Prepare the App for Production

The tutorial gives you a working foundation, but a production AI application needs more than a successful API call.

Preserve conversation history

Our current backend sends only one message to the model. To support follow-up questions, store the conversation history and pass the relevant messages into subsequent requests, or use a supported conversation-state mechanism. Apply a retention policy so conversations do not grow without limits.

Add rate limiting

A public endpoint can be abused to generate unexpected API costs. Add per-user or per-IP rate limits, request quotas, and appropriate authentication before making the app publicly available.

Improve the user experience

For longer responses, streaming can make the interface feel faster because users see text as it arrives. You should also add message timestamps, retry behavior, clear loading states, and accessible error messages.

Measure and monitor failures

Track request latency, token usage, error rates, and model responses. Avoid logging sensitive user content unless you have a clear reason and an appropriate data policy.

Keep the client and server responsibilities separate

Keep provider keys, database credentials, and privileged operations on the server. The frontend should handle presentation and user interaction, not secret management.


Where to Take the Project Next

You now have the core structure of a full-stack AI app: a TypeScript frontend, a server-side API route, and an LLM integration. From here, you can add persistent chat history, authentication, streaming, file uploads, or function calling.

Build one capability at a time. Verify the request flow before adding a database or introducing more infrastructure. A small application with clear boundaries is easier to debug, secure, and extend than a large prototype where every component depends on everything else.

Build it. Break it. Understand it. Fix it.

Reader responses

No responses on this piece yet.

Write what you observed