HarshPatel

Ahmedabad, Gujarat
Back to Blog
AINext.jsOpenAIvercel AI SDKChatbotTutorial

Build Your Own AI Chatbot with Next.js, Vercel AI SDK, and OpenAI in Under 1 Hour

Harsh PatelMay 4, 20262 min read11 views
Build Your Own AI Chatbot with Next.js, Vercel AI SDK, and OpenAI in Under 1 Hour

Introduction

Building an AI chatbot from scratch used to mean: wire up OpenAI's API, manage message history manually, implement streaming with Server-Sent Events, and build the UI on top. It took days.

The Vercel AI SDK abstracts all of this into a handful of hooks and utilities. Here's how to build a working, streaming chatbot in Next.js in under an hour.

Step 1: Create a Next.js app and install dependencies

npx create-next-app@latest my-chatbot --typescript --tailwind --app
cd my-chatbot
npm install ai @ai-sdk/openai

Add your OpenAI API key to .env.local:

OPENAI_API_KEY=sk-your-key-here

Step 2: Create the API route

Create app/api/chat/route.ts:

import { openai } from "@ai-sdk/openai";
import { streamText } from "ai";

export const maxDuration = 30;

export async function POST(req: Request) {
  const { messages } = await req.json();

  const result = await streamText({
    model: openai("gpt-4o"),
    system: "You are a helpful assistant.",
    messages,
  });

  return result.toDataStreamResponse();
}

That's the entire backend. The streamText function handles the OpenAI call and toDataStreamResponse() returns a streaming response the SDK's frontend hooks understand.

Step 3: Build the chat UI

Create app/page.tsx:

"use client";

import { useChat } from "ai/react";

export default function Chat() {
  const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat();

  return (
    
{messages.map((message) => (
{message.content}
))} {isLoading && (
Thinking...
)}
); }

Step 4: Run and deploy

npm run dev

Open localhost:3000 — your chatbot is live. Message history is maintained automatically by useChat. Responses stream in token by token.

To deploy to Vercel:

npx vercel --prod

Add OPENAI_API_KEY to your Vercel environment variables and you're done.

What to add next

  • Swap the model to gpt-4o-mini for cheaper responses
  • Add a system prompt to give your bot a personality
  • Persist chat history to a database with Prisma
  • Add authentication with Clerk so users have private chats

Conclusion

The Vercel AI SDK turns what used to be a multi-day project into a one-hour build. The useChat hook handles everything — message state, streaming, loading states — so you can focus on making your chatbot actually useful.

All Posts
AINext.jsOpenAIvercel AI SDKChatbotTutorial