Chapter 1

What is Codex?

Understanding OpenAI's terminal-based coding agent and how it fits into the AI developer tools landscape.

🤖 OpenAI's CLI Coding Agent
Codex CLI is OpenAI's open-source command-line tool that acts as an AI coding assistant right in your terminal. Think of it as having a senior developer sitting next to you who can read your code, write new code, fix bugs, run commands, and explain what things do -- all from a simple text prompt.

It is powered by OpenAI's models (like o4-mini and o3) and works directly with your local files and development environment. You describe what you want in plain English, and Codex figures out how to do it.
🛠 What Can It Do?
  • Write code -- Generate entire scripts, functions, or components from a description
  • Fix bugs -- Point it at a broken file and let it diagnose and repair issues
  • Refactor -- Clean up messy code, rename variables, restructure logic
  • Explain code -- Ask it to walk you through what a function or file does
  • Run commands -- Execute shell commands as part of its workflow
  • Work with your codebase -- It reads your project files for context before acting
Codex vs. Claude Code
Both Codex and Claude Code are terminal-based AI coding tools, but they have different strengths and designs. Here is how they compare:
Feature Codex CLI Claude Code
Provider OpenAI Anthropic
Models o4-mini, o3 Claude Sonnet, Opus
Open Source Yes No
Sandboxing Built-in (network disabled by default) Permission-based approvals
Approval Modes suggest / auto-edit / full-auto Interactive approval per action
Install npm install -g @openai/codex npm install -g @anthropic-ai/claude-code
Best For Quick tasks, sandboxed automation Complex multi-file refactors, deep reasoning
💡
Both tools are great and worth knowing. Many developers use both depending on the task. Learning one makes it easier to pick up the other since the workflow is similar: describe what you want, review the changes, approve or iterate.

Where You Can Use It

💻
CLI
In any terminal via codex
🖥
Desktop App
Native macOS app with visual interface
🌐
ChatGPT
Use Codex inside ChatGPT Pro/Team/Enterprise
🧩
GitHub Integration
Codex as a GitHub agent for PRs and issues
📦
Open Source
Fork and customize on GitHub
Download Codex CLI → Download Codex Desktop →
Chapter 2

Getting Set Up

From zero to running Codex in your terminal. Follow each step in order.

1
Check Prerequisites
Codex requires Node.js version 22 or later. Check if you have it installed:
Terminal
$ node --version
Expected output
v22.x.x (or higher)
This checks which version of Node.js is installed on your machine. Codex needs Node 22+ because it uses modern JavaScript features. If you do not have Node installed or your version is too old, visit the main guide for installation instructions or go to nodejs.org.
2
Install Codex CLI
Install Codex globally using npm. This makes the codex command available everywhere in your terminal.
Terminal
$ npm install -g @openai/codex
Expected output
added 1 package in 3s + @openai/codex@latest
npm install -g installs a package globally, meaning you can run codex from any directory in your terminal. The @openai/codex is the official package name on the npm registry.
3
Get an OpenAI API Key
Codex needs an API key to communicate with OpenAI's models. You will need to:

1. Go to platform.openai.com/api-keys
2. Sign in or create an account
3. Click "Create new secret key"
4. Copy the key (it starts with sk-)
⚠️
Keep your API key secret. Never commit it to git, share it publicly, or paste it in code. Treat it like a password. Anyone with your key can make API calls on your account.
4
Set Your API Key
Export the key as an environment variable so Codex can find it:
Terminal
$ export OPENAI_API_KEY="your-key-here"
export sets an environment variable in your current terminal session. This makes the key available to any program you run, including Codex. Replace your-key-here with your actual API key from step 3.

Note: This only lasts for the current terminal session. When you close the terminal, the variable is gone. The next step shows how to make it permanent.
5
Make It Permanent
Add the API key to your shell profile so it loads automatically every time you open a terminal:
Terminal
$ echo 'export OPENAI_API_KEY="your-key-here"' >> ~/.zshrc
Terminal
$ source ~/.zshrc
The >> operator appends text to the end of a file. ~/.zshrc is your Zsh shell configuration file that runs every time you open a new terminal.

source ~/.zshrc reloads the configuration file so the change takes effect immediately without opening a new terminal window.

Using Bash instead of Zsh? Replace ~/.zshrc with ~/.bashrc.
6
Verify It Works
Run codex to make sure everything is set up correctly:
Terminal
$ codex
Expected output
OpenAI Codex v0.1 ? What can I help you with? >
If you see the Codex interactive prompt, everything is working. Codex found your API key and is ready to accept commands. You can type a prompt or press Ctrl+C to exit.

If you see an error about API keys: Double-check that your OPENAI_API_KEY environment variable is set correctly by running echo $OPENAI_API_KEY.
7
Authentication Options
There are multiple ways to authenticate with Codex:

Environment variable (recommended) -- Set OPENAI_API_KEY as shown above.

