Issues with setting up the .env file for Next.js project using OpenAI API and TypeScript

I'm currently exploring the capabilities of OpenAI's API. Initially, everything was running smoothly as I tested my API key directly within my code. However, upon attempting to move it to a .env file, I encountered some difficulties. Despite putting in effort to troubleshoot and identify the problem, it still remains elusive.

Below is the snippet of 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 API key presence
if (!apiKey) {
    console.error("The OPENAI_API_KEY environment variable is missing or empty.");
}

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

The error message that continuously greets me reads:

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' }).

Though intriguingly, logging my apiKey does display its value on the server console.

Incorporating Next.js into my project, I relied on its built-in .env support instead of installing dotenv. Even so, opting for .env.local over the standard .env has not resolved the issue.

A nagging thought persists that my helper function might be rendered on the client side, potentially causing the undefined API key error.

To maintain confidentiality, I prefer not to expose my API key publicly with NEXT_PUBLIC_.

Are there alternative methods to address this setback?

If anyone holds insight on what step I may have overlooked, kindly share your ideas.

Answer №1

Update your environment variables by adding the following in your .env or .env.local file:

NEXT_PUBLIC_OPENAI_API_KEY="your-key"

Create a server component named serverai.tsx with the following code:

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);
}

Lastly, invoke the runOpenAI function from a client component:

'use client'

import { runOpenAI } from './serverai';

export default function Home() {

  return (
    <div>
      <button onClick={() => runOpenAI()}>Run OpenAI</button>
    </div>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update the Array by replacing the information corresponding to the specific Id

I am working with an array that looks like this : mainArray = [ {name : "Eminem", id : 2}, {name : "Rakim" , id : 3 }, {name : "Kuniva", id : 4 } ] Let's say I decide to update the name "Kuniva" to "Proof" and send this change to the database. The ...

The integration of Angular Reactive Form with Bootstrap is causing issues with custom validation not functioning properly during animation

After creating a Reactive Form in Angular 16 and adding Bootstrap validation to it, I encountered an issue where normal built-in validators work fine but custom validators do not reflect properly. Even though the error is added to the errors array, Bootstr ...

Directives for components and the NgModule

My goal is to divide a component into three separate sections. To achieve this, I created a new component along with its template. However, now I am facing the challenge of including these child components into the main component in order to ensure that th ...

Guide to incorporating a pluck feature into TypeScript code

One task I face frequently is extracting specific properties from an object const obj = {a:1, b: 2, c: 3}; const plucked = pluck(obj, 'a', 'b'); // {a: 1, b:2} Unfortunately, achieving this task with type safety in TypeScript can be c ...

Exploring the possibilities of incorporating dynamic routing within subdirectories

I have a file structure set up like this: ├── books ├── reviews ├── [title].jsx <- need to route here │ └── page.jsx └── page.jsx On the /books page, I display a list of books, each with its own button to ...

Looping through GET requests

I have a Next.js and TypeScript application where a request is made to a webhook integration that returns a Google sheet in JSON format. I've noticed that the integration keeps getting called repeatedly in a loop. Here is a snippet of my code: import ...

Does manipulating the context before retrieving it within a custom ContextProvider adhere to best practices?

In my React application, I have a custom ContextProvider component called RepositoryContext. This component requires a specific ID to be set inside it in order to perform CRUD operations. Here is a snippet of the code: import React, { Dispatch, PropsWithCh ...

Encountering an error with Angular 7: "global is not defined" issue while trying to include a package

While developing an Angular 7 application, I encountered an issue after adding a package using npm install dragula --save and importing it into the pollyfills.ts file. The error message I received was: index.js:2 Uncaught ReferenceError: global is not d ...

What is the best method for excluding attributes from a nested model in sequelize?

In my project, there are 2 models called User and Role, and they have a many-to-many relationship. To manage this connection, I introduced a third model named UserRole. The issue arises when the UserRole is also retrieved in the query below: async getUser ...

Using Cmd+Click in iTerm2 does not function properly when trying to navigate to TypeScript error messages

The appearance of the file name in the output is as follows: path/filename/ext(line,col) as opposed to the typical path/filename/ext:line This deviation causes iTerm2 to display an error message instead of opening the file: An application is not ass ...

Developing a zod blueprint for a versatile interface

Recently, I created a basic interface to handle paginated responses. It looks like this: export interface PaginatedResponse<T> { pageIndex: number; pageSize: number; totalCount: number; totalPages: number; items: Array<T>; } Now, I w ...

Updating the layout when transitioning between routes in Next.js 14 using the AppRouter design concept

I am a beginner in next.js and I want to create a navigation bar that can be shared between components using the approuter concept. I am currently working with next.js version "14.0.2". The folder structure mentioned below in the image https://i.stack.im ...

The timestamps I generate are based on the day following the date

While creating a schema and using {timestamps:true} in Mongo, the fields 'createdAt' and 'updateAt' are supposed to be automatically generated. However, I have noticed that when creating a document with this setup, the day of the date i ...

Obtain the Enum's Name in TypeScript as a String

I am currently looking for a solution to transform the name of an enum into a string format. Suppose I have the following Response enum, how can I obtain or convert 'Response' into a string? One of my functions accepts any enum as input and requi ...

Issue with manipulating element styles using jQuery in Angular2

My method of assigning IDs to elements dynamically using *ngFor looks like this: <div *ngFor="let section of questionsBySubCat" class="col-md-12"> <div class="subcat-container"> <h4 class="sub-cat">{{ section?.subcategory }}& ...

Guidelines for adjusting the next/image component to a full 100% height

In my Next.js application, I am trying to display an image that fills the full height of its container while automatically adjusting its width based on its aspect ratio. I attempted the following method: <Image src="/deco.svg" alt=&qu ...

Implementing Avro file deserialization in a React application

I could really use some assistance with deserializing an avro file in a react application. I attempted to use the avsc npm package, but now I have encountered an error. const avro = require('avsc') ...... avro.createFileDecoder('./abc.avro&a ...

Tips for inserting an object into an array

Here's the data I received: { 0:{modifierId: 4, modifierName: 'Garlic', modifierPrice: 60 } 1:{modifierId: 1, modifierName: 'Tartar ', modifierPrice: 60} 2:{modifierId: 3, modifierName: 'Herb ', modifierPrice: 60} item ...

Cannot pass a Node/JS Promise to a variable using then statement

I am facing an issue with a promise in a class. Here is the code snippet: someMethod() { return new Promise(function(resolve) { resolve(10); } } Although I know that the value will be 10, I am trying to pass it to a variable called myvar ...

What could be causing my D3.js stacked bar chart to show inaccurate results?

I'm encountering some challenges while creating a stacked bar chart in d3.js. The current appearance of my chart is depicted here (developed with D3.js): https://i.sstatic.net/G6UA6.png However, I aim to achieve a design similar to this one (crafted ...