Skip to main content
Lesson 3 of 14 · Grok API quickstart

The XAI_API_KEY environment variable

Lesson 3 of 14 Updated July 30, 2026 Developer
On this page
  1. Store your key safely
  2. Set XAI_API_KEY
  3. Check the configuration
  4. Production environments
  5. Common mistakes
  6. Key takeaways

Store your key safely

An API key should never appear in plain text in your source code. The standard approach is to store it in an environment variable that your application reads at startup. This separates configuration from code and protects your secrets.

Set XAI_API_KEY

The convention used by xAI and all the official SDKs is the XAI_API_KEY variable. Here’s how to set it on your system.

Linux and macOS

In your terminal, add the variable to your shell profile:

echo 'export XAI_API_KEY="xai-your-key-here"' >> ~/.bashrc
source ~/.bashrc

For Zsh (the default on macOS), replace .bashrc with .zshrc.

Windows (PowerShell)

$env:XAI_API_KEY = "xai-your-key-here"

To make it permanent, use the system environment variables through Advanced settings, or run:

[System.Environment]::SetEnvironmentVariable("XAI_API_KEY", "xai-your-key-here", "User")

.env file (local projects)

For projects that use a framework (Node.js, Django, Flask), create a .env file at the root:

XAI_API_KEY=xai-your-key-here

You must add .env to your .gitignore file so you don’t push your secrets to a Git repository:

# .gitignore
.env
.env.local
.env.*.local

Check the configuration

Test that the variable is available:

echo $XAI_API_KEY

You should see your key. If the command returns an empty line, reload your shell profile or restart your terminal.

In Python, you can check it like this:

import os
key = os.getenv("XAI_API_KEY")
print("Key configured" if key else "Variable missing")

Production environments

In production, don’t use a .env file. Use your platform’s built-in mechanisms instead:

  • Docker: docker run -e XAI_API_KEY=xai-xxx my-image
  • Kubernetes: a Secret mounted as an environment variable
  • Vercel / Netlify / Railway: variables in the project dashboard
  • GitHub Actions: repository secrets (${{ secrets.XAI_API_KEY }})

These systems encrypt secrets at rest and inject them only at runtime.

Common mistakes

  • Extra quotes in the key: if your variable contains literal quotes, requests will fail with an authentication error
  • Variable set in another shell: variables from one terminal aren’t available in another unless they’re exported in your profile
  • Spaces around the = sign: in a .env file, the syntax XAI_API_KEY = value with spaces may fail depending on the library you use

Key takeaways

  • Use the XAI_API_KEY variable, recognized by every xAI SDK
  • Never hard-code the key in your source code
  • Add .env to the .gitignore of all your projects
  • In production, use your hosting platform’s built-in secrets