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.com and 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.

ModeFlagBehaviorBest For
**Suggest**--suggestReads files freely; requires approval for every write and commandLearning, exploring unfamiliar codebases
**Auto Edit**--auto-editApplies file edits automatically; requires approval for commandsDay-to-day development with safety guardrails
**Full Auto**--full-autoRuns commands and edits files without approval inside a sandboxBatch 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_KEY environment 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-mini for faster, cheaper responses on simpler tasks, or codex —model o3 for 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 -q for 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

ErrorCauseSolution
OPENAI_API_KEY is not setEnvironment variable missing or not exportedRun export OPENAI_API_KEY="YOUR_API_KEY" and add it to your shell profile
Node.js version 22+ is requiredOutdated Node.js version installedInstall Node.js 22+ using nvm install 22 or download from the official site
401 UnauthorizedInvalid or expired API keyGenerate a new API key from the OpenAI dashboard and update your environment variable
429 Rate limit exceededToo many requests in a short periodWait 60 seconds and retry; consider upgrading your API usage tier
Sandbox permission deniedFull auto mode cannot access files outside project directoryEnsure 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.

Explore More Tools

Antigravity AI Content Pipeline Automation Guide: Google Docs to WordPress Publishing Workflow Guide Bolt.new Case Study: Marketing Agency Built 5 Client Dashboards in One Day Case Study Bolt.new Best Practices: Rapid Full-Stack App Generation from Natural Language Prompts Best Practices ChatGPT Advanced Data Analysis (Code Interpreter) Complete Guide: Upload, Analyze, Visualize Guide ChatGPT Custom GPTs Advanced Guide: Actions, API Integration, and Knowledge Base Configuration Guide ChatGPT Voice Mode Guide: Build Voice-First Customer Service and Internal Workflows Guide Claude API Production Chatbot Guide: System Prompt Architecture for Reliable AI Assistants Guide Claude Artifacts Best Practices: Create Interactive Dashboards, Documents, and Code Previews Best Practices Claude Code Hooks Guide: Automate Custom Workflows with Pre and Post Execution Hooks Guide Claude MCP Server Setup Guide: Build Custom Tool Integrations for Claude Code and Claude Desktop Guide Cursor Composer Complete Guide: Multi-File Editing, Inline Diffs, and Agent Mode Guide Cursor Case Study: Solo Founder Built a Next.js SaaS MVP in 2 Weeks with AI-Assisted Development Case Study Cursor Rules Advanced Guide: Project-Specific AI Configuration and Team Coding Standards Guide Devin AI Team Workflow Integration Best Practices: Slack, GitHub, and Code Review Automation Best Practices Devin Case Study: Automated Dependency Upgrade Across 500-Package Python Monorepo Case Study ElevenLabs Case Study: EdTech Startup Localized 200 Course Hours to 8 Languages in 6 Weeks Case Study ElevenLabs Multilingual Dubbing Guide: Automated Video Localization Workflow for Global Content Guide ElevenLabs Voice Design Complete Guide: Create Consistent Character Voices for Games, Podcasts, and Apps Guide Gemini 2.5 Pro vs Claude Sonnet 4 vs GPT-4o: AI Code Generation Comparison 2026 Comparison Gemini API Multimodal Developer Guide: Image, Video, and Document Analysis with Code Examples Guide