Getting 401 Unauthorized only on netlify , works perfectly on local

has anyone worked with gemini api? does it not work on public suffix domain like *.netlify.app , on my local the api is working perfectly but on netlify i am getting error ApiError: {“error”:{“message”:“”,“code”:401,“status”:“Unauthorized”}}

Hi @Omkar_Garde ,

Welcome to the Forum!
To help us investigate the issue effectively, could you please provide the following details?

  • The specific Gemini model you are using.

  • The exact prompt that is causing the problem.

exact same issue here… will post here if i figure out a solution

Using Gemini 3 Pro (Direct API)

update: i ended up just using gemini 3 through OpenRouter to bypass the direct api issue (if there is one at all)

Same problem using @google/genai sdk with nextjs on netlify.

Interestingly, running locally via next dev I got no auth errors. Running exact same codebase via deployed .netlify.app I get the 401 auth error. For my own sanity, I logged the api key the app picked up and in both scenarios they are identical.

I have no application or api restrictions on my api key.

I’m using the gemini-2.5-flash-image model. The code fragment causing the error is as follows:

  const result = await ai.models.generateContent({
    model: IMAGEGEN_AI_MODEL,
    contents: [
      {
        inlineData: {
          mimeType: originalImageMimeType,
          data: base64ImageData,
        },
      },
      { text: "Remove the background from this image of flowers and replace it with a white background." },
    ],
    config: {
      responseModalities: [Modality.IMAGE, Modality.TEXT],
    },
  });