Setting Up Claude Code for Indie Shipping u2014 Complete Developer Walkthrough

[IMAGE_PLACEHOLDER_HEADER]

⚡ TL;DR — Key Takeaways

  • What it is: A practical, end-to-end developer walkthrough for configuring Claude Code as an autonomous CLI agent to ship production SaaS quickly and safely.
  • Who it’s for: Indie hackers and 1–2 person dev teams who want a repeatable shipping loop from git init to payment collection using claude-sonnet-4.6 and claude-opus-4.7.
  • Core benefits: Faster iteration, fewer context switches, reproducible guardrails, and predictable billing with prompt caching and per-task model routing.
  • Key components: CLAUDE.md conventions, MCP servers, hooks/subagents, permission modes, testing loops, deploy automation, and cost controls.
  • Bottom line: Treat Claude Code like a briefed senior engineer, not an autocomplete tool. That mental model unlocks ~3x faster shipping while keeping your codebase maintainable.

Why Claude Code became the default indie shipping stack in 2026

By 2026, a pragmatic consensus formed among solo founders and tiny teams: Claude Code is uniquely effective for shipping production SaaS rapidly. There are three reasons for this adoption pattern:

  • Agentic capability: Claude Code is an autonomous CLI agent that can read, plan, run terminal commands, edit files, run tests, and commit changes. This reduces context switching and manual verification compared to IDE-centric tools.
  • Model quality: Opus 4.7 and Sonnet 4.6 deliver strong coding and reasoning performance. Terminal-Bench and SWE-bench improvements mean the agent reliably completes multi-step shell tasks and understands codebase-level changes without constant oversight.
  • Economics and tooling: With per-task model routing, prompt caching, and cheap MCP servers, the marginal cost of using Claude Code drops dramatically for typical indie workflows.

All of that is true only when you pair the tool with disciplined patterns: a clear CLAUDE.md, model routing per task, MCP servers for external context, conservative permission modes, and automation hooks that make the agent verify its work. This guide teaches those patterns so you get the speed benefits without the fear.

What you actually need installed

Before diving into configuration, install and verify a minimal toolchain. This section lists concrete versions and why each item matters.

