OpenAI Codex CLI Installation & Setup Guide: Generate Code with Natural Language in Your Terminal
OpenAI Codex CLI: From Installation to Your First AI-Powered Code Generation
OpenAI Codex CLI is an open-source command-line tool that brings the power of AI code generation directly into your terminal. Instead of switching between browser-based AI assistants and your development environment, Codex CLI lets you describe what you want in plain English and watch as it writes, edits, and executes code right where you work. This guide walks you through every step — from API key creation to sandbox configuration and VS Code integration.
Prerequisites
- Node.js 22 or higher — Codex CLI is built on Node.js
- Git — required for repository-aware context
- An OpenAI API account with billing enabled
- Operating System: macOS or Linux recommended (Windows via WSL2)
Step 1: Obtain Your OpenAI API Key
- Navigate to
platform.openai.comand sign in to your OpenAI account. - Go to Settings → API Keys in the dashboard.
- Click Create new secret key. Give it a descriptive name like
codex-cli-dev. - Copy the key immediately — it will only be shown once. It will look like:
sk-proj-xxxxxxxxxxxxxxxxxxxx - Set the environment variable in your shell profile:
# Add to ~/.bashrc, ~/.zshrc, or ~/.profile
export OPENAI_API_KEY=“YOUR_API_KEY”
Reload your shell configuration
source ~/.bashrc
Verify the key is set correctly:
echo $OPENAI_API_KEY
Should print your key starting with sk-proj-…
Step 2: Install Codex CLI
Install the Codex CLI globally using npm:
# Install globally via npm
npm install -g @openai/codex
Verify the installation
codex —version
If you prefer not to install globally, you can run it directly with npx:
npx @openai/codex@latest “explain this project”
Step 3: Configure Sandbox Mode
Codex CLI provides three approval modes that control how much autonomy the agent has. Choosing the right mode is critical for both safety and productivity.
| Mode | Flag | Behavior | Best For |
|---|---|---|---|
| **Suggest** | --suggest | Reads files freely; requires approval for every write and command | Learning, exploring unfamiliar codebases |
| **Auto Edit** | --auto-edit | Applies file edits automatically; requires approval for commands | Day-to-day development with safety guardrails |
| **Full Auto** | --full-auto | Runs commands and edits files without approval inside a sandbox | Batch operations, CI/CD pipelines |
Set your preferred default mode in the configuration file:
# Create or edit the config file
mkdir -p ~/.codex
cat > ~/.codex/config.yaml << ‘EOF’
model: o4-mini
approvalMode: auto-edit
notify: true
EOF
In **Full Auto** mode, Codex CLI applies network-disabled, directory-sandboxed execution to prevent unintended side effects. Commands run inside a restricted environment where network access is blocked and file system writes are limited to the current working directory and temporary folders.
Step 4: Your First Codex CLI Session
Navigate to a project directory and launch Codex CLI in interactive mode:
# Start an interactive session
cd ~/my-project
codex
Or pass a one-shot prompt directly
codex “create a Python function that reads a CSV file and returns the top 5 rows sorted by the second column”
Example workflow — generating and running a utility script:
# Generate a script
codex “write a bash script that finds all TODO comments in .js files and outputs them as a markdown checklist”
Ask Codex to explain existing code
codex “explain what the authenticate middleware in src/middleware/auth.ts does”
Refactor with context
codex “refactor the database connection logic in db.py to use connection pooling”
Step 5: VS Code Integration
You can integrate Codex CLI directly into VS Code using the built-in terminal for a seamless workflow:
- Open VS Code and navigate to your project folder.
- Open the integrated terminal with
Ctrl+`(backtick). - Ensure your
OPENAI_API_KEYenvironment variable is available in the VS Code terminal. Add it to your VS Code settings if needed:
// .vscode/settings.json
{
“terminal.integrated.env.linux”: {
“OPENAI_API_KEY”: “YOUR_API_KEY”
},
“terminal.integrated.env.osx”: {
“OPENAI_API_KEY”: “YOUR_API_KEY”
}
}
- Create a VS Code task for quick access. Add to
.vscode/tasks.json:
{
"version": "2.0.0",
"tasks": [
{
"label": "Codex CLI",
"type": "shell",
"command": "codex",
"problemMatcher": [],
"presentation": {
"reveal": "always",
"panel": "new"
}
}
]
}
Now you can launch Codex CLI from the Command Palette (Ctrl+Shift+P) by selecting **Tasks: Run Task → Codex CLI**.
Step 6: Custom Instructions for Project Context
Create a codex.md file in your project root to give Codex CLI persistent context about your codebase conventions:
# codex.md — Project instructions for Codex CLI
Stack
- Backend: Node.js with Express and TypeScript
- Database: PostgreSQL with Prisma ORM
- Testing: Jest with supertest
Conventions
- Use async/await, never raw Promises
- All API responses follow { success, data, error } format
Write unit tests for every new function
Pro Tips
- Switch models on the fly: Use
codex —model o4-minifor faster, cheaper responses on simpler tasks, orcodex —model o3for complex multi-file refactors. - Pipe output into Codex: Combine CLI tools with Codex for powerful workflows:
cat error.log | codex “analyze these errors and suggest fixes” - Use quiet mode in scripts: Pass
-qfor machine-readable output when integrating into shell scripts or CI pipelines. - Set spending limits: Configure usage limits in your OpenAI dashboard under Settings → Limits to avoid surprise charges during heavy sessions.
- Leverage git context: Codex CLI automatically reads your git history. Running it inside a git repository yields significantly better results than in a bare directory.
Troubleshooting
| Error | Cause | Solution |
|---|---|---|
OPENAI_API_KEY is not set | Environment variable missing or not exported | Run export OPENAI_API_KEY="YOUR_API_KEY" and add it to your shell profile |
Node.js version 22+ is required | Outdated Node.js version installed | Install Node.js 22+ using nvm install 22 or download from the official site |
401 Unauthorized | Invalid or expired API key | Generate a new API key from the OpenAI dashboard and update your environment variable |
429 Rate limit exceeded | Too many requests in a short period | Wait 60 seconds and retry; consider upgrading your API usage tier |
| Sandbox permission denied | Full auto mode cannot access files outside project directory | Ensure you run Codex CLI from within your project root directory |
Frequently Asked Questions
Is OpenAI Codex CLI free to use?
The Codex CLI tool itself is open-source and free. However, it requires an OpenAI API key, and API usage is billed based on the model and token volume. The o4-mini model is the most cost-effective option for everyday tasks, while o3 costs more but handles complex multi-step operations better. You can monitor and cap your spending through the OpenAI platform billing dashboard.
Can Codex CLI modify files on my system without permission?
It depends on the approval mode you select. In the default Suggest mode, Codex CLI will ask for your explicit confirmation before writing any file or executing any command. In Full Auto mode, it can write and execute freely but is confined to a sandbox — network access is disabled and file operations are restricted to your working directory and temp folders. You always control the level of autonomy.
How does Codex CLI differ from using ChatGPT for coding?
Codex CLI operates directly in your terminal with full access to your project files, directory structure, and git history. It can read your actual codebase for context, write files, and execute commands — all without leaving the command line. ChatGPT is a browser-based conversational interface where you manually copy and paste code snippets. Codex CLI is designed for developers who want AI assistance integrated into their existing terminal-based workflow.