Modern AI Integration: OpenAI API in Your Next.js App
Integrating OpenAI’s API into a Next.js application allows you to leverage advanced AI capabilities, such as natural language processing and content generation. This step-by-step guide will walk you through the process of integrating OpenAI into your Next.js app, leveraging the latest features of Next.js including the App Router.
Prerequisites
Before getting started, ensure you have the following:
- A Next.js application set up with the App Router enabled.
- An OpenAI API key. You can obtain one by signing up at OpenAI’s platform.
- Basic knowledge of React and Next.js.
- Node.js installed on your system.
Step 1: Install Dependencies
Start by installing the required dependencies. OpenAI provides an official Node.js client that simplifies API integration. To install it, run:
npm install openai
Step 2: Secure Your OpenAI API Key
Store your OpenAI API key in an environment file to keep it secure and avoid exposing it in your codebase. Create a .env.local
file in the root of your project and add your key:
OPENAI_API_KEY=your_openai_api_key_here
Environment variables prefixed with NEXT_PUBLIC_
are exposed to the browser, so avoid this prefix for sensitive data.
Restart your development server after creating or modifying the .env.local
file.
Step 3: Set Up the OpenAI Client
Create a utility file to configure and initialize the OpenAI client. For example, create a file named openai.ts
in the lib
directory:
import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
export default openai;
With the App Router, you can create server functions within the app/api
directory. Create a new file at app/api/generate/route.ts
:
import { NextResponse } from 'next/server';
import openai from '@/lib/openai';
interface GenerateRequest {
prompt: string;
}
export async function POST(request: Request) {
const body: GenerateRequest = await request.json();
if (!body.prompt) {
return NextResponse.json({ error: "Prompt is required" }, { status: 400 });
}
try {
const response = await openai.createCompletion({
model: "text-davinci-003",
prompt: body.prompt,
max_tokens: 150,
});
return NextResponse.json({ result: response.data.choices[0].text });
} catch (error) {
console.error(error);
return NextResponse.json({ error: "Failed to generate response" }, { status: 500 });
}
}
This API route follows the App Router’s convention for defining server-side routes.
Step 5: Build the Frontend
In the app
directory, modify your page.tsx
file to create a simple UI for interacting with the API route:
'use client';
import { useState, FormEvent } from 'react';
export default function Home() {
const [prompt, setPrompt] = useState<string>("");
const [response, setResponse] = useState<string>("");
const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const res = await fetch("/api/generate", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ prompt }),
});
const data = await res.json();
if (res.ok) {
setResponse(data.result);
} else {
console.error(data.error);
}
};
return (
<div>
<h1>OpenAI Integration with Next.js</h1>
<form onSubmit={handleSubmit}>
<textarea
value={prompt}
onChange={(e) => setPrompt(e.target.value)}
placeholder="Enter your prompt here..."
/>
<button type="submit">Generate</button>
</form>
{response && <div><h2>Response:</h2><p>{response}</p></div>}
</div>
);
}
Step 6: Test Your Integration
Run your Next.js development server:
npm run dev
Open your application in the browser and test the form. Enter a prompt, submit it, and see the AI-generated response displayed below the form.
Best Practices
- Rate Limiting: Implement rate limiting to prevent abuse of your API route.
- Error Handling: Provide user-friendly error messages and handle edge cases.
- Environment Variables: Never expose your OpenAI API key in the frontend.
- Token Usage: Monitor your API usage to avoid unexpected costs.
Conclusion
With these steps, you’ve successfully integrated OpenAI into your Next.js app using the latest features of the framework. This foundation allows you to build applications with advanced AI capabilities, such as chatbots, text summarization, or content generation. Experiment and unlock the potential of AI in your projects!
Alright folks, that’s a wrap! Hope you enjoyed this article!
For information on my consulting services visit: adhithiravichandran.com
To stay connected follow me @AdhithiRavi or LinkedIn/adhithi
You can checkout my courses on React, Next.js and other topics here:
https://app.pluralsight.com/profile/author/adhithi-ravichandran