
Next Js Ai Image Generator With Openai
Let's create next js ai image generator app using openai api.

You can also watch the YouTube video:
Next JS AI Image Generator with OpenAI
Creating The Project
npx create-next-app@latest
What is your project named? nextjs-ai-image-generator
Would you like to use TypeScript? No
Would you like to use ESLint? No
Would you like to use Tailwind CSS? Yes
Would you like your code inside a `src/` directory? No
Would you like to use App Router? (recommended) Yes
Would you like to use Turbopack for `next dev`? Yes
Would you like to customize the import alias (`@/*` by default)? No
Initializing ShadCN UI
npx shadcn@latest init
npx shadcn@latest init -d
Installing Required ShadCN Components
npx shadcn@latest add button card input skeleton
Installing Required Dependencies
yarn add typewriter-effect openai
Creating AiImageBot Component
Create AiImageBot.jsx
in components
folder:
"use client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import Image from "next/image";
import { useState } from "react";
import { Skeleton } from "./ui/skeleton";
import Typewriter from "typewriter-effect";
const AiImageBot = () => {
const [prompt, setPrompt] = useState("");
const [generatedImage, setGeneratedImage] = useState("");
const [loading, setLoading] = useState(false);
const generateImage = async () => {
try {
setLoading(true);
const response = await fetch("/api/ai-image", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
prompt,
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setGeneratedImage(data);
} catch (error) {
console.error("Error:", error);
} finally {
setLoading(false);
setPrompt("");
}
};
return (
<div className="max-w-3xl mx-auto p-16">
<div>
<div>
<h1 className="text-3xl font-bold">
<Typewriter
onInit={(typewriter) => {
typewriter
.typeString("Write something to generate an image!")
.start();
}}
/>
</h1>
</div>
<div className="mt-8 flex space-x-4 items-center justify-center">
<Input
type="text"
placeholder="Write some stuff..."
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
/>
<Button onClick={generateImage} disabled={loading}>
{loading ? "Loading" : "Send"}
</Button>
</div>
<div className="mt-8">
{loading ? <Skeleton className="w-[1024px] h-[1024px]" /> : null}
{generatedImage ? (
<Image
src={generatedImage}
height={1024}
width={1024}
alt="AI Generated Image"
/>
) : undefined}
</div>
</div>
</div>
);
};
export default AiImageBot;
Editing Home Page
Edit page.tsx
in app
folder:
import AiImageBot from "@/components/AiImageBot";
export default function Home() {
return <AiImageBot />;
}
Creating Ai Image Api Route
Create route.js
in app/api/ai-image
folder:
import { NextResponse } from "next/server";
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "YOUR_API_KEY",
});
export async function POST(request) {
const body = await request.json();
const { prompt } = body;
try {
const response = await openai.images.generate({
prompt,
n: 1,
size: "1024x1024",
});
const image = response.data[0].url;
return NextResponse.json(image, { status: 200 });
} catch (error) {
console.log("Error", error);
return NextResponse.json(
{ error: "An error occurred, please try again later!" },
{ status: 500 }
);
}
}
Now you able to generate images using our next js app.
Don't forget to add image domain to next.config.mjs
file:
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "oaidalleapiprodscus.blob.core.windows.net",
},
],
},
};
export default nextConfig;
0
0