Back to blog

Sunday, December 29, 2024

Integrating AI-Powered Product Descriptions in Next.js: A Step-by-Step Guide

cover

How to Integrate AI-Powered Product Descriptions in a Next.js Project

Are you looking to add AI-generated product descriptions to your Next.js e-commerce site? This guide will walk you through the process step-by-step, using the latest Vercel AI SDK. By the end, you'll have a form that can generate product descriptions based on titles with just a click!

Prerequisites

Before we begin, make sure you have:

  1. Node.js installed (version 14 or later)
  2. A basic understanding of React and Next.js
  3. An OpenAI API key

Step 1: Set Up Your Next.js Project

If you don't already have a Next.js project, create one:

npx create-next-app@latest my-ai-product-app
cd my-ai-product-app

Step 2: Install Dependencies

Install the necessary packages:

npm install ai @ai-sdk/openai @vercel/ai

Step 3: Set Up Environment Variables

Create a .env.local file in your project root and add your OpenAI API key:

OPENAI_API_KEY=your_api_key_here

Step 4: Create the API Route

Create a new file at app/api/generate-description/route.ts with the following content:

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

export const runtime = "edge";

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

  const { text } = await generateText({
    model: openai("gpt-4-turbo"),
    prompt: `Generate a compelling product description for: \${prompt}`,
    temperature: 0.7,
    max_tokens: 200,
  });

  return new Response(text);
}

This creates an API route that uses OpenAI to generate product descriptions.

Step 5: Create the Product Form Component

Create a new file at app/components/ProductForm.tsx:

"use client";

import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";

export default function ProductForm() {
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [isLoading, setIsLoading] = useState(false);

  const handleGenerateDescription = async () => {
    if (title) {
      setIsLoading(true);
      try {
        const response = await fetch("/api/generate-description", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ prompt: title }),
        });
        if (!response.ok) {
          throw new Error("Failed to generate description");
        }
        const generatedDescription = await response.text();
        setDescription(generatedDescription);
      } catch (error) {
        console.error("Error generating description:", error);
      } finally {
        setIsLoading(false);
      }
    }
  };

  return (
    <Card className="w-full max-w-lg">
      <CardHeader>
        <CardTitle>Add New Product</CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <div className="space-y-2">
          <label htmlFor="title" className="text-sm font-medium">
            Product Title
          </label>
          <Input
            id="title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
            placeholder="Enter product title"
          />
        </div>
        <div className="space-y-2">
          <label htmlFor="description" className="text-sm font-medium">
            Product Description
          </label>
          <Textarea
            id="description"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Product description will appear here"
            rows={5}
          />
        </div>
      </CardContent>
      <CardFooter>
        <Button
          onClick={handleGenerateDescription}
          disabled={!title || isLoading}
        >
          {isLoading ? "Generating..." : "Generate Description"}
        </Button>
      </CardFooter>
    </Card>
  );
}

This component creates a form with inputs for the product title and description, and a button to generate the description.

Step 6: Update the Main Page

Update your app/page.tsx file to include the ProductForm component:

import ProductForm from "./components/ProductForm";

export default function Home() {
  return (
    <main className="flex min-h-screen flex-col items-center justify-center p-24">
      <h1 className="text-4xl font-bold mb-8">
        AI-Powered Product Description Generator
      </h1>
      <ProductForm />
    </main>
  );
}

Step 7: Run Your Application

Start your Next.js development server:

npm run dev

Visit http://localhost:3000 in your browser, and you should see your AI-powered product description generator!

How It Works

  1. When you enter a product title and click "Generate Description", the handleGenerateDescription function in ProductForm.tsx is triggered.
  2. This function sends a POST request to your /api/generate-description endpoint.
  3. The API route uses the Vercel AI SDK to generate a product description based on the title.
  4. The generated description is then displayed in the textarea on your form.

Conclusion

Congratulations! You've successfully integrated AI-powered product description generation into your Next.js application. This is just the beginning - you can expand on this to include more features, improve the prompt for better descriptions, or even use AI for other aspects of your e-commerce site.

Remember to handle errors gracefully and consider implementing rate limiting to manage API usage. Happy coding!

Additional Resources

To deepen your understanding of the Vercel AI SDK and its capabilities, check out these official documentation links:

  1. Vercel AI SDK Documentation
  2. AI SDK Core: Generating Text
  3. AI SDK UI: Building Chat Interfaces
  4. OpenAI Integration Guide
  5. Next.js AI Chatbot Template
  6. Vercel AI Playground

These resources will provide you with more detailed information about the SDK's features, best practices, and advanced usage scenarios.