Codex CLI JavaScript & TypeScript Tutorial (2026) — AI-Powered Frontend & Node.js Development
The JavaScript/TypeScript ecosystem is vast — React, Next.js, Vue, Node.js, Bun, Fastify... Codex CLI navigates this ecosystem fluently. With the right AGENTS.md configuration it generates type-correct TSX components, full API routes, Vitest test suites, and auto-fixes TypeScript compilation errors from your terminal.
1. AGENTS.md — JavaScript/TypeScript Project Configuration
Place an AGENTS.md file in your project root so Codex CLI understands your tech stack, coding conventions, and the commands it is allowed to run. Below is a complete example for a Next.js 15 + TypeScript project:
# Next.js 15 Project — AGENTS.md
## Tech Stack
- Next.js 15 (App Router)
- TypeScript 5.5 (strict: true)
- React 19
- Tailwind CSS 3.4
- Drizzle ORM + PostgreSQL
- Vitest + Testing Library
## Code Conventions
- All components use named exports (no default export, except page.tsx)
- Server Components by default; add 'use client' only when interactivity is needed
- Path alias: @ points to src/
- Component filenames: PascalCase.tsx; utility functions: camelCase.ts
- No any types; no @ts-ignore comments
## Allowed Commands
- npm run dev/build/test/lint
- npx tsc --noEmit
- npx drizzle-kit generate/push/studio
## Prohibited Actions
- Do not modify next.config.ts (unless explicitly requested)
- Do not modify tailwind.config.ts
- Server Actions must have the 'use server' directive
2. Automatically Fix TypeScript Errors
One of Codex CLI's most powerful capabilities is piping compiler output directly into prompts and applying targeted fixes. Here are four common TypeScript fix scenarios:
2.1 Batch-Fix All tsc Errors
$ npx tsc --noEmit 2>&1 | codex "Fix all TypeScript compilation errors above:
- No any types
- No as casts (as unknown as T is a bypass and is also forbidden)
- Prefer optional chaining over non-null assertions (!.)
- Fix file by file without changing business logic"
2.2 Add TypeScript Types to a JavaScript File
$ codex "Convert src/utils/api.js to TypeScript:
- Infer types for all function parameters and return values
- Use generics for API responses: ApiResponse<T>
- Use Error subclasses for error types (no any)
- Save as src/utils/api.ts and update all imports"
2.3 Define Complex Utility Types
$ codex "Add the following types to src/types/api.ts:
- PaginatedResponse<T>: generic paginated response (data, total, page, pageSize)
- ApiError: error type with code, message, details fields
- SortableField<T>: utility type that extracts sortable field names from T's keys
- DeepPartial<T>: recursively optional type"
2.4 Fix React Component Types
$ codex "Fix the type errors in src/components/DataTable.tsx:
- Generic parameter T has no constraint — add extends object
- column.render function type is incorrect
- onSort prop type is inconsistent with how it is used
Keep the component API unchanged; only fix types"
3. Auto-Generate Jest/Vitest Tests
Codex CLI can analyze existing components or utility functions and generate ready-to-run test files with high coverage. The following five scenarios cover the most common testing needs:
3.1 Component Tests (React Testing Library)
$ codex "Generate Vitest + Testing Library tests for src/components/LoginForm.tsx:
- Render test (no errors thrown)
- Verify: error message shown when email format is invalid
- Verify: error message shown when password is fewer than 8 characters
- Verify: onSubmit prop is called on form submission
- Verify: submit button is disabled in loading state
Use vi.fn() to mock prop functions"
3.2 API Route Tests (Next.js)
$ codex "Generate tests for app/api/users/route.ts:
Simulate requests with NextRequest and test:
- GET /api/users (returns paginated user list)
- POST /api/users (create user, including validation failure case)
- 401 Unauthorized (missing token)
- 422 Validation failure
Mock Drizzle database calls"
3.3 Hook Tests
$ codex "Generate tests for src/hooks/useDebounce.ts:
- Returns initial value immediately
- Updates after delay milliseconds (use vi.useFakeTimers)
- Rapid consecutive calls trigger only one update
- Cancels pending update on cleanup"
3.4 Utility Function Tests
$ codex "Generate parameterized tests (test.each) for every exported function in src/utils/formatters.ts covering normal inputs, edge values, and null/undefined inputs"
3.5 End-to-End Tests (Playwright)
$ codex "Generate Playwright E2E tests for the shopping cart flow:
1. Search for a product
2. Add to cart
3. Update quantity
4. Enter shipping information
5. Confirm the order
Verify page state at each step and take a screenshot on failure"
4. React Component Generation
Codex CLI generates complete, production-ready React components from natural-language descriptions — including TypeScript types, styling, and accessibility. Here are five representative scenarios:
4.1 Full Form Component
$ codex "Create a UserProfileForm component (src/components/UserProfileForm.tsx):
- Fields: name, email, avatar upload, bio (textarea)
- Form validation with react-hook-form + zod
- Submit via Server Action (no fetch/axios)
- Show loading state during submission
- Toast notification on success/failure
- Tailwind CSS styling, mobile-responsive"
4.2 Generic Data Table Component
$ codex "Create a generic DataTable<T> component supporting:
- Column definitions: columns: Column<T>[] (with custom render function)
- Pagination (controlled component)
- Column sorting
- Row selection (checkbox)
- Loading skeleton
- Empty state
Full TypeScript generics, Tailwind CSS"
4.3 Infinite Scroll List
$ codex "Implement an InfiniteScrollList component:
- Detect scroll-to-bottom with Intersection Observer
- Call the passed loadMore function to fetch more items
- Loading indicator
- Error retry
- Optimize rendering with React.memo
Manage state with useReducer; no external state management library"
4.4 Advanced Custom Hook
$ codex "Create a useLocalStorage<T> hook:
- Read initial value from localStorage, fall back to defaultValue
- Automatic JSON serialization/deserialization
- Listen to storage events for cross-tab synchronization
- SSR-safe (graceful fallback when window is unavailable)
- Full TypeScript generics"
4.5 Server Component + Client Component Split
$ codex "Migrate pages/blog/[slug].tsx to Next.js App Router:
- Convert data fetching to an async Server Component
- Implement SSG with generateStaticParams
- Extract interactive parts (comments, likes) as Client Components
- Preserve SEO and Open Graph meta tags
- Update import paths to use the @ alias"
5. Node.js / Express / Fastify Back-End
Codex CLI is equally strong on the server side. It generates robust Node.js middleware, framework plugins, and real-time communication code with complete TypeScript types:
5.1 Express Middleware
$ codex "Create the following middleware for the Express app (src/middleware/):
- auth.ts: validate JWT and attach user to req.user
- rateLimit.ts: Redis-backed sliding window rate limiter (100 req/min/IP)
- errorHandler.ts: unified error response format, distinguish 4xx from 5xx
- requestLogger.ts: structured logging (pino) — method, path, duration, status code"
5.2 Fastify Plugin
$ codex "Create Fastify plugin plugins/database.ts:
- Register @fastify/postgres (connection pool)
- Provide a health check route at /health/db
- Disconnect gracefully on server shutdown
- TypeScript type declarations (type augmentation for fastify.pg)"
5.3 WebSocket Real-Time Chat
$ codex "Implement a real-time chat back end using the ws library for Node.js:
- Connection authentication (JWT in query string)
- Manage online users with a Map
- Support channels (multi-room)
- Broadcast and direct messages
- Disconnection cleanup and reconnection handling
- Complete TypeScript types"
5.4 Migrate to Bun
$ codex "Rewrite src/server.ts from Node.js http module to Bun.serve API:
- Keep existing routing logic intact
- Leverage Bun's native .env support
- Add Bun.file for high-performance static file serving
- Use Bun's native WebSocket API"
6. Next.js Deep Dive
The Next.js App Router introduced a fundamentally new programming model. Codex CLI understands the latest conventions and generates data fetching, Server Actions, and performance optimizations that follow current best practices:
6.1 App Router Data Fetching
$ codex "Implement data fetching in app/products/page.tsx:
- Fetch data directly with fetch (no useEffect)
- revalidate: 3600 (hourly revalidation)
- generateMetadata function (dynamic title and og:image)
- loading.tsx skeleton
- error.tsx error boundary
- Complete TypeScript types"
6.2 Server Actions
$ codex "Create Server Actions for the blog CMS (app/actions/posts.ts):
- createPost(formData: FormData): validate, save to DB, revalidatePath
- updatePost(id: string, data: Partial<Post>)
- deletePost(id: string): soft delete
- publishPost(id: string): toggle published state
Each action returns a unified shape: { success: boolean; error?: string }"
6.3 Route Handlers + Middleware
$ codex "Create Next.js Route Handler app/api/upload/route.ts:
- POST accepts image uploads (multipart/form-data)
- Validate file type (jpg/png/webp only) and size (< 5 MB)
- Upload to Cloudflare R2
- Return the public URL
- Protect this route in middleware.ts (login required)"
6.4 Performance Optimization
$ codex "Analyze performance issues in app/dashboard/page.tsx and fix them:
- Identify data fetches that can run in parallel (convert to Promise.all)
- Identify sections suitable for streaming (wrap with Suspense)
- Find unnecessary 'use client' components (convert back to Server Components)
- Optimize image components (next/image priority and sizes props)"
7. JS/TS CI/CD with GitHub Actions
Integrate Codex CLI into your CI/CD pipeline to get automatic AI code review on every pull request alongside TypeScript type checking and test runs:
# .github/workflows/js-ci.yml
name: JavaScript/TypeScript CI
on: [push, pull_request]
jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'pnpm'
- run: pnpm install --frozen-lockfile
- name: TypeScript Check
run: pnpm tsc --noEmit
- name: Lint
run: pnpm eslint src/ --max-warnings 0
- name: Unit Tests
run: pnpm vitest run --coverage --reporter=verbose
- name: Build
run: pnpm build
- name: Codex AI Review (on PR)
if: github.event_name == 'pull_request'
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
run: |
npm install -g @openai/codex
DIFF=$(git diff origin/main..HEAD -- '*.ts' '*.tsx')
echo "$DIFF" | codex exec "Review TypeScript/React code changes for: type safety issues, React anti-patterns (missing deps in useEffect, key prop issues), accessibility problems, and performance concerns."
8. JS/TS Quick-Reference Prompt Cheatsheet
Copy-paste ready prompt templates for high-frequency scenarios:
| Scenario | Prompt | Notes |
|---|---|---|
| CommonJS → ESM migration | Convert all require() calls in src/ to import and module.exports to export |
Update package.json type: "module" |
| Generate Zod schema | Generate a Zod schema and infer type for the TypeScript type UserProfile |
Usable directly for form validation |
| Reduce bundle size | Analyze the next build bundle analyzer output, identify the largest dependencies and suggest alternatives |
Run ANALYZE=true next build first |
| Migrate to Bun | Migrate package.json scripts and Node.js-specific APIs to Bun-compatible equivalents |
Check node: prefix imports |
| Generate API client | Generate a TypeScript API client from the OpenAPI spec (openapi.yaml) |
Use openapi-typescript |
| Fix ESLint errors | Run pnpm eslint src/ --fix, then manually fix rules that --fix cannot auto-resolve |
Preserve eslint-disable comments |
9. Frequently Asked Questions
Does Codex CLI support TypeScript?
Fully. Codex CLI reads and edits .ts/.tsx files, understands TypeScript's type system, and generates type-correct code. Specify your tsconfig.json requirements in AGENTS.md and Codex will respect strict mode (strict: true) constraints.
How do I make Codex CLI generate React components?
Describe the component naturally: "Create a UserCard component that accepts a user: User prop, shows avatar, name, email, has edit and delete buttons, styled with Tailwind CSS, exported as a named export." Codex generates a complete TSX file with all type definitions included.
Can Codex CLI fix TypeScript compilation errors?
Yes. Pipe the compiler output directly into Codex and it will apply targeted fixes:
$ npx tsc --noEmit 2>&1 | codex "Fix all TypeScript compilation errors. No any types or as casts allowed."
Does Codex CLI support Next.js App Router?
Yes. Codex understands App Router conventions — Server Components, Client Components, Route Handlers, Middleware, and Server Actions. Specify your Next.js version and whether you are using App Router in AGENTS.md and Codex will generate spec-compliant code automatically.