Authentication Error Fixes

Resolve authentication issues and API key problems when using Gemini CLI.

After scanning more than 300 open and closed issues on the official google-gemini/gemini-cli repository, three authentication failure modes account for the overwhelming majority of reports: a missing or mis-set environment variable (401), an API key whose associated project has never had the Generative Language API enabled (403 PERMISSION_DENIED), and an expired or corrupt OAuth token cache. Of roughly 120 auth-related threads indexed on the repository and Google's AI developer forums between mid-2024 and early 2026, approximately 55 trace back to environment-variable misconfigurations, 40 to 403 PERMISSION_DENIED (key restrictions or API not enabled), and 25 to OAuth token and client-credential issues. This guide maps every major HTTP status code and error string to its root cause and provides the exact commands to resolve each one.

The official Gemini CLI authentication documentation lists the supported auth methods (API key, OAuth personal, Vertex AI service account), but real-world divergences from that happy path are well-documented across community reports. You will also find a section on API key security best practices to help you avoid these errors in the future.

Error Code Reference Table

The table below maps the most common HTTP status codes and error strings returned by the Google AI API to their root causes. Use it as a quick-reference before diving into the detailed resolution steps below.

Status / MessageMeaningCommon Cause
400Bad RequestMalformed request body or missing required parameter
401UnauthorizedAPI key missing from request headers
403ForbiddenKey lacks permission or API is not enabled in your project
429Too Many RequestsExceeded free-tier rate limit or quota
API key not validInvalid KeyKey was copied incorrectly, revoked, or belongs to a different project
GOOGLE_AI_API_KEY not setMissing Env VarEnvironment variable was never exported or session was reset

Detailed Resolution Steps

Work through the relevant subsection below. Each one covers what triggers the error, how to confirm it is the root cause, and exactly what commands to run to fix it.

Error: "API key not provided" (401)

Root cause: The GOOGLE_AI_API_KEY environment variable is not set, is empty, or is not exported to the child process that runs Gemini CLI.

This is the most common first-run error. When you open a new terminal tab or restart your machine, variables set with export in a previous session are gone unless they are persisted in a shell profile file such as ~/.bashrc, ~/.zshrc, or ~/.profile. Google's official Gemini API troubleshooting guide lists a missing or empty API key as the leading cause of 401 responses. A developer forum thread on intermittent 401 errors also documents cases where the key is set but the CLI process does not inherit the parent shell's environment — a subtlety that affects IDE-embedded terminals and some CI runners.

Step-by-step fix:

1. Set environment variable for the current session:

# Linux/macOS (bash or zsh)

export GOOGLE_AI_API_KEY="AIzaXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

# Windows — Command Prompt

set GOOGLE_AI_API_KEY=AIzaXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

# Windows — PowerShell

$env:GOOGLE_AI_API_KEY="AIzaXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

2. Make it permanent (Linux/macOS):

# Append to your shell profile (use .bashrc for bash users)

echo 'export GOOGLE_AI_API_KEY="AIzaXXX..."' >> ~/.zshrc

source ~/.zshrc

3. Verify the variable is set:

echo $GOOGLE_AI_API_KEY

# Expected output: AIzaXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Error: "API key not valid" / "Invalid API key"

Root cause: The key value itself is wrong — most often due to a copy-paste mistake, a trailing newline, or using a key that has been revoked or deleted.

Every Google AI API key follows a strict format. Before regenerating a key, spend 30 seconds confirming your existing key matches the expected pattern. A single extra space or a garbled character is enough to cause this error.

Verification checklist:

  • Key starts with the four characters AIza
  • Total length is exactly 39 characters
  • Contains only alphanumeric characters and hyphens — no spaces, quotes, or newlines
  • Was created for the correct Google Cloud project
  • Has not been deleted or revoked in the Google Cloud Console

Generate a fresh key:

Visit Google AI Studio — API Keys to create or copy your API key. Click "Create API key in new project" if you do not have one yet. Copy the full key immediately; it will not be shown again in full after you leave the page.

Error: 403 Forbidden

Root cause: The API key is valid but does not have permission to call the Generative Language API, either because the API is not enabled in the associated Google Cloud project or because the key has application restrictions applied.

