Building a Next.js AI-Powered Web Application for Beginners

Share:
Tutorial
Beginner
⏱ 45 min read
© Gate of AI 2026-04-07

Learn how to build a simple AI-powered web application using Next.js, OpenAI’s API, and Firebase. This project will introduce you to integrating AI with modern web development frameworks.

Prerequisites

  • Node.js v16.0.0 or higher
  • Next.js v12.0.0 or higher
  • OpenAI API key
  • Firebase account with Firestore enabled
  • Basic understanding of JavaScript and React

What We’re Building

In this tutorial, you will create a simple AI-powered web application using Next.js. The application will allow users to input questions, which will then be processed by OpenAI’s API to generate responses. These responses will be stored in Firebase’s Firestore, and users will be able to view and manage these responses through a responsive user interface styled with Tailwind CSS.

The project demonstrates how to integrate AI into a modern web stack, offering practical insights into using APIs, managing state with Firestore, and creating a user-friendly interface. By the end of this tutorial, you’ll have a functional application and a deeper understanding of how AI can enhance web applications.

Setup and Installation

First, we’ll set up a new Next.js project and install the necessary dependencies. This includes Tailwind CSS for styling, Firebase for database management, and Axios for making API requests.

npx create-next-app ai-nextjs-app
cd ai-nextjs-app
npm install tailwindcss firebase axios

Next, configure Tailwind CSS by creating a configuration file and importing it into your project.

npx tailwindcss init

Create a .env.local file to store your environment variables, including your OpenAI API key and Firebase configuration details.

OPENAI_API_KEY=your_openai_api_key
FIREBASE_API_KEY=your_firebase_api_key
FIREBASE_AUTH_DOMAIN=your_project_id.firebaseapp.com
FIREBASE_PROJECT_ID=your_project_id
FIREBASE_STORAGE_BUCKET=your_project_id.appspot.com
FIREBASE_MESSAGING_SENDER_ID=your_sender_id
FIREBASE_APP_ID=your_app_id

Step 1: Setting Up Firebase

Firebase will be used to store and manage the AI-generated responses. We’ll set up Firestore, which is a flexible, scalable database for mobile, web, and server development from Firebase and Google Cloud Platform.

import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';

const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
export { db };

This code initializes Firebase with your configuration and sets up Firestore. The database instance db is exported for use in other parts of your application.

Step 2: Creating the User Interface

We will use Tailwind CSS to create a simple and responsive user interface. This interface will include a form for users to input their questions and a section to display the AI-generated responses.

import React, { useState } from 'react';
import { db } from './firebase';
import { collection, addDoc } from 'firebase/firestore';

function App() {
const [question, setQuestion] = useState('');

const handleSubmit = async (e) => {
e.preventDefault();
try {
const docRef = await addDoc(collection(db, 'questions'), { question });
console.log('Document written with ID: ', docRef.id);
} catch (e) {
console.error('Error adding document: ', e);
}
};

return (
<div className="container mx-auto p-4">
<form onSubmit={handleSubmit}>
<input type="text" value={question} onChange={(e) => setQuestion(e.target.value)} className="border p-2 w-full" />
<button type="submit" className="bg-blue-500 text-white p-2 mt-2">Submit</button>
</form>
</div>
);
}

export default App;

This component defines a form where users can input their questions. Upon submission, the question is added to the Firestore database. Tailwind CSS classes are used for styling the form and button, providing a responsive design.

Step 3: Integrating OpenAI’s API

In this step, we’ll integrate OpenAI’s API to process the user questions and generate responses. We’ll use Axios to make HTTP requests to the API.

import axios from 'axios';
import { useEffect, useState } from 'react';
import { collection, query, onSnapshot } from 'firebase/firestore';
import { db } from './firebase';

function Responses() {
const [responses, setResponses] = useState([]);

useEffect(() => {
const q = query(collection(db, 'questions'));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
const data = [];
querySnapshot.forEach((doc) => {
data.push({ ...doc.data(), id: doc.id });
});
setResponses(data);
});
return () => unsubscribe();
}, []);

const generateResponse = async (question) => {
try {
const response = await axios.post('https://api.openai.com/v1/engines/davinci-codex/completions', {
prompt: question,
max_tokens: 150
}, {
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
}
});
console.log(response.data.choices[0].text);
} catch (error) {
console.error('Error fetching AI response:', error);
}
};

return (
<div>
{responses.map((resp) => (
<div key={resp.id}>
<p>{resp.question}</p>
<button onClick={() => generateResponse(resp.question)}>Get AI Response</button>
</div>
))}
</div>
);
}

export default Responses;

This component listens for new questions added to Firestore and displays them. Users can click a button to fetch AI-generated responses for each question. The responses are logged to the console, but you can extend this to display them in the UI.

⚠️ Common Mistake: Ensure that your environment variables are correctly configured and accessible in your application. Missing or incorrect API keys can lead to authentication errors when making requests to Firebase or OpenAI’s API.

Testing Your Implementation

To test your implementation, run your Next.js application and interact with the form. Input some questions and ensure they appear in Firestore. Click the “Get AI Response” button and check the console for AI-generated responses.

npm run dev

Open your browser and navigate to http://localhost:3000 to view your application. Verify that questions are stored in Firestore and that AI responses are generated correctly.

What to Build Next

  • Enhance the UI to display AI responses directly in the application instead of logging them to the console.
  • Implement authentication with Firebase to restrict access to certain features of your application.
  • Add error handling and loading states to improve the user experience when interacting with the API.

Share:

Was this tutorial helpful?

What are you looking for?