Claude Code for JavaScript & TypeScript Developers

Complete Guide Updated May 2026 35+ copy-paste prompts Node.js · React · Next.js · Vitest

Contents

  1. Project Setup & CLAUDE.md
  2. TypeScript Workflows
  3. Framework Patterns (Node.js · React · Next.js · Vue)
  4. Testing with Jest / Vitest / RTL
  5. Tooling: ESLint, Prettier, Bundlers
  6. Copy-Paste Prompt Library
  7. FAQ

Project Setup & CLAUDE.md

Claude Code needs to know your package manager, scripts, and project structure before it can work effectively. A good CLAUDE.md eliminates 5–10 minutes of per-session context-setting and prevents common mistakes (using npm in a pnpm workspace, running the wrong test command).

CLAUDE.md Template for JS/TS Projects

# Project Setup Node version: 22.x (managed via .nvmrc — run `nvm use` first) Package manager: pnpm 9 — NEVER use npm or yarn in this project Install: pnpm install # Core Commands Dev server: pnpm dev Build: pnpm build Type check: pnpm tsc --noEmit Lint: pnpm eslint . --fix --max-warnings 0 Format: pnpm prettier --write . Test: pnpm vitest run --reporter=verbose Test (watch): pnpm vitest E2E: pnpm playwright test # Structure src/ — all source (App Router: app/, Pages Router: pages/) src/lib/ — shared utilities and API clients src/types/ — shared TypeScript type definitions tests/ — unit + integration tests (co-locate with src/ when possible) # Important Rules - All new code in TypeScript — no .js files in src/ - Use named exports only (no default exports except page components) - Error handling: throw typed errors, never swallow - DO NOT modify: dist/, .next/, node_modules/ - DO NOT commit .env files # Environment Copy .env.example to .env.local and fill in values before running
First-session prompt: "Read CLAUDE.md and package.json. Confirm you understand the project structure, then run pnpm tsc --noEmit and pnpm vitest run to check the baseline state before we start."

Getting Claude to Respect Your Lock File

Claude will use npm install by default unless told otherwise. Fix this once in CLAUDE.md: add your package manager prominently in caps. For monorepos, also specify the workspace filter pattern: pnpm --filter @myapp/web add react-query.

TypeScript Workflows

Migrating a JS Codebase to TypeScript

1

Start strict: false

Prompt: "Add tsconfig.json with strict: false and allowJs: true. Rename all .js files in src/ to .ts and fix only the errors that prevent compilation."

2

Type file by file

Prompt: "Add explicit TypeScript types to all exported functions in src/lib/api.ts. Run tsc --noEmit after and fix any new errors in that file only."

3

Enable strict mode

Prompt: "Enable strict: true in tsconfig.json. Fix all resulting errors file by file. Prefer narrowing with type guards over 'as' casts."

4

Tighten generics and utility types

Prompt: "Replace any 'any' types in src/ with proper generics or utility types. Use 'unknown' where the type is genuinely uncertain."

TypeScript Patterns Claude Handles Well

Framework Patterns

Node.js & Express / Hono / Fastify

Claude understands the full Node.js ecosystem. Key patterns:

Node.js tip: Tell Claude your Node version — it writes node:fs/promises, node:test, and native fetch correctly for Node 22+ but falls back to older patterns if uncertain.

React 19 Patterns

Claude writes modern React with hooks, server components (where applicable), and Concurrent features:

Next.js App Router Patterns

Claude understands App Router deeply — server vs client components, caching, server actions:

App Router tip: Tell Claude if you're on App Router vs Pages Router — it writes completely different patterns for each. Add this to your CLAUDE.md: "Architecture: Next.js 15, App Router, React Server Components enabled".

Vue 3 / Nuxt 3 Patterns

Claude writes modern Vue 3 Composition API and Nuxt 3 patterns:

Testing: Jest, Vitest & React Testing Library

TDD Workflow with Claude

The most effective pattern for feature development: write the failing test first, then ask Claude to implement the code that makes it pass.

