Building AI-Powered Features in Next.js and React
Building AI-Powered Features in Next.js and React
Alright, let's talk about AI. I know everyone's going crazy over it, and honestly, there's a reason. I've been adding AI features to some of my projects and it's actually not that hard. Let me show you what I've done.
Why Bother With AI?
Here's where I've found AI actually useful:
- Chatbots - Basic customer support without hiring someone 24/7
- Smart search - Actually understanding what people are looking for
- Content help - Not writing for them, but helping them write faster
- Categorization - Auto-tagging stuff users upload
Getting Started with OpenAI
The easiest way to get started is OpenAI's API. Here's how I set it up:
Install the SDK
npm install openai
Set Up Your API Key
Create a .env.local file:
OPENAI_API_KEY=your_key_here
Create an API Route
In Next.js, you create a route handler:
// app/api/chat/route.ts
import { OpenAI } from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
export async function POST(request: Request) {
const { message } = await request.json();
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: message },
],
});
return Response.json({
reply: completion.choices[0].message.content,
});
}
Use It in a React Component
// components/ChatBot.tsx
'use client';
import { useState } from 'react';
export default function ChatBot() {
const [message, setMessage] = useState('');
const [response, setResponse] = useState('');
const [loading, setLoading] = useState(false);
const sendMessage = async () => {
setLoading(true);
const res = await fetch('/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ message }),
});
const data = await res.json();
setResponse(data.reply);
setLoading(false);
};
return (
<div>
<input
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Ask me anything..."
/>
<button onClick={sendMessage} disabled={loading}>
{loading ? 'Thinking...' : 'Send'}
</button>
{response && <p>{response}</p>}
</div>
);
}
Vercel AI SDK - Even Easier
Vercel made this way easier with their AI SDK:
npm install ai
import { useChat } from 'ai/react';
export default function Chat() {
const { messages, input, handleInputChange, handleSubmit } = useChat();
return (
<div>
{messages.map((m) => (
<div key={m.id}>
<strong>{m.role}:</strong> {m.content}
</div>
))}
<form onSubmit={handleSubmit}>
<input
value={input}
onChange={handleInputChange}
placeholder="Say something..."
/>
<button type="submit">Send</button>
</form>
</div>
);
}
That's seriously it. One import and you get a full chatbot.
Image Generation
You can also generate images:
const response = await openai.images.generate({
prompt: 'A modern website design for a restaurant',
n: 1,
size: '1024x1024',
});
const imageUrl = response.data[0].url;
Some Things I've Learned
Keep Your Keys Safe
Never, ever put your API key in client-side code. Always call OpenAI from your server. This is super important.
Errors Happen
AI APIs fail sometimes. Add good error handling - users shouldn't see weird error messages.
It Costs Money
AI isn't free (well, some is, but the good stuff isn't). Set budgets and monitor usage. I've gotten surprised by bills before.
Don't Be Creepy
Don't use AI to analyze user data without being upfront about it. Just don't.
Wrapping Up
Look, AI isn't magic. It's just another tool in your toolbox. Start small - maybe just a chatbot that answers basic questions. Then expand from there.
The hardest part is usually figuring out WHAT to automate, not HOW to build it.
Want to chat about AI in your project? Hit me up.