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

Grok Best Practices for Academic Research and Literature Discovery: Leveraging X/Twitter for Scholarly Intelligence Best Practices Grok Best Practices for Content Strategy: Identify Trending Topics Before They Peak and Create Content That Captures Demand Best Practices Grok Case Study: How a DTC Beauty Brand Used Real-Time Social Listening to Save Their Product Launch Case Study Grok Case Study: How a Pharma Company Tracked Patient Sentiment During a Drug Launch and Caught a Safety Signal 48 Hours Before the FDA Case Study Grok Case Study: How a Disaster Relief Nonprofit Used Real-Time X/Twitter Monitoring to Coordinate Emergency Response 3x Faster Case Study Grok Case Study: How a Political Campaign Used X/Twitter Sentiment Analysis to Reshape Messaging and Win a Swing District Case Study How to Use Grok for Competitive Intelligence: Track Product Launches, Pricing Changes, and Market Positioning in Real Time How-To Grok vs Perplexity vs ChatGPT Search for Real-Time Information: Which AI Search Tool Is Most Accurate in 2026? Comparison How to Use Grok for Crisis Communication Monitoring: Detect, Assess, and Respond to PR Emergencies in Real Time How-To How to Use Grok for Product Improvement: Extract Customer Feedback Signals from X/Twitter That Your Support Team Misses How-To How to Use Grok for Conference Live Monitoring: Extract Event Insights and Identify Networking Opportunities in Real Time How-To How to Use Grok for Influencer Marketing: Discover, Vet, and Track Influencer Partnerships Using Real X/Twitter Data How-To How to Use Grok for Job Market Analysis: Track Industry Hiring Trends, Layoff Signals, and Salary Discussions on X/Twitter How-To How to Use Grok for Investor Relations: Track Earnings Sentiment, Analyst Reactions, and Shareholder Concerns in Real Time How-To How to Use Grok for Recruitment and Talent Intelligence: Identifying Hiring Signals from X/Twitter Data How-To How to Use Grok for Startup Fundraising Intelligence: Track Investor Sentiment, VC Activity, and Funding Trends on X/Twitter How-To How to Use Grok for Regulatory Compliance Monitoring: Real-Time Policy Tracking Across Industries How-To NotebookLM Best Practices for Financial Analysts: Due Diligence, Investment Research & Risk Factor Analysis Across SEC Filings Best Practices NotebookLM Best Practices for Teachers: Build Curriculum-Aligned Lesson Plans, Study Guides, and Assessment Materials from Your Own Resources Best Practices NotebookLM Case Study: How an Insurance Company Built a Claims Processing Training System That Cut Errors by 35% Case Study