Minimum viable indie stack (practical)

  • Node.js 20+ — Claude Code is Node-first; newer LTS reduces runtime differences between your machine and CI/deploy targets.
  • Claude Code CLI — npm install -g @anthropic-ai/claude-code (keep up-to-date; breaking changes appear between major releases).
  • An Anthropic API key (Tier 2 recommended) — programmatic access gives predictability and avoids GUI throttling.
  • Git with sensible defaults — sign commits, set your name/email, and use a simple branching convention (main + feature/*).
  • One MCP-compatible DB client — Postgres is standard; MCP Postgres server gives structured DB access without leaking tokens.
  • Shell — zsh or bash; Claude will execute terminal commands so ensure your profile scripts are sane and fast.

[IMAGE_PLACEHOLDER_SECTION_1]

Optional but strongly recommended

  • pnpm or bun — faster installs and deterministic node_modules. Pick one and record it in CLAUDE.md.
  • Playwright — for automated UI verification via MCP.
  • Local dev database — run a dev Postgres container or managed environment for realistic tests.
  • Pre-commit hooks — keep linting and formatting consistent so the agent’s edits pass style checks.

Installation and first-boot configuration

This section walks through a fresh install, authentication choices, and the first settings you should tweak for indie shipping.

Clean install steps

npm uninstall -g @anthropic-ai/claude-code || true
npm install -g @anthropic-ai/claude-code@latest
claude --version
# Expect a 2.x.x or higher release

# Authenticate
claude
# Choose: API Key (paste from console.anthropic.com)
# Or: Use a subscription-style auth if offered (note: subscription often lacks full programmatic access)

Notes on authentication: an API key gives you programmatic access, consistent quotas, and clear billing. A subscription (Claude Pro/Max) may give UI-level advantages for interactive sessions but often lacks predictable programmatic access and can be throttled.

Initial settings you should set now

Create ~/.claude/settings.json with project-friendly defaults. Example:

{
  "model": "claude-sonnet-4-6-20260315",
  "fallbackModel": "claude-haiku-4-5-20260201",
  "thinkingBudget": 8000,
  "permissionMode": "acceptEdits",
  "autoCompactThreshold": 0.85,
  "telemetry": false
}

Key fields:

  • thinkingBudget — controls extended reasoning tokens; 8000 is a solid default for typical coding tasks with Sonnet.
  • permissionMode — start in plan mode for large tasks, then acceptEdits for execution.
  • autoCompactThreshold — a heuristic for automatic session compaction; tune if you see context rot.

CLAUDE.md best practices and template

The CLAUDE.md file is the single most important guardrail for consistent agent behavior. It becomes part of the agent’s system prompt every session and benefits from prompt caching (cheap to reference).

Principles for good CLAUDE.md files

  1. Rules over descriptions: Describe rules, conventions, and forbidden operations. Prefer explicit guardrails to long prose about business rationale.
  2. Small, testable units: Keep sections short and scoped. If a rule is conditional, show the condition example.
  3. Version everything: Record framework and package versions so the agent uses the correct patterns (SvelteKit v1.3.2, Prisma 4.12.0, etc.).
  4. Off-limits paths: Explicitly mark files and folders the agent must never edit, and explain why.
  5. Update on change: When you change architecture, update CLAUDE.md. Treat it as living glue-docs for the agent.

CLAUDE.md template (practical starter)

# CLAUDE.md - Project rules and guardrails

Project: Acme SaaS
Stack: Node.js 20, TypeScript 5.5, pnpm 8, SvelteKit 1.3.2, Prisma 4.12.0, Postgres 15

Directory conventions:
- /src/lib: business logic
- /src/routes: http endpoints and pages
- /migrations: PR-reviewed DB migrations only (no direct edits)
- /legacy: read-only (do not modify)

Naming rules:
- Files: kebab-case
- React/Svelte components: PascalCase
- DB columns: snake_case

Forbidden actions:
- Never run: prisma migrate reset, DROP TABLE on production, git push --force
- Never edit files under /legacy
- Never commit secrets or environment variables (examples: .env.production)

Testing and CI:
- Unit test: pnpm test:unit
- E2E: pnpm test:e2e
- Typecheck: pnpm typecheck

Deployment:
- Auto-deploy branch: main
- Preview branch: preview/*
- Environment variables: list.env (do not expose in logs)

When inspecting DB, read db/schema.sql first. Only query live DB when absolutely necessary (and never production unless a migration PR is created).

Keep CLAUDE.md under ~2000 tokens of instructions — in practice a 400–900 word focused file works best. Longer files risk instruction dilution where Claude begins to ignore middle-section rules.

MCP servers: essential servers and patterns

Model Context Protocol (MCP) servers are how Claude Code safely accesses external systems like databases, GitHub, and the browser. Set up a small, focused set of MCP servers tuned to common indie tasks.

Essential MCP servers for indie SaaS

  • Postgres MCP — structured DB queries and schema inspection.
  • GitHub MCP — read/open PRs, inspect issues, and check CI state.
  • Filesystem MCP (sandboxed) — reference repos or fixtures outside current project.
  • Playwright / Chrome DevTools MCP — end-to-end UI verification and basic accessibility checks.

[IMAGE_PLACEHOLDER_SECTION_2]

Sample .mcp.json for an indie repo

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost:5432/myapp_dev"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_TOKEN": "${GITHUB_PAT}" }
    },
    "playwright": {
      "command": "npx",
      "args": ["-y", "@playwright/mcp@latest"]
    }
  }
}

Database access patterns that save tokens

Live DB queries are expensive in token terms if you repeatedly pull schema or data. Use these patterns:

  • schema.sql snapshot: Use pg_dump --schema-only or a formatted SQL snapshot at db/schema.sql and instruct Claude to read that before any live query.
  • Query sparingly: Only ask the Postgres MCP for rows when you need fresh, time-sensitive data (e.g., a failing migration or a single-user repro).
  • Pre-commit refresh: Keep schema snapshots updated in a pre-commit hook so they’re rarely stale.
  • Field-level extracts: If you need to inspect a table, ask for a sampled projection (e.g., first 50 rows of (id, created_at, status)) not whole tables.

Custom MCP servers: quick wins

Write small MCP wrappers for external services you query often. Common ones:

  • Stripe — list customers, create a refund, simulate checkout session
  • Resend / SendGrid — check last 24h deliveries
  • Analytics provider — query events for a specific user

Use @modelcontextprotocol/sdk to implement a simple TypeScript MCP in ~80 lines, and keep it in ./mcp-servers/ rather than publishing to npm. Point to the local path in .mcp.json.

Hooks, subagents, and guardrails

Hooks are how Claude Code verifies its own work; subagents give you specialized, lower-cost workers for repeated tasks. Combined, they reduce human-in-the-loop work dramatically while keeping safety.

The five high-ROI hooks to configure

Put these in ~/.claude/settings.json or project-specific ./.claude/settings.json:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [{
          "type": "command",
          "command": ".claude/scripts/block-dangerous.sh"
        }]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [{
          "type": "command",
          "command": "pnpm typecheck --silent || echo 'TYPECHECK FAILED'"
        }]
      },
      {
        "matcher": "Edit|Write",
        "hooks": [{
          "type": "command",
          "command": "pnpm lint --fix --silent"
        }]
      }
    ],
    "Stop": [
      {
        "hooks": [{
          "type": "command",
          "command": "pnpm test --run --silent"
        }]
      }
    ]
  }
}

Why these hooks matter:

  • PreToolUse block script: Prevent catastrophic commands from running (rm -rf, prisma migrate reset, git push –force).
  • PostToolUse typecheck: Ensure each file edit compiles; feed errors back to Claude for self-fixing.
  • Lint and tests: Enforce style and basic correctness before claiming work is done.

Example block-dangerous.sh

#!/usr/bin/env bash
set -euo pipefail

CMD="$*"

# Patterns to block
BLOCKED_PATTERNS=(
  "rm -rf"
  "DROP TABLE"
  "prisma migrate reset"
  "git push --force"
  "aws s3 rm"
  "heroku pg:reset"
)

for p in "${BLOCKED_PATTERNS[@]}"; do
  if echo "$CMD" | grep -qi "$p"; then
    echo "DANGEROUS COMMAND DETECTED: $p" >&2
    exit 2
  fi
done

# If fine, allow execution (but agent will still be asked to confirm)
exec $CMD

Subagents you should define immediately

Subagents are scoped Claude instances with limited tools and a focused system prompt. Three subagents deliver immediate ROI:

  • code-reviewer — reads diffs, flags bugs and security issues. Use a cheap model like Haiku 4.5 for cost efficiency.
  • test-writer — given a file or function, generate unit/e2e tests. Sonnet 4.6 is good here.
  • migration-author — writes forward+rollback migrations after reviewing schema changes. Use Opus when reasoning about DB invariants.

Subagents let the main agent delegate work and return structured responses. In practice this yields faster, more deterministic outcomes than a single large session.

Permission modes: a disciplined approach

Use permission modes to reduce risk. Suggested workflow:

  1. Plan mode: Start here for any task >1 file. Claude returns a numbered plan you can reject.
  2. acceptEdits: Switch here for controlled execution once you approve the plan. Hooks still apply.
  3. default: Use when touching sensitive configs / production-involving work.
  4. bypassPermissions: Never use in real repos. For throwaway sandboxes only.

The shipping loop: spec → deployed

Claude Code works best when you adopt a repeatable shipping loop. This section expands the five-phase loop into concrete checklists and examples so you can reproduce successful runs reliably.

Phase 1: Write a spec, not a one-line prompt

Create a small spec file in spec/ describing goal, scope, files expected to change, acceptance criteria, and edge cases. The spec acts as a contract between you and the agent.

# spec/2026-04-26-add-team-invites.md

## Goal
Allow workspace owners to invite teammates via email link.

## Files expected to change
- src/routes/api/invites/+server.ts (new)
- src/routes/invites/[token]/+page.svelte (new)
- src/lib/server/email/templates/invite.tsx (new)
- prisma/schema.prisma (add Invite model)

## Out of scope
- Role-based permissions (handled in separate spec)
- SAML / SSO

## Acceptance
- Owner can POST /api/invites with email; receives 200
- Email arrives via Resend within 30s
- Clicking link creates membership; expired tokens (>7 days) return 410
- Tests cover happy path, expired token, already-member, invalid token

Phase 2: Plan review — what to check

Questions to ask when Claude returns a plan:

  • Does it understand data model changes? (Show the schema excerpt if necessary.)
  • Are auth checks and validation listed?
  • Does it propose touching any off-limits files listed in CLAUDE.md?
  • Is the plan broken into small, testable tasks (unit-first, then e2e)?

Phase 3: Execution with hooks

Switch to acceptEdits and let Claude run. Don’t micromanage but watch for long-running Bash processes. Use Ctrl+C to interrupt and re-plan rather than letting the agent finish a wrong path for 20 minutes.

Phase 4: Diff review and commit

Checklist before commit:

  • git diff –stat — confirm scope.
  • Run local test suite and typecheck locally (hooks should ensure this already, but double-check).
  • Review for secrets, environment variable leakage, and forbidden file touches.
  • Edit the commit message to enforce semantic commit style (Claude can write a good first draft).

Phase 5: Deploy and verify

Have a small command in .claude/commands/deploy.md that runs tests, builds, deploys to a preview URL, and uses Playwright MCP to verify acceptance criteria. Example deploy flow:

  1. Run pnpm test –run
  2. Build preview: pnpm build –preview
  3. Deploy preview CLI (Vercel/Fly/Railway)
  4. Playwright open preview URL; verify selected flows

[IMAGE_PLACEHOLDER_SECTION_3]

Billing, cost control, and measurement

Predictable billing is essential for indie devs. This section gives practical routing, caching, and daily measurement practices that keep costs reasonable.

Model routing: per-task selection

Route models by task to balance cost vs quality:

  • Architecture & debugging: claude-opus-4.7 — highest reasoning quality.
  • Feature implementation & refactor: claude-sonnet-4.6 — solid code generation at lower cost.
  • Boilerplate & unit tests: claude-haiku-4.5 — cheapest and fast for mundane work.
  • Large repo review: Opus 4.7 with 1M context if required (enable only when necessary).

Prompt caching and /compact

Prompt caching reduces reads cost dramatically. Use /compact frequently on long sessions to summarize context into a short representation and reduce token usage on subsequent turns.

Daily measurement

Use claude usage or your Anthropic dashboard to get session and token metrics daily for the first month. Track:

  • Tokens per session
  • Sessions per day
  • Model mix (percentage Opus vs Sonnet vs Haiku)
  • Cost per day and extrapolated monthly spend

Common cost culprits and fixes

  • Using Opus for everything → switch routine tasks to Sonnet or Haiku.
  • Not compacting → call /compact or end-and-start new sessions.
  • Schema pulls each turn → add db/schema.sql and instruct the agent to read first.
  • Huge CLAUDE.md with redundancies → trim and organize rules into bullets.

With these practices, most indie devs working with Claude Code 6–8 hours/day land in the $40–$90/month range. If you need ultra-low cost Q&A rather than long agentic runs, compare experiments with other models (Gemini, OpenAI) for selective tasks.

Common failure modes and how to recover

After shipping features with Claude Code, six failure modes show up repeatedly. Recognizing them quickly saves hours.

Failure mode 1: Context rot on long sessions

Symptoms: Claude forgets rules from CLAUDE.md, repeats earlier mistakes, or ignores directory conventions. Recovery:

  1. Call /compact to summarize prior turns.
  2. If compaction doesn’t help, start a fresh session and paste the compacted summary as the system prompt.
  3. Shorten sessions by breaking big tasks into smaller specs.

Failure mode 2: Silent type errors

Symptoms: Agent edits many files but CI/typecheck fails later. Mitigation:

  • Ensure PostToolUse typecheck hook is active so Claude sees type errors immediately and can fix them.
  • Run a local typecheck before commit.

Failure mode 3: Dangerous DB or shell commands

Symptoms: Agent proposes or attempts destructive commands. Mitigation:

  • Strict PreToolUse block script that exits non-zero on patterns.
  • PermissionMode default for production-affecting tasks.
  • Require explicit migration PRs for production DB changes; never allow direct production migrations.

Failure mode 4: Overly defensive or verbose changes

Symptoms: Agent inserts try/catch everywhere or overly cautious code. Mitigation:

  • Guide Claude in CLAUDE.md regarding error-handling style (e.g., prefer early-return validation vs nested try/catch).
  • Use code-reviewer subagent to flag stylistic or non-idiomatic patterns.

Failure mode 5: CI flakiness post-deploy

Symptoms: Preview deploy succeeds locally, but CI fails with environment mismatch. Mitigation:

  • Make local environment mirrors for critical env vars using a .env.example file (no secrets).
  • Use the same Node and package manager versions in CI and CLAUDE.md.

Failure mode 6: Unexpected cost spikes

Symptoms: Monthly spend far above expected. Mitigation:

  • Audit recent sessions to find Opus-heavy runs or long unattended agent runs.
  • Use daily cost alerts and hard limits on API keys if possible.

Advanced topics: CI, observability, custom MCPs

Once your basic stack is stable, add CI integration, observability, and custom MCP servers for higher automation and lower friction.

CI integration patterns

Integrate Claude actions into CI conservatively:

  • Preview-only agent runs: Allow Claude to run in preview branches only, not on main.
  • Automated PR checks: Use code-reviewer subagent to run on every PR and post structured findings as PR comments.
  • Blocked merges: Enforce that database migrations require a human sign-off and a passing migration-author check in CI before merging.

Observability and logs

Track agent activity with structured logs:

  • Log session start/stop time, model used, and token usage to a local file or lightweight service.
  • Keep diffs and commit hashes associated with session IDs for auditing.
  • Record MCP server queries and responses (redacted) to help reproduce issues.

Custom MCP development: a short recipe

When to write a custom MCP:

  • If you call an API >10 times/week.
  • If the API state or context is complex (e.g., Stripe + metadata + idempotency).

Recipe:

  1. Install @modelcontextprotocol/sdk.
  2. Create a TypeScript handler exposing a small set of operations (listCustomers, getInvoice, refundCharge).
  3. Run locally and add to .mcp.json as a local path server.
  4. Restrict outputs to only the necessary fields to avoid token waste.

Frequently Asked Questions

What Node.js version does Claude Code require to run properly?

Claude Code requires Node.js 20 or higher. It interacts heavily with the file system and spawns child processes, so use a modern LTS for deterministic behavior. Verify with node --version.

Should I use a subscription or API tokens?

For predictable programmatic access and billing control, prefer API tokens. Subscriptions (like Claude Max) can be a useful UI fallback but may throttle or lack full CLI/SDK access. If you need heavy interactive usage with unpredictable token patterns, evaluate subscription quotas vs API spend.

How do I avoid leaking secrets to the agent?

Never include production secrets in CLAUDE.md, and add them to your .gitignore. Configure MCP servers to redact or filter sensitive fields. Use a separate secrets manager and only provide minimally scoped access to custom MCPs.

How often should I compact sessions?

Compact proactively after long planning phases or every ~40–60 turns. If the agent starts ignoring rules or repeating mistakes, compact immediately or start a new session with the compacted summary as context.

What are the most important lines to include in CLAUDE.md?

Priority: stack and versions, directory conventions (what to touch/avoid), forbidden actions, test/run commands, and deployment branch/preview rules. Those allow Claude to act safely and predictably.

Appendix: Useful sample files

Sample .claude/agents/code-reviewer.md

---
name: code-reviewer
description: Reviews git diffs for bugs, security issues, and convention violations
model: claude-haiku-4-5
tools: Read, Grep, Bash
---

You are a strict code reviewer. Read the provided diff and flag:
1. Potential null/undefined errors
2. Missing input validation on user-facing endpoints
3. N+1 query patterns
4. Hardcoded secrets or environment variables
5. Violations of conventions in CLAUDE.md

Output a numbered list of concerns. Do NOT suggest stylistic changes. Do NOT comment on what is correct. Be terse.

Sample .claude/commands/deploy.md

---
name: deploy
description: Run tests, build and deploy preview to Vercel then verify with Playwright
model: claude-sonnet-4-6
tools: Bash, Playwright
---

1. Run pnpm test --run
2. Build preview: pnpm build --preview
3. Deploy to Vercel CLI: vercel --prod
4. Return preview URL and run Playwright checks:
   - Visit homepage
   - Ensure signup button exists and routes to /signup
   - Attempt mocked checkout flow (Resend/Stripe stubs)

Closing notes

Claude Code is a powerful tool for indie shipping when paired with disciplined patterns: crisp CLAUDE.md rules, MCP servers that avoid token waste, hooks and subagents that enforce quality, and a cautious permission strategy. Use the templates and patterns above to build a reproducible shipping loop. Start small, measure token usage daily for the first month, and iterate on CLAUDE.md and your hook scripts so the system steadily improves.

[IMAGE_PLACEHOLDER_FOOTER]

Get Free Access to 40,000+ AI Prompts for ChatGPT, Claude & Codex

Subscribe for instant access to the largest curated Notion Prompt Library for AI workflows.

More on this