Let's Create an AI Image Generator with OpenAI and Next.js 14
Written on
Chapter 1: Introduction to AI Image Generation
Have you ever dreamed of creating your own AI image generator? It's more straightforward than you might expect! In this guide, I will walk you through the process using OpenAI and Next.js. Imagine having an AI that can visualize exactly what you envision—a charming portrait of your puppy skateboarding in an astronaut suit, for example. By the end of this tutorial, you'll be equipped to code your own AI-powered image generator, which I've named CHARL·E.
REQUIREMENTS:
- Basic familiarity with programming, particularly JavaScript and React, along with some experience using APIs.
- Access to OpenAI's SDK (you'll need to generate your own API Key).
- Next.js Server Actions (available from version 13.4) will be utilized.
- A simple user interface created using v0 for efficiency.
- A text editor of your choice, such as VS Code or Sublime Text.
Let’s briefly overview the tools we'll be using. Next.js provides a powerful framework for web development (ensure you have at least version 13.4). OpenAI is a leading company in artificial intelligence research and development, while v0 allows users, including those without coding expertise, to create user interfaces using simple text descriptions.
Chapter 2: Project Setup
Step 1: Create Your Project
To kick things off, let's create a new Next.js 14 project. Run the following command:
Follow the prompts to finalize the setup, which should resemble the following:
Next, navigate to the created directory and open the project in your preferred IDE. For this tutorial, I will be using Visual Studio Code:
cd image-generator
code .
Step 2: Install Necessary Dependencies
Inside your VS Code terminal, install the required libraries:
npm install openai
npx v0@latest init
Step 3: Obtain Your API Key
Visit the OpenAI website, create an account, and set up a project to receive your API key. Assign this key to an environment variable, like so:
OPENAI_API_KEY=sk_YOUR_API_KEY
Chapter 3: Coding Time!
Now that everything is set up, let's ensure everything is functioning properly. Run the command:
npm run dev
If everything is set up correctly, you should see the following output indicating your server is running. Head over to 'http://localhost:3000' to view the default Next.js landing page.
I know you’re eager to dive into the AI aspects—let’s get into it!
Section 3.1: Building the Front-End
Creating the UI with v0
v0 is an excellent UI library that simplifies the process of building interfaces. We will use it to design a straightforward form for text prompts and to display generated images. Visit v0.dev to create an account.
After entering a prompt, such as "an AI image generator," it will generate a mockup along with the corresponding code.
To add this component to your project, run:
npx v0 add O2JUYV2H
When prompted, name your component 'Generator'. Your UI setup is now complete!
Section 3.2: Setting Up the Backend
Next.js 13.4 introduced server actions, allowing you to execute server-side code directly from frontend components. This makes it simpler to manage actions requiring secure access to APIs or sensitive environment variables.
To interact with OpenAI's API, create a server actions file named app/actions.ts with the following content:
'use server'
import OpenAI from 'openai';
const apiKey = process.env.OPENAI_API_KEY;
const openaiModel = new OpenAI({
apiKey
});
export const generateImage = async (formData: FormData) => {
const prompt = formData.get('prompt') as string;
if (!prompt) {
return { error: 'Prompt is required' };}
const res = await openaiModel.images.generate({
prompt: prompt,
n: 1,
size: '512x512',
});
return JSON.parse(JSON.stringify(res));
};
What This Means:
- The directive 'use server' indicates that the code should run on the server.
- import OpenAI from 'openai' allows access to the OpenAI API.
- const apiKey = process.env.OPENAI_API_KEY securely retrieves your API key.
- You create an instance of the OpenAI client with your API key for authentication.
- The generateImage function takes FormData, checks for a prompt, and if valid, sends it to the OpenAI API to generate an image.
Section 3.3: Connecting Frontend and Backend
Here’s how to connect your frontend and backend:
'use client'
import { Input } from "@/components/ui/input"
import { Button } from "@/components/ui/button"
import { generateImage } from "@/app/actions";
import { useState } from "react";
import Image from "next/image";
export function Generator() {
const [url, setUrl] = useState('');
const action = async (formData: FormData) => {
const imageData = await generateImage(formData);
setUrl(imageData.data[0].url);
};
return (
<div>
<h1>AI Image Generator</h1>
<p>Enter a text prompt and let our AI generate an image for you.</p>
<form onSubmit={action}>
<Input name="prompt" placeholder="Enter your prompt..." />
<Button type="submit">Generate</Button>
</form>
<Image src={url || "/placeholder.svg"} alt="Generated AI Image" />
</div>
);
}
In this code:
- A state variable url is created to store the generated image's URL.
- The action function triggers the generateImage server action, extracts the image URL from the response, and updates the url state.
- The form handles user input and submission.
And just like that, you’re ready to generate images! Visit 'http://localhost:3000', input a text prompt, and watch your AI generator work its magic!
Chapter 4: Next Steps
This is a fundamental example, and there are numerous ways to enhance it, such as:
- Allowing users to request multiple image variations.
- Improving the interface design with TailwindCSS.
- Adding share functionality for generated images on social media.
Thank you for following along! You can check out CHARL·E and find the complete repository [here](#).
If you found this guide helpful, feel free to leave a comment! Follow me for more tutorials on web and iOS development!