DEV Community

Sangmin Lee
Sangmin Lee

Posted on • Originally published at claudeguide.io

Build an AI Chatbot with Next.js and Claude: Step-by-Step Guide

Originally published at claudeguide.io/build-ai-chatbot-nextjs-claude

Build an AI Chatbot with Next.js and Claude: Step-by-Step Guide

You can build a working AI chatbot with Next.js and Claude in under 2 hours. The core stack: Next.js App Router API route for the backend, the Anthropic SDK for streaming responses, and a React component for the chat UI. This guide covers each piece with complete code — no boilerplate repos to clone, just the exact code that works.


What you'll build

A streaming chatbot with:

  • Message history (context carries across turns)
  • Streaming responses (text appears as it generates)
  • System prompt configuration
  • Clean UI with loading states
  • Error handling

Prerequisites

  • Node.js 20+, bun or npm
  • An Anthropic API key (get one at console.anthropic.com)
  • Basic Next.js knowledge

Step 1: Create the Next.js project

bunx create-next-app@latest claude-chatbot --typescript --tailwind --app --no-src-dir
cd claude-chatbot
bun add @anthropic-ai/sdk
Enter fullscreen mode Exit fullscreen mode

Step 2: Set up the API key

Create .env.local:

ANTHROPIC_API_KEY=sk-ant-your-key-here
Enter fullscreen mode Exit fullscreen mode

Add to .gitignore (already there if you used create-next-app, but verify):

.env.local
Enter fullscreen mode Exit fullscreen mode

Step 3: Create the API route

Create app/api/chat/route.ts:


typescript
import Anthropic from "@anthropic-ai/sdk";
import { NextRequest } from "next/server";

const client = new Anthropic();

export const runtime = "nodejs"; // Not edge — Anthropic SDK requires Node.js

export async function POST(request: NextRequest) {
  try {
    const { messages, system } = await request.json();

    // Validate input
    if (!Array.isArray(messages) || messages.length === 0) {
      return new Response("Invalid messages", { status: 400 });
    }

    // Create streaming response
    const stream = await client.messages.stream({
      model: "claude-sonnet-4-5",
      max_tokens: 2048,
      system: system || "You are a helpful assistant.",
      messages: messages.map((m: { role: string; content: string }) =

[→ Get the Agent SDK Cookbook — $49](https://shoutfirst.gumroad.com/l/ogxhmy?utm_source=claudeguide&utm_medium=article&utm_campaign=build-ai-chatbot-nextjs-claude)

*30-day money-back guarantee. Instant download.*
Enter fullscreen mode Exit fullscreen mode

Top comments (0)