This tutorial will guide you through building an AI-powered content ideas generator using Next.js and OpenAI’s GPT APIs. By the end of this tutorial, you’ll have a working application where users can input topics, and the AI generates creative and relevant content ideas.
Prerequisites
- Basic Knowledge of JavaScript, React, and APIs.
- Installed Tools: Node.js (LTS version), npm/yarn, and a code editor (like VSCode).
- OpenAI API Key: Create an account at OpenAI and get your API key.
Features of the AI Content Ideas Generator
- User-friendly interface to input a topic or niche.
- Generates a list of content ideas for blogs, social media, or videos.
- Responsive design for all devices.
Step 1: Set Up the Project
1.1 Create a Next.js App
Run the following command to create a new Next.js project:
npx create-next-app@latest ai-content-ideas-generator cd ai-content-ideas-generator
1.2 Install Required Packages
Install the OpenAI library for API integration and any additional packages:
npm install openai npm install axios # Optional: For making API requests
Step 2: Set Up OpenAI API in the Backend
2.1 Create API Route
In Next.js, API routes allow you to handle server-side logic. Create an API file at pages/api/generate-ideas.js
:
import { Configuration, OpenAIApi } from "openai"; const configuration = new Configuration({ apiKey: process.env.OPENAI_API_KEY, }); const openai = new OpenAIApi(configuration); export default async function handler(req, res) { if (req.method !== "POST") { return res.status(405).send({ message: "Only POST requests allowed" }); } const { topic } = req.body; if (!topic) { return res.status(400).send({ message: "Topic is required" }); } try { const completion = await openai.createCompletion({ model: "text-davinci-003", prompt: `Generate a list of 10 creative content ideas for the topic: "${topic}"`, max_tokens: 150, temperature: 0.7, }); res.status(200).json({ ideas: completion.data.choices[0].text.trim().split("\n") }); } catch (error) { console.error(error); res.status(500).send({ message: "Error generating ideas" }); } }
2.2 Add Environment Variables
Create a .env.local
file in the root directory:
OPENAI_API_KEY=your_openai_api_key
Restart your development server after adding this file to load the environment variables.
Step 3: Build the Frontend
3.1 Update pages/index.js
Replace the content of pages/index.js
with the following code:
import { useState } from "react"; export default function Home() { const [topic, setTopic] = useState(""); const [ideas, setIdeas] = useState([]); const [loading, setLoading] = useState(false); const fetchIdeas = async () => { if (!topic.trim()) { alert("Please enter a topic."); return; } setLoading(true); setIdeas([]); try { const response = await fetch("/api/generate-ideas", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ topic }), }); const data = await response.json(); if (response.ok) { setIdeas(data.ideas); } else { alert(data.message || "Something went wrong"); } } catch (error) { console.error(error); alert("Error fetching ideas."); } finally { setLoading(false); } }; return ( <div style={{ padding: "2rem", fontFamily: "Arial, sans-serif" }}> <h1>AI Content Ideas Generator</h1> <p>Enter a topic or niche to generate creative content ideas:</p> <div style={{ marginBottom: "1rem" }}> <input type="text" placeholder="Enter a topic..." value={topic} onChange={(e) => setTopic(e.target.value)} style={{ padding: "0.5rem", width: "300px" }} /> <button onClick={fetchIdeas} style={{ padding: "0.5rem 1rem", marginLeft: "1rem", backgroundColor: "#0070f3", color: "#fff", border: "none", borderRadius: "4px", cursor: "pointer", }} > {loading ? "Generating..." : "Generate"} </button> </div> {loading && <p>Loading ideas...</p>} <ul> {ideas.map((idea, index) => ( <li key={index} style={{ marginBottom: "0.5rem" }}> {idea} </li> ))} </ul> </div> ); }
Step 4: Test the Application
Start the development server:
npm run dev
Open your browser and navigate to http://localhost:3000.
Enter a topic (e.g., “Digital Marketing”) and click “Generate.” Wait for the ideas to appear below.
Step 5: Improve the UI (Optional)
To make the interface more visually appealing:
- Install Tailwind CSS: Follow the Tailwind CSS installation guide for Next.js.
- Add Styling: Update the UI using Tailwind classes for buttons, inputs, and layouts.
Step 6: Deploy the Application
- Push the Code to GitHub: Initialize a Git repository and push your code:
git init git add . git commit -m "Initial commit" git branch -M main git remote add origin your-git-repo-url git push -u origin main
- Deploy on Vercel:
- Go to Vercel.
- Import your GitHub repository.
- Add the
OPENAI_API_KEY
environment variable in the Vercel project settings.
- Your app will be live at
https://your-app-name.vercel.app
.