Invalid API KEY Error with Gemini 1.5 Flash

import { GoogleGenerativeAI } from "@google/generative-ai";

export default async function getAIPostContent() {

    const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY!);
    const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

    const prompt = "Generate a simple but nice and engaging socila media post \
                    that is acceptable by most social media topics and is in \
                    the interest of most viewers";

    const result = await model.generateContent(prompt);
    console.log(result);

    return result.response.text();
}
{"generationConfig":{},"safetySettings":[],"contents":[{"role":"user","parts":[{"text":"Generate a simple but nice and engaging socila media post                     that is acceptable by most social media topics and is in                     the interest of most viewers"}]}]}

I have a correct API i generated and this code was copied and pasted from https://ai.google.dev/api?lang=node

yet is say the API KEY is invalid

1 Like

Sometimes keys can get extra “noise” added when they are copy/pasted.

Can you run this code, assuming your key is in a KEY variable:

console.assert(KEY.trim() == KEY, "Key has extra whitespace at the start or end");
console.assert(KEY.slice(0, 4) == 'AIza', "Key should start with 'AIza'");
console.assert(KEY.length == 39, "Key is not the correct length");

If your key is in good shape, it should throw no errors.

2 Likes