DEV Community

Obed Avorlenu
Obed Avorlenu

Posted on

Build Your First AI App: A Code-First Guide for Beginners

Forget the high-level theory and endless debates about artificial general intelligence. If you are a developer looking to actually build with AI, the best way to learn is by writing code.
​In this guide, we are going to build a functional AI text generator using Next.js, TypeScript, and the OpenAI API. No fluff, no abstract concepts—just line-by-line code and practical implementation.
​Prerequisites
​Before writing any code, ensure you have the following ready:
​Node.js installed on your machine.
​A code editor (VS Code is recommended).
​An OpenAI API Key (Grab one from the OpenAI developer dashboard).
​Step 1: Project Setup
​We are using Next.js (App Router) for this build because it allows us to handle both our frontend UI and our backend API routes in a single repository.
​Open your terminal and run:
npx create-next-app@latest my-first-ai-app
During the setup, select the following options:
​TypeScript: Yes
​ESLint: Yes
​Tailwind CSS: Yes
​src/ directory: No
​App Router: Yes
​Customize default import alias: No
​Navigate into your new project and install the official OpenAI SDK:cd my-first-ai-app
npm install openai
Create a file named .env.local in the root of your project to securely store your API key:
OPENAI_API_KEY=your_actual_api_key_here
Never commit this file to GitHub. Next.js automatically ignores .env.local by default).
Step 2: Building the API Route (The Backend)
We need a secure place to execute our AI requests so our API key isn't exposed to the client. Next.js Route Handlers are perfect for this.
Create a new file at app/api/generate/route.ts and add the following code
import { NextResponse } from 'next/server';
import OpenAI from 'openai';

// Initialize the OpenAI client with your API key
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});

export async function POST(request: Request) {
try {
// Parse the incoming JSON payload from the frontend
const body = await request.json();
const { prompt } = body;

// Validate that a prompt was actually provided
if (!prompt) {
  return NextResponse.json(
    { error: 'Prompt is required' },
    { status: 400 }
  );
}

// Call the OpenAI API using the gpt-3.5-turbo model
const completion = await openai.chat.completions.create({
  model: 'gpt-3.5-turbo',
  messages: [
    {
      role: 'system',
      content: 'You are a helpful and concise AI assistant.',
    },
    {
      role: 'user',
      content: prompt,
    },
  ],
  temperature: 0.7,
  max_tokens: 500,
});

// Extract the AI's response text
const aiResponse = completion.choices[0].message.content;

// Send the response back to the client
return NextResponse.json({ result: aiResponse });
Enter fullscreen mode Exit fullscreen mode

} catch (error) {
// Handle errors (e.g., rate limits, invalid keys)
console.error('AI API Error:', error);
return NextResponse.json(
{ error: 'Failed to generate response' },
{ status: 500 }
);
}
}
Line-by-Line Breakdown:
​import { NextResponse }...: We import Next.js's built-in response handler to send data back to the browser.
​const openai = new OpenAI(...): This instantiates the OpenAI client. It automatically looks for process.env.OPENAI_API_KEY.
​export async function POST(request: Request): This defines an HTTP POST endpoint. AI generation should always be a POST request because we are sending a payload (the prompt).
​const body = await request.json(): We extract the JSON body sent from our frontend.
​openai.chat.completions.create(...): This is the core engine. We specify the model (GPT-3.5-turbo is fast and cheap for beginners), set the system message to define the AI's personality, and pass the user prompt.
​temperature: 0.7: Controls creativity. 0 is robotic and exact, 1 is highly creative. 0.7 is a good middle ground.
​completion.choices[0].message.content: The OpenAI API returns a deeply nested JSON object. This specific path extracts just the raw text of the AI's answer.
​Step 3: Building the User Interface (The Frontend)
​Now, let's build the visual interface where users can type their prompts and read the AI's responses.
​Open app/page.tsx, delete the boilerplate code, and replace it with this:

'use client';

import { useState } from 'react';

export default function Home() {
// State variables to manage inputs, outputs, and loading status
const [input, setInput] = useState('');
const [output, setOutput] = useState('');
const [isLoading, setIsLoading] = useState(false);

// The function triggered when the user clicks "Generate"
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!input) return;

setIsLoading(true);
setOutput('');

try {
  // Make a POST request to our custom API route
  const response = await fetch('/api/generate', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ prompt: input }),
  });

  const data = await response.json();

  // Check for errors returned by the backend
  if (!response.ok) {
    throw new Error(data.error || 'Something went wrong');
  }

  // Update the UI with the AI's response
  setOutput(data.result);
} catch (error: any) {
  setOutput(`Error: ${error.message}`);
} finally {
  setIsLoading(false);
}
Enter fullscreen mode Exit fullscreen mode

};

return (




My First AI Generator

    <form onSubmit={handleSubmit} className="flex flex-col gap-4">
      <textarea
        className="w-full p-4 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 text-black"
        rows={4}
        placeholder="Ask the AI something..."
        value={input}
        onChange={(e) => setInput(e.target.value)}
      />

      <button
        type="submit"
        disabled={isLoading}
        className="bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 disabled:bg-blue-300 transition-colors"
      >
        {isLoading ? 'Generating...' : 'Generate Response'}
      </button>
    </form>

    {output && (
      <div className="mt-8 p-6 bg-gray-100 rounded-md border border-gray-200 text-black">
        <h2 className="text-sm font-semibold text-gray-500 mb-2">AI Response:</h2>
        <p className="whitespace-pre-wrap">{output}</p>
      </div>
    )}
  </div>
</main>

);
}
Line-by-Line Breakdown:
​'use client';: A required Next.js directive indicating this component runs in the browser, allowing us to use React Hooks.
​const [input, setInput] = useState('');: Manages the text the user types into the textarea.
​const [output, setOutput] = useState('');: Stores the final response returned by the AI.
​const [isLoading, setIsLoading] = useState(false);: Prevents the user from spamming the submit button while waiting for the API.
​const response = await fetch('/api/generate', ...): We call the backend route we created in Step 2, passing the user's input as a JSON string.
​if (!response.ok): Catch backend errors (like a 400 or 500 status code) and throw an exception to be caught in our catch block.
​className="...": We use Tailwind CSS utility classes to rapidly style the app.
​whitespace-pre-wrap: A crucial CSS class for AI text formatting. It ensures that line breaks and paragraphs generated by the AI are actually rendered on the screen, rather than mashed into a single block of text.
​Step 4: Run and Test
​Start your development server:
npm run dev
Open http://localhost:3000 in your browser. Type a prompt like "Write a two-sentence horror story" into the box and hit Generate. You have just built a fully functional, full-stack AI application.
​The Next Step: Monetizing Your AI Skill
​Writing the code is only the first half of the equation; the second half is turning that technical execution into a tangible income stream. Knowing how to wire up an API isn't enough if you don't know how to package and sell the result.
​Once you have mastered these basics, you can monetize this skill in several ways:
​Micro-SaaS: Build a niche AI tool (e.g., an AI cover letter generator for a specific industry) and charge a monthly subscription.
​Freelance Integration: Many traditional businesses want AI integrated into their existing sites but don't know how. You can offer services to build custom AI chatbots for their customer service.
​Digital Products: Package specific, highly optimized prompts and small scripts into templates that you can sell to non-developers.
​If you are looking for practical, actionable steps on how to transition from simply writing code to actually monetizing digital products and tech skills, VectricEarn is an excellent resource to study. It focuses heavily on the business side of content, remote opportunities, and digital monetization, providing the blueprints needed to turn your new AI development skills into actual revenue.
​Keep building, keep shipping, and start looking at your code as a product.

Top comments (0)