Skip to main content

OpenAI Codex CLI Setup

This tutorial walks you through installing, configuring, and using OpenAI Codex CLI — the open-source, Rust-based AI coding agent from OpenAI.

Time Required: 20 minutes
Prerequisites: Terminal familiarity, OpenAI account

Overview

By the end of this tutorial, you will have:

  • Installed Codex CLI on your machine
  • Configured project-specific AI context
  • Run your first agentic coding session
  • Set up security and governance controls

Step 1: Installation (5 minutes)

Check Prerequisites

# Verify Node.js version (18+ required)
node --version

# Verify Git
git --version

# Verify you're on macOS 12+ or Linux
uname -a

Install Codex CLI

Option A: Via npm (Recommended)

npm install -g @openai/codex

Option B: Via install script

curl -fsSL https://raw.githubusercontent.com/openai/codex/main/install.sh | bash

Option C: Download binary

# macOS (Apple Silicon)
curl -L https://github.com/openai/codex/releases/latest/download/codex-darwin-arm64 -o codex
chmod +x codex
sudo mv codex /usr/local/bin/

Verify Installation

codex --version
# Output: codex version 1.x.x

codex --help
# Shows available commands

Step 2: Authentication (3 minutes)

Get API Key

  1. Visit platform.openai.com
  2. Navigate to API KeysCreate new secret key
  3. Copy the key (starts with sk-)

Authenticate Codex CLI

# Interactive login
codex auth login
# Paste your API key when prompted

# Or set environment variable
export OPENAI_API_KEY="sk-your-key-here"

# Verify authentication
codex auth status
# Output: Authenticated as user@example.com

Test Connection

codex test
# Output: ✓ Connected to OpenAI API
# ✓ Model access verified
# ✓ Ready to use

Step 3: Project Setup (5 minutes)

Create AGENTS.md

Navigate to your project and create context configuration:

cd /path/to/your-project

cat > AGENTS.md << 'EOF'
# Project Agent Configuration

## Role
Full-stack developer specializing in modern web applications.

## Technology Stack
- Frontend: React 18, TypeScript, Tailwind CSS
- Backend: Node.js, Express
- Database: PostgreSQL with Prisma ORM
- Testing: Jest, React Testing Library
- Build: Vite

## Code Style
- Use functional components with hooks
- Prefer async/await over callbacks
- Follow RESTful API conventions
- Use explicit TypeScript types (no `any`)
- Error handling: try/catch with specific error types

## File Organization

src/ components/ # Reusable UI components pages/ # Route-level components hooks/ # Custom React hooks utils/ # Helper functions types/ # TypeScript interfaces api/ # API client functions


## Constraints
- NEVER expose API keys or secrets in code
- ALWAYS validate user input
- Include error handling for all API calls
- Write tests for business logic
- Follow accessibility best practices (ARIA labels)

## Testing Requirements
- Unit tests for utils and hooks
- Integration tests for API calls
- Component tests for UI elements
- Minimum 70% coverage
EOF

Configure Exclusions

Create .codexignore to exclude sensitive files:

cat > .codexignore << 'EOF'
# Secrets and credentials
.env
.env.local
.env.production
*.pem
*.key
credentials.json

# Dependencies
node_modules/
vendor/

# Build outputs
dist/
build/
*.bundle.js

# Large files
*.mp4
*.mov
*.zip
*.tar.gz

# Generated files
coverage/
.nyc_output/
EOF

Configure Approval Levels

Create user configuration:

mkdir -p ~/.codex

cat > ~/.codex/config.json << 'EOF'
{
"approvalMode": "edit",
"allowedCommands": [
"npm test",
"npm run build",
"npm run lint",
"git status",
"git diff"
],
"blockedCommands": [
"npm publish",
"git push",
"git push --force",
"rm -rf",
"sudo"
],
"sandbox": {
"enabled": true,
"allowNetwork": false
},
"logging": {
"level": "info",
"file": "~/.codex/audit.log"
}
}
EOF

Step 4: Your First Session (5 minutes)

Start Interactive Session

codex

