0

I am trying to use OpenAI's API. My code works great when I tested my API key directly in my code, but when I tried moving it to a .env file, it stopped working. I've been trying to figure out what the issue is but cannot figure it out.

Here is my code:

import OpenAI from "openai";

const apiKey: string = process.env.OPENAI_API_KEY;
const assistantId: string = process.env.OPENAI_ASSISTANT_ID;

console.log(apiKey)
console.log(assistantId)

// Check if API key is provided
if (!apiKey) {
    console.error("The OPENAI_API_KEY environment variable is missing or empty.");
}

const openai = new OpenAI({ apiKey: apiKey });

Here is the error I have been receiving: Error: The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).

But when I console.log my apiKey, I see it in my server console.

I am using Next.js, and have read that Next has built in .env support so I don't need to npm install dotenv. I've tried using .env.local instead of standard .env and still having issues.

I'm also worried that my helper function is being client side rendered which is why my API key could be coming back as undefined.

I don't want my API key to be displayed publically with NEXT_PUBLIC_.

Is there another way to get this working?

Any ideas on what I could be missing?

2
  • 2
    Environment variables are not available to the client/browser unless it's prefixed with NEXT_PUBLIC_. Make sure this helper function lives only on the server, and you can expose it through a route or something. Commented Mar 6, 2024 at 19:07
  • Got it. So I should change this to be on an API route so that it only lives on the server? Commented Mar 6, 2024 at 19:39

1 Answer 1

-2

in your .env or .env.local add

NEXT_PUBLIC_OPENAI_API_KEY="you-key"

and then you can make a server component like (serverai.tsx):

import { generateText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';

export const runOpenAI = async () => {

    const openai = createOpenAI({ apiKey: process.env.NEXT_PUBLIC_OPENAI_API_KEY })

    const { text } = await generateText({
        model: openai('gpt-3.5-turbo'),
        system: 'You are a friendly assistant!',
        prompt: 'Why is the sky blue?',
    });

    console.log(text);
}

finally, call from a client component:

'use client'

import { runOpenAI } from './serverai';

export default function Home() {

  return (
    <div>
      <button onClick={() => runOpenAI()}>Run OpenAI</button>
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

I don't think it's a good idea to be exposing your Open AI key in client side code like this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.