Google Generative AI API Key Error with Vue 3 and Vite Build Setup

I’m working on a Vue 3 project using Vite to implement a chatbot. However, I keep encountering the following error:

AI_LoadAPIKeyError: Google Generative AI API key is missing. Pass it using the 'apiKey' parameter. Environment variables is not supported in this environment.
    at loadApiKey (load-api-key.ts:25:11)
    at getHeaders (google-provider.ts:111:23)
    at resolve (resolve.ts:14:14)
    at GoogleGenerativeAILanguageModel.doGenerate (google-generative-ai-language-model.ts:217:13)
    at async fn (generate-text.ts:351:30)

I believe this occurs because the loadApiKey tries to access process.env which does not work with Vite. I have also attempted using import.meta.env without success.

Here’s an example of my component:

<template>
  <v-card-text>Chat Assistant Feature</v-card-text>
  
  <v-text-field
    v-model="userInput"
    density="compact"
    placeholder="Ask me anything and I'll help you out!"
    prepend-inner-icon="mdi-message-outline"
    variant="outlined"
  />
  <v-btn @click="handleSubmit" :disabled="!userInput">Send</v-btn>
</template>

<script setup>
import { generateResponse } from '@/helpers/aiHelper';
import { ref } from 'vue';

const userInput = ref("");

const handleSubmit = async () => {
  await generateResponse(userInput.value);
};
</script>

My environment setup includes:

GOOGLE_GENERATIVE_AI_API_KEY=my_secret_key_here

I’m using version 1.2.1 of @ai-sdk/google. It seems the issue arises from the node_modules where the API key loading tries to access environment variables that aren’t available in the browser. Any suggestions on how to resolve this?

Yeah, ai-sdk packages need server environments. Switch to @google/generative-ai - it’s built for client-side use. Just import GoogleGenerativeAI and pass your key when creating the instance. David’s right about security though. For dev work, prefix your env var with VITE_ (like VITE_GOOGLE_AI_KEY) and access it with import.meta.env.VITE_GOOGLE_AI_KEY

You’re running into a classic security issue. The @ai-sdk/google package is built for Node.js, not browsers. Right now you’re exposing your API key to anyone who views your client-side code - that’s a huge security risk. Here’s what you need to do: create a backend API endpoint to handle the Google AI calls. Set up an Express.js server (or similar) where you can safely store your API key in environment variables. Then update your Vue component to call your backend instead of hitting Google’s API directly. If you absolutely need everything client-side for prototyping, try the official Google AI JavaScript SDK (@google/generative-ai) and pass your API key directly to the constructor. But remember - this exposes your key publicly and should never go to production.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.