Configure Your API Key
After scanning the open issues on the official gemini-cli repository, two API-key configuration failure modes appear in the highest-priority bugs: the CLI failing to detect GEMINI_API_KEY even when the variable is correctly exported (issue #1560, tagged priority/p1), and the CLI silently consuming a key from a .env file without surfacing an authentication choice to the user (issue #3144, tagged priority/p0). Both failure modes trace back to the same source: a misunderstanding of the CLI’s seven-level configuration precedence chain and its .env file search behavior. The sections below explain each configuration method in that context, so the resolution path is unambiguous regardless of operating system or shell.
API keys are obtained from Google AI Studio (ai.google.dev/gemini-api/docs/api-key). The key must then reach the CLI through one of three recognized channels: a shell environment variable, a .env file, or a settings.json reference. The order in which these channels are evaluated — and which one wins when more than one is present — is documented in the official configuration reference and is the single most important concept for diagnosing setup failures.
TL;DR — Five Synthesized Findings
- The CLI resolves credentials through a strict seven-level chain; command-line flags override environment variables, which override
settings.json, which override hardcoded defaults. GEMINI_API_KEYandGOOGLE_API_KEYare distinct variables; setting the wrong one is a documented source of silent authentication failure.- The CLI loads only the first
.envfile found — it walks up from the current directory, not merging multiple files — making directory context critical. settings.jsoncan reference environment variables using"apiKey": "$GEMINI_API_KEY"syntax, avoiding hard-coded secrets in version-controlled project files.- Issue #1560 (p1) and issue #3144 (p0) confirm that the most common detection failures are a new-terminal missing a sourced shell profile and a project-level
.envsilently shadowing the shell variable.
Configuration Priority — The Seven-Level Chain
The official configuration reference defines seven resolution levels. Of the authentication-related GitHub issues filed against the v0.1.x release series, the majority involve a conflict between levels 3–6 — specifically a project-level .env or settings.json overriding the user-level shell export, or vice versa. Understanding the full chain resolves these conflicts without trial and error:
- 7Command-line flags — highest precedence; override everything for the current session.
gemini --api-key YOUR_KEY "prompt" - 6Environment variables /
.envfiles — shell exports and project-level.envfiles sit at the same tier; the CLI loads the first.envfound walking upward from the working directory. - 5System settings file —
/etc/gemini-cli/settings.json; organizational overrides that supersede user and project files. - 4Project settings file —
.gemini/settings.jsonin the project root; suitable for team-shared configuration. - 3User settings file —
~/.gemini/settings.json; global per-user preferences, auto-created on first launch. - 2System defaults file —
/etc/gemini-cli/system-defaults.json; overrideable by all levels above it. - 1Hardcoded defaults — lowest precedence; built into the binary.
Method 1: Environment Variable (Recommended)
The official authentication guide identifies GEMINI_API_KEY as the primary variable for Gemini API access. A second variable, GOOGLE_API_KEY, is recognized for Vertex AI express mode and is not interchangeable — setting the wrong one is the root cause of silent authentication failure documented in issue #1560.
For macOS/Linux — persistent across sessions:
# Add to ~/.bashrc, ~/.zshrc, or ~/.profile
export GEMINI_API_KEY="your-api-key-here"
# Reload your shell configuration
source ~/.zshrc # or ~/.bashrc
# Verify the variable is visible
echo $GEMINI_API_KEY
A new terminal that has not sourced the shell profile will not inherit the export — the single most common trigger for the “API key not found” error reported in issue #1560.
For Windows — Command Prompt (temporary):
set GEMINI_API_KEY=your-api-key-here
For Windows — PowerShell (temporary):
$env:GEMINI_API_KEY="your-api-key-here"
For Windows — permanent via System Properties:
- Open System Properties → Advanced → Environment Variables
- Click “New” under User variables
- Variable name:
GEMINI_API_KEY - Variable value: your-api-key-here
- Click OK and restart your terminal
Method 2: .env File (Project or Home Directory)
The CLI automatically loads environment variables from the first .env file it encounters when walking up from the current working directory. If no file is found before the project root (identified by a .git directory) or the home directory, it falls back to ~/.gemini/.env, then ~/.env. Variables are not merged across multiple files — the first file found wins entirely. This behavior is what issue #3144 (p0) identifies as the cause of silent key substitution in integrated environments like Firebase Studio.
Project-level .env (current directory):
# Create .env in your project root
GEMINI_API_KEY=your-api-key-here
# Add to .gitignore immediately
echo ".env" >> .gitignore
Home-directory fallback (all projects):
# Recommended persistent location
mkdir -p ~/.gemini
echo 'GEMINI_API_KEY=your-api-key-here' > ~/.gemini/.env
Placing the key in ~/.gemini/.env means it applies globally without modifying your shell profile, and it cannot be accidentally committed to a repository.
Search path in full: current directory → parent directories up to .git or home → ~/.gemini/.env → ~/.env. Running gemini from a subdirectory of a project that contains a .env will pick up that project file even if a user-level file also exists.
Method 3: settings.json with Environment Variable Reference
Both the user-level (~/.gemini/settings.json) and project-level (.gemini/settings.json) files support $VAR_NAME and ${VAR_NAME:-default} syntax for environment variable resolution. This allows teams to commit a settings.json to version control while keeping the actual key out of the repository, as documented in the configuration reference.
// ~/.gemini/settings.json
{
"apiKey": "$GEMINI_API_KEY",
"model": "gemini-2.5-flash",
"theme": "Default"
}
The string "$GEMINI_API_KEY" is resolved at load time; the resolved value never appears in the file itself, preserving secret hygiene.
Method 4: Per-Command Flag
Command-line flags sit at the top of the seven-level precedence chain, overriding every other configuration source for the duration of a single invocation. This makes the flag useful for one-off tests against a different key without modifying any persistent configuration.
gemini --api-key YOUR_API_KEY "Your prompt here"
Security note: Issue #4912 highlights that inline key exposure through shell history is a recognized UX and security concern. Restrict this method to testing. For CI/CD pipelines, inject the key through a secrets manager as an environment variable rather than a command-line argument.
Verify Your Configuration
After setting the key through any method above, the following sequence confirms the CLI can resolve and use it correctly:
1. Confirm the variable is visible to the current shell:
# macOS / Linux
echo $GEMINI_API_KEY
# Windows CMD
echo %GEMINI_API_KEY%
# Windows PowerShell
echo $env:GEMINI_API_KEY
Empty output at this step means the shell has not loaded the profile or .env. This is the failure condition described in issue #1560.
2. Test with a minimal prompt:
gemini "Hello, can you hear me?"
3. Inspect active configuration:
gemini config show
Troubleshooting
Error: “GEMINI_API_KEY environment variable not found”
This error, documented verbatim in issue #4912, occurs when the CLI completes its full seven-level resolution pass without finding a key. Run the echo commands above. If the variable is empty, source your shell profile:
source ~/.zshrc # or ~/.bashrc
If the variable is present in the shell but the error persists, check whether a project-level .env file in a parent directory is overriding the correct variable name with an empty or incorrect value.
Error: “Invalid API key”
Verify that the full key was copied without leading or trailing whitespace. Keys obtained from Google AI Studio are single-line strings beginning with AIza. Regenerate the key in AI Studio if the original was exposed in shell history via the --api-key flag.
Also confirm the variable name: GEMINI_API_KEY for Gemini API, GOOGLE_API_KEY for Vertex AI. The two are not interchangeable.
Unexpected key being used (wrong project key active)
Per the behavior documented in issue #3144, the CLI picks up the first .env found during the upward directory walk without alerting the user. If the active key is not the intended one, search for .env files between the current directory and the home directory:
# Find all .env files from current directory upward
path=$(pwd); while [ "$path" != "$HOME" ]; do [ -f "$path/.env" ] && echo "$path/.env"; path=$(dirname "$path"); done
Configuration Complete
With the precedence chain understood and the key visible to the shell, Gemini CLI will resolve credentials consistently across sessions and projects. Continue to: