
A pragmatic, beginner-friendly course that walks you through one real project from start to finish.
Initialize a minimal Next.js App Router project with TypeScript, pinned dependencies, basic App Router files, and confirm the dev server runs at http://localhost:3000 (npm run dev).
Why this matters
You want a predictable project folder before adding routes, server code, or chat UI. That means: a package.json with reproducible versions and useful scripts; a conservative tsconfig.json so TypeScript warns you about mistakes early; minimal App Router files so Next can serve pages; and ignore rules plus an env template to keep secrets out of git. We'll create those files, install dependencies, and start the dev server so you have a working baseline to build the chatbot on.
In this lecture
- package.json with pinned dependency versions and npm scripts (dev, build, start, lint)
- devDependencies vs dependencies and Node engines field
- tsconfig.json minimal configuration for Next.js + TypeScript (strict, noEmit, jsx, moduleResolution)
- Next.js App Router minimal files: app/layout.tsx and app/page.tsx
- next-env.d.ts so TypeScript picks up Next's global types
- .gitignore and .env.example to avoid committing secrets
- Running npm install and npm run dev and confirming Local: http://localhost:3000
Install openai@7.27.0 and dotenv@18.0.5, add a .env.example placeholder, and add a minimal server route that checks process.env.OPENAI_API_KEY and returns a small example Responses API request shape. Verify the route returns a 400 when the key is missing.
Why this matters
Your OpenAI-compatible API key must never be exposed to the browser or committed to git. Next.js server code (App Router route handlers) can read process.env, but the values come from .env.local at startup. We'll add the openai npm client and dotenv for local scripts, add a .env.example that documents the variable, and create a tiny server route at /api/check-key that checks process.env.OPENAI_API_KEY and returns an example Responses API request shape. We'll run the dev server and confirm the route returns a 400 when the key is not set.
What you'll see built
- .env.example with a placeholder
- package.json updated to include openai@7.27.0 and dotenv@18.0.5
- app/api/check-key/route.ts server route that checks the environment and returns an example request shape
- Terminal commands to install packages and run the dev server
Notes
- Next.js reads .env.local at startup; restart the dev server after adding or changing .env.local.
- Do not create .env.local in the repo and do not commit it. Copy .env.example to .env.local and put your real key there.
## In this lecture
- npm install and updating package.json
- .env.example and .env.local usage
- process.env in Next.js (server only)
- Keeping API keys on the server (never in client code)
- Minimal Responses API request shape (example only)
- Restarting Next.js dev server after env changes
Explain why Next's App Router needs a root layout and an index page, then create the minimal files /app/layout.tsx and /app/page.tsx so the project serves a page at http://localhost:3000.
Next's App Router relies on a root layout and route components inside the app/ folder. The root layout (app/layout.tsx) establishes the HTML shell and is required for any route rendering under app/. The index route is app/page.tsx and provides the content you see at '/'. We'll create the minimal layout and page so Next serves a page at http://localhost:3000. I'll show the smallest working content for each file, explain the lines you need (metadata, children, where to import global CSS), run npm run dev, and verify the Local URL. If these files are in the wrong place or named incorrectly, Next will return a 404 — that's the most common mistake.
## In this lecture
- Next.js App Router
- /app/layout.tsx as the root layout
- /app/page.tsx as the index route component
- Where global CSS and metadata belong
- File-system routing and common 404 mistakes
- Starting the dev server and verifying Local URL
Create a client-side ChatWindow component at app/components/ChatWindow.tsx that manages local message state, renders a MessageList, and provides a controlled input with a Send button. Add the component to app/page.tsx so you can run and test sending messages locally.
Why this matters
- The chat UI is the user's surface for the bot. Before we connect the API, we need a predictable client-side component that holds messages, accepts input, and renders them. That makes later steps (posting to /api/chat, streaming, saving history) a small, local change.
What you'll build
- app/components/ChatWindow.tsx as a *client* component ("use client"), with a Message type, messages state, controlled input, a Send button, and Enter-to-send. We'll also show how to add ChatWindow to app/page.tsx so the UI appears at the index route.
How this fits the project
- This lesson focuses on the smallest working UI. Later lessons replace the local append with a server POST and streaming. For now messages are only in memory so you can test UI behavior quickly.
## In this lecture
- Client component: "use client" directive
- React state with useState
- Controlled input pattern
- Mapping an array to JSX for message rendering
- Keyboard submission via onKeyDown
- Basic accessibility: aria-label, button type
- Where to place UI components in the Next.js App Router
Explain server vs client components in the Next.js App Router, show how to construct initialMessages in the server page (/app/page.tsx) and pass them into a client ChatWindow component, demonstrate a common hydration pitfall (non-serializable Date objects), and fix it. Give clear rules to avoid similar problems.
Why this matters: Next.js' App Router defaults to Server Components. You should construct initial data (initialMessages) on the server and pass it into client UI. But props crossing the server → client boundary must be serializable and stable; otherwise you get hydration mismatches or runtime errors. In this lesson you'll build initialMessages in the server page, pass them to the client ChatWindow, see a realistic mistake (passing a Date), and fix it by sending a string (ISO). Also practical rules: keep API keys and network calls on the server, keep UI state on the client, and never import server-only packages into files with "use client".
## In this lecture
- Server Components vs Client Components (App Router)
- Passing props from a server page to a client component
- Hydration mismatch causes and diagnostics
- Serializable props (Date pitfalls) and fixes
- Where to run server-only code and keep secrets
Add a Next.js App Router route handler at /app/api/chat/route.ts that uses the openai npm client (openai@7.27.0) to call the Responses API. Read process.env.OPENAI_API_KEY using lib/getEnv, accept a user message in the request body, call the model, and return a JSON response to the client with the model output. Handle basic errors and avoid leaking secrets.
Problem: the client UI needs a secure server endpoint to forward user messages to the AI. We must read the OPENAI_API_KEY on the server, call the Responses API, and return the model text. We'll create /app/api/chat/route.ts. Keep the API key server-only (use getEnv), validate the incoming JSON, call client.responses.create, and return a clean JSON response. Avoid logging secrets or reading the key at module import time.
## In this lecture
- Next.js App Router route handlers (app/api/*/route.ts)
- openai npm client (openai@7.27.0) and Responses API
- Reading server-only env vars with getEnv (lib/env.ts)
- async/await in route handlers and returning JSON with NextResponse
- Basic request validation and error handling
Implement the client-side POST from app/components/ChatWindow.tsx to /api/chat, show loading and error states, and append the model reply to the chat UI without importing server-only modules or API keys.
Problem: ChatWindow shows messages and accepts input, but it doesn't call the server. We need to send the user's message to /api/chat, show that the bot is working, and then show the reply or a friendly error.
What I changed (high level):
- Added loading and error UI state using useState in app/components/ChatWindow.tsx.
- Made sendMessage async and optimistic: append the user's message immediately, then append a temporary bot message with text "Thinking..." so the UI feels responsive.
- Performed a same-origin POST to /api/chat with headers { "Content-Type": "application/json" } and body JSON.stringify({ message }).
- Parsed res.json(), and handled three failure modes: network error (catch), HTTP failure (!res.ok), and business failure where server returns { ok: false } with an error message.
- Replaced the temporary loading message in messages state with the returned bot text on success, or a short failure text on error. Also set an inline error message below the message list.
Why this matters: keeping API keys on the server is critical. The client only POSTs to a same-origin route. The UI flow (optimistic append → loading placeholder → replace with real reply) is simple, avoids duplicate sends, and gives good feedback to the user.
# In this lecture
- Client component state: useState for messages, input, loading, and error
- Optimistic UI: append user message immediately, show a temporary bot "Thinking..." message
- Same-origin fetch to Next.js App Router route (/api/chat) with Content-Type: application/json
- Parse response.json() and handle HTTP errors and business-level { ok: false } from the server
- Never import server-only modules (openai) or read env vars in client code
- Update React state to replace temporary messages with the bot reply
- Disable input and send button while request is in flight
Harden the server route at app/api/chat/route.ts with input validation and structured error responses, then update app/components/ChatWindow.tsx to handle 4xx/5xx/network errors and offer a simple manual Retry UX. Share types between server and client so both sides agree on the shapes.
Why this matters: right now the route can return raw errors and the client only shows a generic "Failed to get reply". That makes it impossible for users to understand whether they mistyped something, whether the server is misconfigured, or whether they're rate-limited. We'll: 1) add a small shared types file (lib/types.ts) so the server and client agree on ChatRequest and ChatResponse shapes, 2) update app/api/chat/route.ts to validate JSON and the message (presence, type, length), map provider errors into canonical ErrorCode values and return a structured ServerError object with appropriate HTTP status codes, and 3) update the client (app/components/ChatWindow.tsx) to read the structured response, show clear inline messages for invalid input vs rate limits vs server errors, and provide a manual Retry button for retryable issues. The result: the UI gives helpful guidance and a predictable payload shape for future features.
# In this lecture
- Server-side input validation (required fields, types, length)
- Structured error JSON with ErrorCode and ServerError shapes
- Appropriate HTTP status codes: 400 (invalid input), 401 (bad API key), 429 (rate limit), 502 (upstream error), 500 (server error)
- Client-side mapping of server errors to friendly messages
- Manual retry UX for retryable failures (rate limits and server errors)
- Sharing TypeScript types between server and client for safety
Add shared Message TypeScript types and persist chat history in the client using localStorage. Load stored history on mount, save on changes, show timestamps, and add a Clear History button. Avoid SSR/localStorage pitfalls and handle malformed stored data gracefully.
Why this matters: Chat history makes the app feel like a real chat. Persisting to localStorage keeps things simple for a single-user app and lets you swap to a server DB later. We'll add a shared Message type in lib/types.ts so both server and client agree on the shape. Then, in app/components/ChatWindow.tsx (a client component), we'll load saved messages on mount, save whenever messages change, show human-friendly timestamps, and provide a Clear History button. We'll be defensive: check for malformed JSON and guard localStorage access even though this code runs on the client.
# In this lecture
- Shared TypeScript types for client and server (lib/types.ts)
- localStorage read/write with JSON.stringify / JSON.parse
- React lifecycle: useEffect for load-on-mount and save-on-change
- Client component guard for localStorage (component already marked 'use client')
- Timestamps as ISO strings and rendering with toLocaleString
- Defensive parsing and fallbacks for corrupted stored data
- Clear History UX and disabling the button when empty
Turn the buffered bot reply into a streamed reply so the UI shows the model's text as it arrives. Add AbortController cancel support, a non-stream fallback, and robust error handling.
Why this matters: streaming gives users immediate feedback — text appears progressively instead of waiting for the whole answer. That improves perceived latency and feels more polished. We'll make the server proxy the AI provider's event stream and the client will read and append chunks to the latest bot message. If streaming isn't available (or on older hosts), we'll fall back to buffered JSON. We'll also add an AbortController so the user can cancel the response to avoid wasted compute and to keep the UI responsive.
# In this lecture
- Server streaming proxy (SSE) from a secure server route
- Client-side ReadableStream consumption with response.body.getReader()
- TextDecoder for incremental decoding
- SSE framing: data: lines and [DONE] sentinel
- AbortController to cancel an in-flight stream
- Fallback to buffered JSON when streaming isn't available
Prepare the chatbot for production and deploy it to Vercel: pin Node, document deployment steps, add optional vercel.json, commit, build locally, and verify how to set OPENAI_API_KEY on the host and test the deployed app.
We need to get the app ready to deploy so the model requests stay on the server and your API key never ends up in client code or git history. That means documenting deployment steps in README.md, telling teammates where to put OPENAI_API_KEY in Vercel Project Settings, pinning Node so builds are stable, adding a minimal vercel.json so Vercel treats this as a Next project, running a local production build to catch type/build errors early, and committing the repo to trigger Vercel’s import flow. Also, TypeScript 7 removed compiler option baseUrl; replace it with a simple paths mapping so module resolution keeps working during build.
# In this lecture
- Keep API calls server-side and secrets out of the client
- Pin Node engine for deterministic builds
- Never commit .env.local; set secrets in Vercel Project Settings
- How to connect a Git repo to Vercel and trigger a deploy
- How to test the deployed app and read server logs
Add minimal production hygiene: a small IP-based rate limiter as middleware, and explain secrets handling, cost monitoring, and next steps.
Why this matters: a demo that calls a paid AI provider can accidentally leak secrets or rack up bills if you allow runaway requests or return raw provider internals to clients. We add a tiny, best-effort middleware limiter that blocks obvious rapid repeats during demos. This is not a production-grade solution — it prevents quick abuse in demos and keeps server logs clean. For production, move counters to Redis, cap provider usage in the provider dashboard, and export minimal metrics (request count, 5xx rate, token usage).
# In this lecture
- In-process middleware rate limiting (IP-based)
- Never logging secrets or request bodies
- Why in-memory limits are a demo-only stopgap
- Provider quotas and basic monitoring to control cost
This course contains the use of artificial intelligence.
This course is a pragmatic, beginner-friendly walkthrough that teaches you to build, run, and deploy a TypeScript Next.js chatbot backed by an OpenAI-compatible API using the App Router. It focuses on a small but real chat application implemented with Next.js (App Router) and TypeScript, connected to an OpenAI-compatible API via the openai npm client.
You will build a chat UI that includes a message list and input box, a secure server API route that forwards messages to the AI API, handling of API errors, and simple local chat history persisted to the browser. An optional lesson covers streaming responses so the UI can show incremental text while the model is generating.
By the end you will be able to start a Next.js + TypeScript project configured with the official packages used in production, implement a client-side chat component and a server API route at /app/api/chat or /api/chat that calls an OpenAI-compatible API, and type the code with TypeScript to get safer API usage and clearer errors. The course shows how to persist conversations to localStorage and explains how to adapt the server to persist to a database. It also covers deploying the finished app to Vercel or a similar host while keeping your API key secret.
Technical lessons include project setup and TypeScript basics (Create a Next.js + TypeScript app, install openai@7.27.0 and dotenv, add .env.local with OPENAI_API_KEY, check tsconfig.json, and run npm run dev), App Router anatomy and a minimal chat UI (add /app/layout.tsx and /app/page.tsx, create app/components/ChatWindow.tsx with "use client"), and a secure server route at /app/api/chat/route.ts that uses the openai client to call the Responses API. The course emphasizes server-vs-client boundaries (do not import openai in client code) and basic production notes such as avoiding logging secrets, pinning a Node version, and adding basic rate limits and cost monitoring.
This course is aimed at beginner web developers who know basic HTML/CSS and some JavaScript, are comfortable creating and editing files, and can follow terminal commands (npm, git). The final project is a deployed Next.js TypeScript chatbot that accepts user messages, forwards them to an OpenAI-compatible API from a secure server route, renders AI responses in a chat UI, supports local chat history, and includes TypeScript types and basic production readiness guidance, with optional streaming output.