Next.js Discord

Discord Forum

Nextjs 14 | Chatgpt

Unanswered
alexluk posted this in #help-forum
Open in Discord
Hello, initially, I want to set up simple translation with gpt 3.5 turbo in my nextjs 14 app. When I use NEXT_PUBLIC_OPENAI_API_KEY in app/page.tsx (client side) and .env.local NEXT_PUBLIC_OPENAI_API_KEY=secret key etc. it works good but when i try to move my openai api call on a server side (for security reasons) I get page.tsx:11 POST http://localhost:3000/api/translation 404 (Not Found). I don't know exactly why as everything seem so be well done.

Thank you very much for your help!

Below code:

1.
I changed .env.local OPENAI_API_KEY=secret key

2.
app/api/translation.ts
import type { NextApiRequest, NextApiResponse } from 'next';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method === 'POST') {
    const { input } = req.body;
    const response = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        model: "gpt-3.5-turbo",

        messages: [
          {
            role: "system",
            content: "You are a helpful assistant."
          },
          {
            role: "user",
            content: `Translate these English words into French: ${input}`
          }
        ],
      }),
    });

   (...)

  }
}

3.

app/page.tsx
"use client";
import Navbar from './components/navbar'
import { useState } from 'react';

const HomePage = () => {
  const [input, setInput] = useState('');
  const [translation, setTranslation] = useState('');

  const handleTranslate = async () => {
    const response = await fetch('/api/translation', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        input: input,
      }),
    });

  

(...)

export default HomePage;

8 Replies

There are a couple of things wrong there.

The first is that you should never expose api keys to your front-end. That means that you have to avoid adding the NEXT_PUBLIC_ prefix to any sensitive environment variable. It's a good thing that you changed it.

The second thing is that route handlers in the app router should export functions with HTTP verbs like GET, POST, PUT, etc.
So you should change your handler function from this:
export default async function handler() {
  // ...
}

to this:
export async function POST() {
  // ...
}
And if you need to handle multiple http verbs just export multiple function with the corresponding name
Unfortunately with:
export async function POST(req: NextApiRequest, res: `NextApiResponse) {
  const { input } = req.body;
  const response = await fetch('https://api.openai.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Authorization': Bearer ${process.env.OPENAI_API_KEY},
      'Content-Type': 'application/json',
    },
` I still get page.tsx:12 POST http://localhost:3000/api/translation 404 (Not Found)
There are three things wrong there :thinq:

Your route file should be nested inside a folder. Instead of having it like this /app/api/translation.ts, it should be /app/api/translation/route.ts
You should read up on Next.js app router file conventions.

See: https://nextjs.org/docs/app/api-reference/file-conventions
Unfortunately I still get 404 (Not Found), where do I make a mistake? Can you look at this code? Thank you very much for your commitment!
There are a couple of things that you could do. First remove the default keyword from the route export. The POST handler should be a named export and not a default one.

Then you could move the functionality in a server action and call it from your page instead of fetching your owna api routes. For more information about server actions refer to the docs here: https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations
thank you for help I used chat and completions hook: https://sdk.vercel.ai/docs/guides/frameworks/nextjs-app