node.jsfirebasefunctiongoogle-cloud-functionsopenai-api

I get Error TypeError: Cannot read properties of undefined (reading 'key')


I'm experiencing a couple of issues with configuring and using OpenAI in a Firebase function.

When trying to access the OpenAI API key in the openaiConfig.ts file, I get the error:

TypeError: Cannot read properties of undefined (reading 'key')

Here's the relevant part of the code:

import OpenAI from 'openai';
import * as functions from 'firebase-functions';

const openaiApiKey = functions.config().openai.key;

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

I set the environment variable using the command:

firebase functions:config:set openai.key="MY_KEY"

Additional Information:

The functions execute normally when deployed to the cloud. The issue occurs only when running locally with the command:

firebase emulators:start

Version: firebase-admin: "^12.1.0", firebase-functions: "^5.0.0", openai: "^4.56.0"


Solution

  • When testing locally, use the Firebase Functions emulator. Make sure to set the environment configuration for the emulator as well:

    firebase functions:config:get > .runtimeconfig.json
    

    This command creates a .runtimeconfig.json file in your functions directory, which the emulator will use.