Login command -- Run codex --login for browser-based authentication via ChatGPT. This stores credentials locally and does not require managing API keys manually.

Project-level config -- Create a codex.json or codex.yaml file in your project root to configure model, approval mode, and other settings per-project.
📚
If you have a ChatGPT Plus or Pro subscription, you can use codex --login to authenticate without needing a separate API key or billing setup.
Chapter 3

How to Use Codex

From basic prompts to advanced workflows. Master the different ways to interact with Codex.

⚡ Basic Usage

💬 One-Shot Prompts
The simplest way to use Codex: pass your request as a quoted string after the codex command.
Terminal
$ codex "Create a Python script that fetches weather data from an API"
Codex response
Codex I'll create a Python script that fetches weather data. Let me write that for you... + Created weather.py - Uses requests library - Fetches from OpenWeatherMap API - Includes error handling - Formats output nicely ? Apply this change? (y/n)

🗨 Interactive Mode

🔁 Multi-Turn Conversations
Just run codex with no arguments to enter interactive mode. This lets you have a back-and-forth conversation, refine your requests, and build on previous responses.
Terminal -- Interactive Mode
$ codex
Interactive session
OpenAI Codex v0.1 ? What can I help you with? > Fix the bug in server.js Codex I'll look at server.js to find and fix the bug... Reading server.js... I found the issue: the error handler middleware is defined before the routes, so it never catches route errors. - app.use(errorHandler); // line 12 (before routes) app.get('/api/users', ...) app.post('/api/users', ...) + app.use(errorHandler); // moved to line 45 (after routes) ? Apply this change? (y/n)

📁 Working with Files

🔎 Codex Reads Your Project
Codex automatically reads relevant files in your current directory to understand context. Just cd into your project folder before running Codex, and it will be aware of your codebase.

For best results:
  • Run Codex from your project root so it can see all relevant files
  • Be specific about which files to work with in your prompt
  • Use a AGENTS.md file to give Codex persistent context about your project structure, conventions, and preferences
Terminal
$ codex "Add tests for the utils module"
Codex response
Codex I'll read the utils module and create tests for it. Reading src/utils.js... Found 4 exported functions: formatDate, slugify, debounce, deepMerge + Created tests/utils.test.js - 12 test cases covering all 4 functions - Edge cases for empty inputs - Uses Jest framework (detected from package.json) ? Apply this change? (y/n)

🔒 Approval Modes

Codex has three modes that control how much autonomy it has. Choose based on your comfort level and the task at hand.
📛
suggest
Default mode. Codex shows proposed changes and asks for approval before applying anything. Safest option.
✏️
auto-edit
Codex automatically applies file changes but still asks before running shell commands. Good balance of speed and safety.
🚀
full-auto
Codex applies changes and runs commands without asking. Fast but use with caution. Best in sandboxed environments.
Terminal -- Using approval modes
$ codex --approval-mode full-auto "Set up a basic Express server"
⚠️
Be careful with full-auto mode. Codex runs in a sandboxed environment with network disabled by default, but it can still modify and delete files in your project. Always use version control (git) so you can undo changes.

🏷️ Common Flags & Options

--model <model>
Choose which OpenAI model to use. Default is o4-mini. Use o3 for harder tasks.
--approval-mode <mode>
Set to suggest, auto-edit, or full-auto.
--quiet
Reduce output verbosity. Useful in scripts or CI pipelines.
--login
Authenticate via browser using your ChatGPT account.
--help
Show all available commands and options.
--version
Display the currently installed version of Codex CLI.

🔬 More Example Prompts

Terminal -- Explain code
$ codex "Explain what the handleAuth function does in src/auth.js"
Codex response
Codex Here's what handleAuth() does: 1. Extracts the JWT token from the Authorization header 2. Verifies the token using the secret from env vars 3. Decodes the user ID and looks up the user in the database 4. Attaches the user object to req.user 5. Calls next() if valid, or returns a 401 if not It's an Express middleware that protects routes requiring authentication.
Terminal -- Refactor
$ codex "Refactor the database queries in models/ to use async/await instead of callbacks"
Terminal -- Using a specific model
$ codex --model o3 "Optimize the sorting algorithm in utils/sort.js for large datasets"
💡
Pro tip: The more specific your prompt, the better the results. Instead of "fix the bug," try "fix the null pointer error when users array is empty in getUserById on line 42 of users.js."
Chapter 4

Codex Skills

Skills are reusable workflow packages that extend Codex with specialized capabilities. Think of them as plugins that teach Codex new tricks.

What Are Skills?

Skills package instructions, resources, and optional scripts into a reusable bundle. When you invoke a skill, Codex follows the workflow reliably every time — no need to re-explain complex processes.

  • Perform specialized tasks consistently
  • Encapsulate multi-step workflows into a single command
  • Share and reuse across projects
  • Can be invoked explicitly ($skill-name) or automatically matched to your prompt

Enable & Install Skills

Enable the skills feature, then use the built-in installer:

Terminal
$ codex --enable skills

Install skills from the catalog inside a Codex session:

Inside Codex
> $skill-installer
💡
After installing a skill, restart Codex so it can discover the new skill.

Where Skills Live

Codex discovers skills from multiple locations (in order of precedence):

Repository .agents/skills/ — project-specific, shared with your team User ~/.codex/skills/ — your personal skills Admin /etc/codex/skills/ — system-wide System Built-in skills bundled with Codex

Anatomy of a Skill

Every skill is a folder with a SKILL.md file and optional extras:

Skill Structure
my-skill/
├── SKILL.md              # required — name, description, instructions
├── agents/
│   └── openai.yaml       # optional — UI, invocation policy
├── scripts/              # optional — helper scripts
├── references/           # optional — reference docs
└── assets/               # optional — images, templates

⭐ Recommended Skills

🔧 Built-in

skill-creator

Create new skills interactively. Generates the folder structure and SKILL.md for you. Type $skill-creator to start.

📦 Built-in

skill-installer

Browse and install skills from the official catalog. Handles download, placement, and configuration automatically.

📋 Curated

create-plan

Generates structured implementation plans before writing code. Great for breaking down complex features into steps.

🐦 Curated

gh-address-comments

Reads GitHub PR review comments and generates fixes automatically. Saves time on code review cycles.

🎨 Community

Design Skills

50+ community design skills for generating UI components, layouts, and styling. Install via the catalog or build your own.

📄 Community

Document Processing

Skills for working with spreadsheets, DOCX files, and PDFs. Transform, analyze, and generate documents from prompts.

🚀
Pro tip: Build project-specific skills and commit them to .agents/skills/ in your repo. Your whole team gets the same Codex superpowers, and the skills evolve with the codebase.
Chapter 5
Chapter 4

Fun Projects to Try

Put Codex to work on real projects. Each card includes the exact prompt to get started.

Beginner
CLI Todo App
Build a command-line todo list manager with add, remove, complete, and list functionality. Data persists to a local JSON file.
codex "Build a Node.js CLI todo app with add, remove, list, and complete commands. Store data in a local JSON file."
🕷 Beginner
Web Scraper
Create a Python web scraper that extracts headlines from a news site and saves them to a CSV file. Learn about HTTP requests and HTML parsing.
codex "Create a Python web scraper using BeautifulSoup that scrapes top headlines from Hacker News and saves them to a CSV file."
🌐 Intermediate
REST API
Build a complete REST API with Express.js including CRUD operations, input validation, error handling, and an in-memory data store.
codex "Build a REST API with Express.js for a bookstore. Include CRUD endpoints, input validation, error handling, and organize with routes and controllers."
🤖 Intermediate
Discord Bot
Create a Discord bot that responds to commands, moderates chat, and can play trivia games with server members.
codex "Build a Discord bot using discord.js with slash commands for /hello, /trivia, and /poll. Include a help command and error handling."
💼 Beginner
Personal Portfolio Site
Generate a clean, responsive personal portfolio website with HTML, CSS, and vanilla JavaScript. Includes sections for about, projects, and contact.
codex "Create a responsive personal portfolio website with a dark theme. Include hero, about, projects grid, and contact sections. Use only HTML, CSS, and vanilla JS."
🔗 Intermediate
URL Shortener
Build a URL shortening service with a simple web interface. Generates short codes, tracks click counts, and redirects visitors.
codex "Build a URL shortener with Express.js. Include a web form to submit URLs, generate short codes, track clicks, and redirect. Use SQLite for storage."
📝 Beginner
Markdown Blog Generator
Create a static site generator that converts Markdown files into a beautiful HTML blog with an index page, tags, and syntax highlighting.
codex "Build a Node.js static blog generator that converts Markdown files in a posts/ folder into styled HTML pages with an index, tags, and code syntax highlighting."
📈 Intermediate
Data Visualization Dashboard
Build an interactive dashboard that reads a CSV file and creates charts and graphs. Includes filtering, sorting, and responsive layout.
codex "Create an interactive data dashboard using Chart.js that reads a CSV file, displays bar/line/pie charts, and includes date range filtering. Use vanilla HTML/CSS/JS."
🎮 Beginner
Terminal Snake Game
Build the classic snake game that runs in the terminal. Use arrow keys to move, eat food to grow, and avoid hitting walls or yourself.
codex "Build a terminal-based snake game in Python using curses. Include score tracking, increasing speed, and game over screen with replay option."
☁️ Beginner
Weather CLI Tool
Create a command-line weather app that shows current conditions, forecasts, and fun ASCII art for different weather types.
codex "Build a CLI weather tool in Python that takes a city name, fetches weather from wttr.in, and displays temperature, conditions, and a 3-day forecast."
🌟
Getting better results: After Codex generates a project, use follow-up prompts to iterate. Try "add error handling," "make it look better," "add a README," or "write tests for this." Building in steps often produces better results than one giant prompt.