How I combined chatGPT with NextJS 13 to create my app

Poatek
Poatek
Published in
7 min readMar 28, 2023

The so-called “artificial intelligence chatbot” of the XXI century is constantly generating a lot of content since its release in November of 2022. Highlights and Clickbait titles, reports, and news, the last trimester has been filled with chatGPT inside those. Nowadays, everybody with an internet connection knows that this “Superpowered AI that will steal your job” exists, and many people are scared about it.

Usage of chatGPT

As an enthusiast of futuristic technology (or maybe contemporary technology?) and a Software Engineer at Poatek, since the initial release, I’ve been not only impressed but a constant user/tester of OpenAi’s new tool. It’s easy to use, with no need for manuals, documentation to read before using it, or pointers on the screen to show where to click (which are usually pretty common in apps). Just a blank screen (or a dark one if you use a dark theme on your system) with some information about the software and an input field to write something.

“Go on, write something…” is the first thought, and there you go: “Why are manholes round?” This a stupid question that sometimes is asked of candidates being interviewed for a job. The answer I got?

Manholes are typically round in shape for a few reasons:

1. Safety: A round manhole cover cannot fall through the opening since it cannot drop in diagonally. Square covers could potentially fall in if they were inserted diagonally, which could be dangerous for pedestrians or workers who might be using the manhole.

2. Efficient use of space: A round cover fits snugly into a round hole, leaving no gaps around the edges. Square covers would leave gaps at the corners, which would require additional material to be used to fill those gaps.

3. Easier to move: Round covers are easier to move because they can be rolled or rotated, whereas square covers can only be moved by lifting them straight up and putting them back down.

4. Standardization: The use of round manhole covers has been standardized in many countries and municipalities, making them easier to manufacture and transport. This also ensures that covers from different manufacturers can be used interchangeably.

Overall, the round shape of manhole covers has proven to be a practical and effective choice for safety, efficiency, and standardization reasons.

And there it is chatGPT working as intended. That is the 3-step process that is scaring some people that I know. 4 steps if you count the “login step” that may “steal all my data” or something related.

That’s when the idea came to mind: why not try to use the chatGPT API on a custom environment to show to some folks? Skip these steps that may “scare” some people and just let them use it right away.

Image by Emiliano Vittoriosi

Creating an app to demo chatGPT

1. Create a new Next project:

As simple as it is, yarn create next-appwas on my terminal, and I was creating a new Next App. A little and fast project that should be up and running in under 1 hour. (Made on the weekend, maybe I should be away from the screen? 🤔)

I know, I know, what an outstanding name.

Note: I will not talk about the incredible new features that Next Js 13 brings with itself, in a future Medium post we will talk about every use of every new feature, so follow Poatek here and stay tuned.

2. Think what to do:

With only 58 minutes or so, after the command runs, left to develop this project, I started searching the internet to know how this could be achieved. The first stop was obviously provided by muscular memory itself. Google. But after writing something on the input field and getting a lot of links to click (and some videos that I’ve saved for later) I got a bit lazy to read so many things that weren’t necessarily what I was looking for. So — I asked chatGPT how I could integrate it with a NextJS app.

The first answer was not exactly right, and that’s good, now I know I have to either write a question with more details on what I want, or I should go back to Google. (The third option would be reading a lot of documentation, which resulted in my mind screaming: “me lazy, me no like letters”).

3. Just do it:

Okay, the plan is simple:

  1. Make a home page that has an image and a button to start chatting
  2. Create a (friendly) page with input to write whatever the user wants
  3. Maybe some pictures to make it look more like a chat
  4. Don’t write chatGPT anywhere across the app (it will scare people!)
  5. Optional: add dark mode and light mode

Let’s start!

So, let’s get our OPEN_API_KEY. It’s basic and takes less than a minute. Just go to https://platform.openai.com/account/api-keys (You need to be logged in) and click on create a new secret key. Boom, that’s it.

With the project already running on VSCode, I’ve created a .env file to insert the OPENAI_API_KEYwhich is the only environment key that we will have for this project. It should be like this:

 OPENAI_API_KEY=<YOUR AWESOME KEY>

Now, let’s start working by installing OpenAi’s lib and importing it on a file to use as a route on the backend of our Next JS app.

I’ve created a file called “chat.ts” inside a folder called ‘api’. The path should be something like pages/api/chat.ts

With only 30 lines of code, we can ask questions using the chatGPT completion model:

import { NextApiRequest, NextApiResponse } from 'next'
import { Configuration, OpenAIApi } from 'openai'

const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
})

const openai = new OpenAIApi(configuration)

export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
const prompt = req.body.prompt

if (!prompt) {
return new Error('There was an error with you text, try again!')
}

const chatResponse = await openai.createCompletion({
model: 'text-davinci-003',
prompt: prompt,
max_tokens: 2048,
temperature: 0.8,
})

const response =
chatResponse.data.choices[0].text?.trim() || "I'm offline, try again later"
res.status(200).json({ text: response })
}

And… it’s live!

Note: It took me some minutes to finally understand that my personal usage quota was disabled, don’t forget to check that!

But this is only an API call on the backend; let’s make it user-friendly to the end user. With the project running, I launched the browser, and the landing page was already like this:

The initial state of our page is just like that. A bit of glass morphism, a minimalistic and clean screen, a bit of text, and that is it. Let’s customize this screen to invite the user to use the chat function.

We will be reusing much of what is already here to spend less time on visuals and more on usage.

I removed the components from the bottom of the page, created a Button to “Start the conversation” and now, as the following image shows, we have an input to ask a question, and the answer comes on top of that.

I know it’s not beautiful, but it will do the job for now.

Once it’s done, a bit of attention to detail will take care of the rest of the job, for now, I believe I can say that I’ve fully integrated chatGPT and NextJS 13 in the simplest way possible. And the deployment of this web app is super simple too, just by running vercel — prod in the terminal, and vercel will take care of that for me.

4. So? (Conclusion)

Even though it may scare people, chatGPT is still just another AI chatbot, okay, a superpowered one, but it has its limitations and sometimes get things really, really wrong.

The integration was super easy to do, the usage is simple, and the chat can be infinite (as long as you want to pay for use). This app was created to serve as a demo for some folks that may not have used chatGPT before, it can be better, and I may be working more on this later.

For now, I can only say that AI is coming to stay, and it’s coming fast! And if you reached this part of this post, you are awesome. Thanks for spending this time here, I hope you create awesome things with this little demo!

Guilherme Zago

--

--

Poatek
Poatek
Editor for

We’re a software engineering company filled with the best tech talent!📍Porto Alegre, São Paulo, Miami and Lisbon linktr.ee/poatek.official