Project Setup Beginner

In this lesson, you will create a React project, install the AI SDK, set up a backend API endpoint, and build your first AI-powered component.

Step 1: Create a React Project

Bash
# Using Vite (recommended)
npm create vite@latest my-ai-react-app -- --template react-ts
cd my-ai-react-app
npm install

Step 2: Install Dependencies

Bash
# AI SDK with React hooks
npm install ai @ai-sdk/react

# Markdown rendering for AI responses
npm install react-markdown remark-gfm

# Code syntax highlighting (optional)
npm install react-syntax-highlighter

Step 3: Set Up the Backend

You need a backend API that proxies requests to the AI provider. Here is a simple Express server:

TypeScript - server/index.ts
import express from 'express';
import cors from 'cors';
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';

const app = express();
app.use(cors());
app.use(express.json());

app.post('/api/chat', async (req, res) => {
  const { messages } = req.body;

  const result = await streamText({
    model: openai('gpt-4o'),
    messages,
  });

  result.pipeDataStreamToResponse(res);
});

app.listen(3001, () => console.log('API running on port 3001'));
Important: Never call AI APIs directly from the browser. Always proxy through a backend to keep your API keys secure. The backend should handle authentication, rate limiting, and input validation.

Step 4: Your First AI Component

TypeScript - src/App.tsx
import { useChat } from '@ai-sdk/react';

function App() {
  const { messages, input, handleInputChange, handleSubmit } = useChat({
    api: 'http://localhost:3001/api/chat',
  });

  return (
    <div>
      <h1>AI Chat</h1>
      {messages.map(m => (
        <div key={m.id}>
          <strong>{m.role}:</strong> {m.content}
        </div>
      ))}
      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} />
        <button type="submit">Send</button>
      </form>
    </div>
  );
}

export default App;

Setup Complete!

Your React app is connected to an AI backend. In the next lesson, you will build polished, reusable chat components.

Next: Chat Components →

Ready to Go Deeper?

Live instructor-led courses from our partners. Affiliate disclosure.