# You'll see:
# Codex CLI v1.x.x
# Loaded context from AGENTS.md
# Ready. Type your request or /help for commands.

Try a Simple Task

> Create a simple Button component with variants

Expected behavior:

  1. Codex reads your AGENTS.md for context
  2. Generates Button.tsx with TypeScript
  3. Shows you the proposed code
  4. Asks for approval to write file
  5. Applies changes on approval

Review and Approve

Codex wants to:
✓ Create src/components/Button.tsx
✓ Create src/components/Button.test.tsx

Approve? (y/n/diff)
> y

Files written successfully.

Check the Output

cat src/components/Button.tsx
# Review the generated code

Step 5: Advanced Usage (2 minutes)

Custom Slash Commands

Create reusable command:

mkdir -p ~/.codex/commands

cat > ~/.codex/commands/add-tests.md << 'EOF'
# Add Tests

Generate comprehensive tests for the current file.

## Steps
1. Identify the file being edited
2. Analyze the code structure
3. Generate unit tests covering:
- Happy path
- Edge cases
- Error scenarios
4. Use appropriate testing framework
5. Ensure tests are isolated and deterministic

## Output
Write tests to [filename].test.ts adjacent to source file.
EOF

Use it:

codex /add-tests

Scripting Codex

Create automated workflow:

cat > scripts/refactor.sh << 'EOF'
#!/bin/bash
set -e

echo "Starting refactoring with Codex..."

codex --approval edit \
--no-interactive \
"Refactor all utility functions to use async/await consistently"

echo "Running tests..."
npm test

echo "Refactoring complete!"
EOF

chmod +x scripts/refactor.sh

CI/CD Integration

# .github/workflows/codex-review.yml
name: AI Code Review

on:
pull_request:
paths:
- 'src/**'

jobs:
codex-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- name: Install Codex CLI
run: npm install -g @openai/codex

- name: Run Codex Review
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
codex --approval suggest \
--no-interactive \
"Review this PR for code quality, security, and best practices" \
> codex-review.md

- name: Post Review
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const review = fs.readFileSync('codex-review.md', 'utf8');
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: `## Codex Code Review\n\n${review}`
});

Security Best Practices

1. API Key Management

# Never commit API keys
echo ".codex/" >> .gitignore

# Use environment-specific keys
export OPENAI_API_KEY="$PROD_OPENAI_KEY" # Production
export OPENAI_API_KEY="$DEV_OPENAI_KEY" # Development

2. Sandboxing

# Enable strict sandbox
codex --sandbox strict "Untrusted task"

# Network isolation
codex --no-network "Local-only task"

3. Audit Logging

# Review audit trail
tail -f ~/.codex/audit.log

# Rotate logs
logrotate ~/.codex/logrotate.conf

Troubleshooting

Issue: "Authentication failed"

Solution:

# Verify API key
echo $OPENAI_API_KEY | head -c 10

# Re-authenticate
codex auth logout
codex auth login

# Check API access at platform.openai.com

Issue: "Command not found after installation"

Solution:

# Check npm global bin
npm bin -g

# Add to PATH
export PATH="$PATH:$(npm bin -g)"

# Or use npx
npx @openai/codex

Issue: "AGENTS.md not loading"

Solution:

# Verify file location
ls -la AGENTS.md

# Check for syntax errors
codex --debug "Test prompt"
# Review debug output for context loading

Issue: "Approvals too frequent"

Solution:

# Adjust approval mode
# In ~/.codex/config.json
{
"approvalMode": "full-auto", // For trusted workflows
"allowedCommands": ["..."]
}

Next Steps

Learn More

Practice Exercises

  1. Component Library: Use Codex to generate a set of form components
  2. API Integration: Implement a new API client with error handling
  3. Test Generation: Create comprehensive test suites for existing code
  4. Documentation: Generate API documentation from code comments

Join the Community

Summary

You've successfully:

  • ✅ Installed Codex CLI
  • ✅ Configured project context with AGENTS.md
  • ✅ Set up security controls
  • ✅ Run your first agentic session
  • ✅ Created custom commands

Codex CLI is now ready for production use under AEEF governance standards.