# Step 1 — write the failing test
"Write a Vitest test for parseQueryString(). It should handle:
- empty string → {}
- single param → {key: value}
- array params (?ids=1&ids=2) → {ids: ['1','2']}
- URL-encoded values → decoded strings
Run it — it should fail (the function doesn't exist yet)."

# Step 2 — implement
"Implement parseQueryString() in src/lib/url.ts to make all tests pass.
Run Vitest after each change until all assertions are green."

Component Testing with React Testing Library

Mocking Strategies

# Mock a module with Vitest
"Mock the ../lib/stripe module in this test file using vi.mock().
stub processPayment() to resolve with { id: 'ch_test', status: 'succeeded' }.
Don't mock the rest of the module."

# Mock fetch with msw
"Set up MSW handlers for /api/users: GET returns an array, POST creates and returns the new user.
Add the server setup to src/tests/setup.ts and wire it into vitest.config.ts."

Tooling: ESLint, Prettier, Bundlers

ESLint & Prettier Setup

Vite & Build Optimization

Copy-Paste Prompt Library (35+ Prompts)

CategoryPrompt
TypeScript"Add full TypeScript types to all exported functions in src/. Run tsc --noEmit after each file and fix errors before moving on."
TypeScript"Replace all 'any' types in the codebase with proper types or 'unknown'. Use type guards where needed. Run tsc to verify."
TypeScript"Create a branded type for UserId and ProductId so they can't be mixed up. Update all relevant functions."
TypeScript"Add Zod schemas for all API request/response types in src/types/api.ts. Infer TypeScript types from the schemas."
TypeScript"Enable strict: true in tsconfig.json and fix all resulting errors. Prefer type narrowing over 'as' assertions."
React"Audit all useEffect hooks in src/. Remove effects that can be replaced with event handlers or useMemo. Fix missing deps arrays."
React"Add error boundaries to each top-level route. Each boundary should show a user-friendly fallback UI with a 'Try again' button."
React"Create a ConfirmDialog component using a React portal. It should be callable from anywhere via a useConfirm() hook."
React"Memoize the expensive list in ProductGrid with useMemo and React.memo. Show me the re-render count before and after."
React"Add keyboard navigation to the Dropdown component: arrow keys to navigate, Enter to select, Escape to close, Home/End for first/last."
Next.js"Add generateStaticParams to all dynamic routes that should be statically generated. Add revalidate: 3600 to the rest."
Next.js"Create a middleware.ts that blocks unauthenticated requests to /dashboard/* and redirects to /login with the return URL."
Next.js"Add a /sitemap.xml route using next-sitemap or a dynamic sitemap route handler. Include all static and dynamic pages."
Next.js"Convert this client component data-fetching pattern to a server component. Pass data as props and remove the loading state."
Next.js"Set up next/image for all <img> tags. Add the image domains to next.config.ts. Ensure width/height are set correctly."
Node.js"Refactor the Express router in routes/users.ts to use async handlers with a global error middleware. Remove try/catch boilerplate."
Node.js"Add Helmet.js security headers to the Express app. Configure CSP, HSTS, and referrer-policy appropriate for a public web app."
Node.js"Create a database migration system using node-postgres and ts-node. Add up/down functions and a CLI to run them."
Node.js"Add health check and readiness probe endpoints at /health and /ready. Check database connectivity for the readiness probe."
Node.js"Convert the CommonJS require() calls in this file to ESM imports. Update package.json with type: 'module'."
Testing"Write Vitest unit tests for src/lib/validation.ts. Achieve 100% branch coverage. Run the coverage report to verify."
Testing"Add MSW handlers for all API calls in src/api/. Set up the server in tests/setup.ts so all tests use it automatically."
Testing"Write Playwright E2E tests for the signup flow: invalid email, weak password, success with email verification link."
Testing"Add property-based tests for the price calculation logic using fast-check. Find edge cases the unit tests miss."
Testing"Run the test suite and fix all failing tests. Don't change test expectations — fix the source code instead."
Tooling"Set up changesets for this monorepo. Add a GitHub Actions workflow that creates a release PR when changesets are committed."
Tooling"Configure Turbopack (or Turborepo) for this monorepo. Set up the pipeline so builds only rerun when inputs change."
Tooling"Add a GitHub Actions CI workflow: install → type-check → lint → test → build. Cache node_modules and pnpm store."
Refactor"Extract the inline fetch logic in Dashboard.tsx into a useDashboardData() hook. Keep the component rendering only."
Refactor"Replace the class-based EventEmitter in events.ts with a typed event bus using mitt. Update all call sites."
Refactor"Convert this Promise chain to async/await. Handle the error cases with try/catch and ensure cleanup in a finally block."
Security"Audit the API routes for missing auth checks. Add JWT verification middleware to all routes that require authentication."
Security"Sanitize all user inputs before they touch the database. Add SQL parameterization where missing and HTML escaping for rendered output."
Performance"Profile this Node.js server with clinic.js doctor. Identify the bottleneck and suggest a fix."
Performance"Add React Query to replace the manual fetch/loading/error state pattern across the app. Configure staleTime and cacheTime sensibly."
Docs"Generate TSDoc comments for all public exports in src/lib/. Include @param, @returns, @throws, and a @example for each."
Docs"Create a CONTRIBUTING.md explaining the dev setup, PR process, commit conventions, and how to run tests locally."

FAQ

Does Claude Code work with Node.js and npm workspaces?

Yes — Claude Code inherits your shell's Node version (via nvm, fnm, or system install) and understands npm, yarn, and pnpm workspaces. It reads package.json scripts, lock files, and monorepo configs like Turborepo or Nx. Specify your package manager in CLAUDE.md so Claude never mixes them.

How do I use Claude Code with TypeScript?

Claude reads your tsconfig.json to understand strict settings, path aliases, and module resolution. Prompt: "Add full TypeScript types to all exported functions in src/" and Claude infers types from usage, JSDoc, and return values. Add pnpm tsc --noEmit to your CLAUDE.md test command so Claude catches type errors automatically after every change.

Can Claude Code help with React and Next.js projects?

Claude understands App Router vs Pages Router, React Server Components, server actions, dynamic routes, middleware, and the Next.js caching model. Specify your Next.js version and router type in CLAUDE.md — the patterns are completely different between App Router and Pages Router, and Claude defaults to App Router for Next.js 13+.

How does Claude Code work with Jest and Vitest?

Claude reads jest.config.ts or vitest.config.ts, understands vi.mock() and jest.mock(), and generates correct async test patterns with waitFor() and userEvent. For TDD: "Write failing tests for [feature], then implement the code to make them pass." Claude runs the test suite between changes and iterates until green.

Can Claude Code help migrate JavaScript to TypeScript?

This is one of Claude Code's strongest use cases. Approach: start with strict: false and allowJs: true, then migrate file by file, then enable strict: true. A 10,000-line migration that takes a developer weeks often completes in one session. Commit after each file so you can roll back individual changes.

What should I put in CLAUDE.md for a JS/TS project?

Essential items: (1) Node version and package manager, (2) pnpm install, (3) dev server command, (4) test command with flags, (5) type check command (tsc --noEmit), (6) lint/format command, (7) build command, (8) path aliases, (9) directories Claude must not touch (dist/, .next/, node_modules/). The template above covers everything — customize it in five minutes.

How do I use Claude Code for React testing with Testing Library?

Claude writes RTL tests correctly: uses getByRole, findByText, and userEvent instead of Enzyme-style wrapper methods. Prompt: "Write RTL tests for UserCard — test loading state, success state, and error state." Claude wraps state updates in act(), uses waitFor() for async updates, and mocks network requests with MSW or vi.mock().

Related Guides

More Claude Code Tools

⚡ Using Claude Code? 30 power prompts that 2× your output · £5 £3 first 10Get PDF £3 →