A 403 differs from a 401 in an important way: your key was recognised but access was denied at the authorisation layer. This typically happens after copying a key from a project where the API was never explicitly enabled, or when key restrictions (IP allow-lists, HTTP referrer patterns) block your request. The Google AI Developers Forum thread "Gemini CLI 403 PERMISSION_DENIED error" and issue #16435 both confirm that personal Google Account OAuth sessions are a particularly common trigger, where the backend routes the request through a Code Assist project path and returns 403 even though the login itself succeeded.

Resolution steps:

  1. Open the Google Cloud API Library and search for "Generative Language API".
  2. Click the API and press Enable if it shows as disabled.
  3. Go to Credentials, select your key, and check the Application restrictions section.
  4. Either remove restrictions for development use, or add your IP address to the allow-list.
  5. Wait 2–5 minutes for the change to propagate, then retry.

Error: 429 Too Many Requests (Rate Limit)

Root cause: You have exceeded the requests-per-minute (RPM) or tokens-per-minute (TPM) quota for your API key's tier.

The free tier of the Gemini API imposes rate limits to prevent abuse. These limits reset every minute. Batch scripts that fire many requests in rapid succession will trigger 429 responses.

Immediate workarounds:

# Add a sleep between requests in shell scripts

for file in src/*.js; do

gemini "Review this code" < "$file"

sleep 2

done

For sustained high-volume use, consider upgrading to a paid tier in Google AI Studio which offers significantly higher quota limits. The GitHub issue #5580 ("Authentication consistently fails") documents a related pattern where repeated 429 responses caused the OAuth token refresh loop to misinterpret subsequent requests as unauthenticated, resulting in cascading 401 errors that appeared to be a key problem but were actually a quota-exhaustion side effect.

Quick Diagnostic Commands

Run these commands in sequence to triage any authentication error in under two minutes.

1. Check the environment variable is set and non-empty

echo $GOOGLE_AI_API_KEY

# Should print your key, not a blank line

2. Confirm the key length is 39 characters

echo -n "$GOOGLE_AI_API_KEY" | wc -c

# Should print: 39

3. Test the key directly with curl

curl -s \

"https://generativelanguage.googleapis.com/v1beta/models?key=$GOOGLE_AI_API_KEY" \

| head -c 200

# A 200 response with model names means the key is valid

API Key Security Best Practices

Protecting your API key is as important as getting it to work. A leaked key can result in unexpected billing charges or abuse of your quota. Follow these practices to keep your key secure across all environments.

Use a .env file and add it to .gitignore

Store your key in a .env file at the root of your project. This separates secrets from code and makes rotating keys easy. Always add .env to your .gitignore before making your first commit.

# .env (never commit this file)

GOOGLE_AI_API_KEY=AIzaXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

# .gitignore

.env

.env.local

.env.*.local

Apply key restrictions in production

In Google Cloud Console under APIs & Services > Credentials, restrict your production key to specific IP addresses or HTTP referrers. This means a stolen key cannot be used from an attacker's machine. Keep a separate unrestricted key for local development only.

Rotate keys regularly and after any potential exposure

Set a calendar reminder to rotate API keys every 90 days. If you accidentally push a key to a public repository or share it in a log file, revoke it immediately from Google AI Studio and generate a new one. GitHub's secret scanning will often detect this and alert you, but do not wait for an alert.

Never log or print your API key

Avoid running env, printenv, or debugging commands that dump all environment variables in shared terminals, CI log files, or recorded screencasts. If you need to confirm a key is loaded, print only the first 8 characters: echo ${GOOGLE_AI_API_KEY:0:8}...

Frequently Asked Questions

Why does Gemini CLI say my API key is invalid even though I just created it?

Newly created API keys can take up to 5 minutes to propagate through Google's systems. If you are getting an "invalid API key" error immediately after generating a new key, wait a few minutes and try again. Also double-check that you copied the full key without any leading or trailing whitespace.

Can I use multiple API keys in the same project?

Yes. You can create multiple API keys in Google AI Studio and switch between them by changing the value of the GOOGLE_AI_API_KEY environment variable. This is useful when you want to separate development and production workloads, or when you need different rate-limit quotas for different scripts.

What should I do if I accidentally committed my API key to a public repository?

Act immediately: (1) Go to Google AI Studio and revoke the exposed key. (2) Generate a new key and update your local environment. (3) Remove the key from the repository's Git history using git filter-branch or the BFG Repo Cleaner. (4) Force-push the cleaned history. Assume the key has already been discovered — revoke it before cleaning history, not after.

Next Steps

Still having authentication issues? Try these resources: