AI Tech News HubDaily Updates
Developer ToolsSeptember 23, 2026

Codex CLI in Practice: Let OpenAI Write Code for You Right in Your Terminal

A
AI 觀察家
Columnist · 3151 words
Codex CLI in Practice: Let OpenAI Write Code for You Right in Your Terminal

If you've recently seen people on Twitter or Hacker News posting terminal screenshots, claiming they're using Codex CLI to have AI write, modify, and explain code directly from the command line — it's genuinely not as complicated as you might think. This guide will get you up and running from scratch while steering you around a few common pitfalls.

By the end of this, you'll have: an AI coding assistant you can invoke from any project directory that's actually integrated into your development workflow — not another browser tab you open and never use.


What You'll Need

Clear the prerequisites first so you don't hit a wall halfway through:

  • Node.js 18+ (confirm with node -v)
  • OpenAI API Key (your account needs credits; Codex CLI uses models like codex-1 or o4-mini)
  • Basic terminal familiarity is enough — no special Python environment required
  • macOS / Linux works best; Windows with WSL2 is also viable

If you're still unsure whether to call the API directly or go with a RAG architecture, check out this comparison of Fine-tuning vs RAG first to clarify your requirements before continuing.


Step One: Install Codex CLI

npm install -g @openai/codex

After installation, run codex --version to confirm it outputs a version number. If you get command not found, the npm global bin path usually isn't in your PATH — check your ~/.bashrc or ~/.zshrc.

As of Q3 2026, Codex CLI is in the 0.1.x series and iterating rapidly. Running npm update -g @openai/codex occasionally to stay current is a good habit.


Step Two: Configure Your API Key

The simplest approach is setting an environment variable:

export OPENAI_API_KEY="sk-proj-..."

For it to persist, add that line to your shell's rc file, or create a .env in your project root (and remember to add it to .gitignore — you know why).

Codex CLI also supports entering your key interactively after running codex, but that approach requires re-entering it every new session, so it's only practical for one-off testing.


Step Three: Run Your First Command and Get a Feel for It

codex "help me explain this repo's structure"

Simply put: wherever you run this command, Codex CLI feeds that directory's file structure to the model and returns a description.

A few common usage patterns:

  • Explain existing code: codex "explain src/index.ts"
  • Generate new features: codex "add a rate limiter middleware using express"
  • Debug: paste the error message directly — codex "how do I fix this error: [error message]"
  • Write tests: codex "write Jest unit tests for utils/parser.ts"

Codex CLI runs in Suggest mode by default — it gives you recommendations without touching your files. To have it actually write changes, add --approval-mode auto-edit or manually confirm in interactive mode.


Step Four: Tune the Model and Configuration

Codex CLI defaults to codex-1, but you can switch with --model:

codex --model o4-mini "do a quick review of this SQL"

o4-mini is faster and cheaper, making it suitable for tasks that don't require deep reasoning. codex-1 is optimized specifically for coding tasks and noticeably outperforms on complex refactors or multi-file changes.

To control context scope, use --context to specify the paths you want fed to the model:

codex --context src/api/ "are there any obvious security issues in these route handlers"

This prevents the entire repo from being dumped in, saving tokens while keeping responses more focused. On that note, the pricing logic for the OpenAI API has a few gotchas worth reviewing before using Codex CLI heavily — better to understand it upfront than face a surprise bill.


Step Five: Actually Integrate Codex CLI Into Your Workflow

Knowing the commands isn't enough — the real value comes from making it part of your daily workflow. Here are a few integrations I've found genuinely useful:

Git pre-commit hook: Automatically run codex "review this diff for obvious bugs" before each commit as a final sanity check.

Makefile or package.json scripts:

"scripts": {
  "ai:review": "codex 'review the latest changes in src/'",
  "ai:test": "codex 'generate missing tests for changed files'"
}

VS Code terminal shortcuts: Bind frequently used codex commands to tasks so you're not typing them out manually each time.

If your project uses an AI agent architecture, it's worth looking at how Claude Code AI Agent works alongside this. The two tools take different approaches, but they complement each other well.


Common Errors and How to Avoid Them

"Rate limit exceeded": Codex CLI's conversational back-to-back calls hit rate limits easily, especially on the free tier. Set "delayBetweenRequests": 1000 (in milliseconds) in .codex/config.json to mitigate this.

Context too large, response quality degrades: Running Codex CLI from the root of a monorepo with hundreds of files tends to confuse the model. The fix is using --context to narrow the scope, or creating a .codexignore (same format as .gitignore) to exclude node_modules, build artifacts, and other noise.

Generated code doesn't work when run: Always review in Suggest mode first. Don't enable auto-edit on your first run — especially for tasks involving database operations or infrastructure changes.

Can't set environment variables in Windows PowerShell: Switching to WSL2 is the cleanest solution, or use the cross-env package as a wrapper.


Advanced: Lock In Context With .codex/instructions.md

Not everyone knows about this feature: create a .codex/instructions.md in your project root, and write in background information about the repo, your coding style, and areas that are off-limits. Codex CLI automatically includes this file's contents in the system prompt on every run.

For example:

# Project Overview
This is a NestJS + TypeScript backend service deployed on AWS Lambda.
- All API responses must use the `ApiResponse<T>` wrapper format
- Do not modify anything under src/legacy/
- Testing framework is Jest — do not switch to Vitest

This way the model won't keep losing track of your stack, or suddenly suggest a Python solution.


After Setup: Confirming You're Actually Integrated

A few checkpoints:

  • codex --version outputs a version number
  • codex "hello" returns a normal response (confirms the API key is configured correctly)
  • You've run at least one real task in your actual project directory (not an empty test folder)
  • .codexignore excludes node_modules and build directories
  • OPENAI_API_KEY is stored somewhere protected by .gitignore and not hardcoded in your source

Directions worth exploring next: setting up automated code review in your CI pipeline, or looking into Codex CLI's --format json output mode to pipe its responses into your own toolchain for further processing. This tool is evolving fast — significant API changes are likely before the end of 2026, so subscribing to the OpenAI changelog is a worthwhile habit.

Frequently Asked Questions

What's the difference between Codex CLI and just asking ChatGPT?

The biggest difference is that Codex CLI runs directly in your terminal environment. It can automatically read the file structure and code in your current directory as context — no manual copy-pasting required. It can also write directly to files, making it more like a coding agent embedded in your development environment rather than a chat window.

How is Codex CLI billed? Can it get expensive?

Billing runs through your OpenAI account's API usage and is charged based on the model you select. Running general code reviews or explanation tasks with o4-mini is very inexpensive. However, if you enable auto-edit mode and it makes consecutive changes across multiple files, token consumption from accumulated context climbs noticeably. Setting up an API usage alert is recommended to avoid bill surprises.

Can Codex CLI run on Windows?

Yes, but WSL2 (Windows Subsystem for Linux) is strongly recommended over running it natively in PowerShell or CMD. Environment variable configuration is more cumbersome in the native Windows environment, and some shell integration features behave inconsistently under PowerShell. WSL2 + Ubuntu is currently the least problematic path on Windows.

Is .codexignore necessary?

Strictly speaking, no — but it's strongly recommended. Without a .codexignore, Codex CLI running in a directory with node_modules will attempt to include those tens of thousands of files in the context. This slows responses, burns through tokens, and scatters the model's focus. The format is identical to .gitignore, so you can simply copy yours over.

What's the difference between Codex CLI and GitHub Copilot? Which should I use?

GitHub Copilot is primarily an in-editor inline completion tool. Codex CLI is a command-line task execution tool. The former suits a "type-and-autocomplete" workflow; the latter suits a "assign a task and let it run" approach — things like generating tests, refactoring a module, or automating code review. They serve different purposes and aren't mutually exclusive; many engineers use both.

Share

Related articles