Content is user-generated and unverified.

Claude Code Guidelines for Modern Web Applications

Implementation Best Practices

0 — Purpose

These rules ensure maintainability, performance, security, and developer velocity in modern web applications. MUST rules are enforced by CI/CD; SHOULD rules are strongly recommended; CONSIDER rules are situational best practices.


1 — Before Development

  • BP-1 (MUST) Ask clarifying questions about requirements, constraints, and user experience goals.
  • BP-2 (SHOULD) Draft and confirm technical approach for complex features, including performance implications.
  • BP-3 (SHOULD) If ≥ 2 implementation approaches exist, provide clear pros/cons with performance and maintainability trade-offs.
  • BP-4 (CONSIDER) Identify potential accessibility, SEO, and security implications early.

2 — Web Development Standards

  • WD-1 (MUST) Follow semantic HTML principles and ensure proper accessibility attributes.
  • WD-2 (MUST) Implement responsive design patterns that work across devices.
  • WD-3 (SHOULD) Optimize for Core Web Vitals (LCP, FID, CLS) from the start.
  • WD-4 (SHOULD) Use progressive enhancement principles - ensure basic functionality works without JavaScript.
  • WD-5 (MUST) Validate all user inputs on both client and server side.
  • WD-6 (SHOULD) Implement proper error boundaries and graceful degradation.
  • WD-7 (CONSIDER) Use CSS-in-JS or utility-first CSS frameworks for consistent styling.

3 — Code Quality & Architecture

  • CQ-1 (MUST) Follow TDD: component scaffold → failing test → implementation → refactor.
  • CQ-2 (MUST) Name functions, components, and variables using established domain vocabulary.
  • CQ-3 (SHOULD NOT) Create classes when functional components and hooks suffice.
  • CQ-4 (SHOULD) Prefer composition over inheritance, pure functions over side effects.
  • CQ-5 (MUST) Use strict TypeScript with branded types for domain IDs:
ts
  type UserId = Brand<string, 'UserId'>     // ✅ Good
  type ProductId = Brand<string, 'ProductId'> // ✅ Good
  type UserId = string                      // ❌ Bad
  • CQ-6 (MUST) Use import type { … } for type-only imports.
  • CQ-7 (SHOULD NOT) Add comments except for critical business logic caveats; prefer self-documenting code.
  • CQ-8 (SHOULD) Default to type over interface; use interface only for extensibility or declaration merging.
  • CQ-9 (SHOULD NOT) Extract functions/components unless: reused elsewhere, enables isolated testing, or significantly improves readability.
  • CQ-10 (MUST) Handle loading, error, and empty states for all async operations.

4 — Component Architecture

  • CA-1 (SHOULD) Keep components small and focused on single responsibility.
  • CA-2 (MUST) Separate presentational components from container/logic components.
  • CA-3 (SHOULD) Use custom hooks to encapsulate complex stateful logic.
  • CA-4 (SHOULD) Implement proper prop validation and default values.
  • CA-5 (CONSIDER) Use render props or compound components for flexible, reusable UI patterns.
  • CA-6 (MUST) Implement proper key props for dynamic lists.
  • CA-7 (SHOULD) Use React.memo() judiciously for expensive re-renders, not by default.

5 — State Management

  • SM-1 (SHOULD) Start with local state, lift up only when necessary.
  • SM-2 (SHOULD) Use context sparingly; prefer prop drilling for 2-3 levels.
  • SM-3 (CONSIDER) Implement global state management (Redux, Zustand) for complex apps with shared state.
  • SM-4 (MUST) Separate server state (React Query, SWR) from client state.
  • SM-5 (SHOULD) Use reducers for complex state transitions and business logic.

6 — Testing Strategy

  • TS-1 (MUST) Colocate unit tests in *.test.ts or __tests__ folder next to source.
  • TS-2 (MUST) Write integration tests for critical user workflows in e2e/ or tests/integration/.
  • TS-3 (MUST) Separate pure logic tests from DOM/API integration tests.
  • TS-4 (SHOULD) Prefer integration and end-to-end tests over heavy mocking.
  • TS-5 (SHOULD) Unit-test complex algorithms, business logic, and utility functions thoroughly.
  • TS-6 (SHOULD) Test complete user interactions, not implementation details:
ts
  // ✅ Good - tests behavior
  expect(screen.getByText('Welcome')).toBeInTheDocument();
  
  // ❌ Bad - tests implementation
  expect(mockSetState).toHaveBeenCalledWith('welcome');
  • TS-7 (MUST) Test accessibility with screen reader simulation and keyboard navigation.
  • TS-8 (SHOULD) Include visual regression tests for critical UI components.

7 — Performance & Optimization

  • PO-1 (MUST) Implement code splitting and lazy loading for routes and heavy components.
  • PO-2 (SHOULD) Optimize images with proper formats (WebP, AVIF) and responsive sizes.
  • PO-3 (SHOULD) Use virtual scrolling for large lists (1000+ items).
  • PO-4 (MUST) Implement proper caching strategies (browser cache, CDN, service worker).
  • PO-5 (SHOULD) Minimize bundle size - audit dependencies regularly.
  • PO-6 (CONSIDER) Use SSR/SSG for SEO-critical pages and initial load performance.

8 — Data & API Management

  • API-1 (MUST) Type API responses and requests with strict schemas (Zod, TypeBox).
  • API-2 (SHOULD) Implement proper error handling with user-friendly messages.
  • API-3 (MUST) Handle network failures gracefully with retry logic and offline support.
  • API-4 (SHOULD) Use optimistic updates for better perceived performance.
  • API-5 (MUST) Implement proper data validation on both client and server.
  • API-6 (CONSIDER) Use GraphQL for complex data requirements, REST for simple CRUD.

9 — Security & Privacy

  • SP-1 (MUST) Sanitize all user inputs to prevent XSS attacks.
  • SP-2 (MUST) Implement Content Security Policy (CSP) headers.
  • SP-3 (MUST) Use HTTPS everywhere, implement proper CORS policies.
  • SP-4 (SHOULD) Implement proper authentication and authorization patterns.
  • SP-5 (MUST) Never expose sensitive data in client-side code or logs.
  • SP-6 (SHOULD) Implement rate limiting and input validation on all endpoints.

10 — Code Organization & Architecture

  • CO-1 (MUST) Use feature-based folder structure for large applications:
  src/
    features/
      auth/
        components/
        hooks/
        services/
        types/
      dashboard/
        ...
    shared/
      components/
      hooks/
      utils/
      types/
  • CO-2 (MUST) Place code in shared/ only if used by ≥ 2 features.
  • CO-3 (SHOULD) Separate business logic from UI components.
  • CO-4 (SHOULD) Use barrel exports (index.ts) for clean imports.

11 — Tooling & Quality Gates

  • TQ-1 (MUST) prettier --check passes on all files.
  • TQ-2 (MUST) eslint --fix passes with zero warnings.
  • TQ-3 (MUST) tsc --noEmit passes with strict TypeScript checks.
  • TQ-4 (SHOULD) Use pre-commit hooks to enforce quality gates.
  • TQ-5 (SHOULD) Run bundle analysis and performance audits in CI.

12 — Git & Deployment

  • GD-1 (MUST) Use Conventional Commits format: https://www.conventionalcommits.org/en/v1.0.0
  • GD-2 (SHOULD NOT) Reference AI tools or assistants in commit messages.
  • GD-3 (MUST) Use feature branches and pull requests for all changes.
  • GD-4 (SHOULD) Include deployment previews for UI changes.
  • GD-5 (MUST) Run full test suite before merging to main branch.

Code Quality Evaluation

Function Quality Checklist

When evaluating function quality, use this checklist:

  1. Readability: Can you understand the function's purpose and logic without extensive mental parsing?
  2. Complexity: Does it have manageable cyclomatic complexity (< 10 branches)?
  3. Patterns: Would standard algorithms/data structures make it clearer and more robust?
  4. Parameters: Are all parameters used? Can type safety be improved?
  5. Testability: Can it be unit tested without mocking core dependencies?
  6. Dependencies: Are external dependencies minimal and explicit?
  7. Naming: Is the name descriptive and consistent with codebase conventions?
  8. Single Responsibility: Does it do one thing well?

IMPORTANT: Only extract separate functions when:

  • The function is reused in multiple places
  • Extraction enables isolated unit testing of complex logic
  • The original function is genuinely hard to follow despite good naming and structure

Component Quality Checklist

  1. Single Responsibility: Does the component have one clear purpose?
  2. Prop Interface: Are props well-typed with clear naming and defaults?
  3. State Management: Is state kept at the appropriate level (local vs lifted)?
  4. Performance: Are expensive operations memoized appropriately?
  5. Accessibility: Does it work with keyboard navigation and screen readers?
  6. Error Handling: Does it handle edge cases and error states gracefully?
  7. Reusability: Can it be easily reused without tight coupling?

Test Quality Checklist

  1. Parameterization: Use descriptive test data, avoid magic numbers like 42 or "foo".
  2. Failure Potential: Every test should be able to fail for a real defect.
  3. Clear Intent: Test description should match exactly what the assertion verifies.
  4. Independent Oracles: Compare to pre-computed expectations, not function output.
  5. Code Quality: Follow same lint, type, and style rules as production code.
  6. Property Testing: Use property-based testing for mathematical invariants:
ts
import fc from 'fast-check';

test('addition is commutative', () => {
  fc.assert(
    fc.property(fc.integer(), fc.integer(), (a, b) => 
      add(a, b) === add(b, a)
    )
  );
});
  1. Test Organization: Group tests by component/function name.
  2. Strong Assertions: Use specific assertions over generic ones.
  3. Edge Cases: Test boundaries, error conditions, and realistic user inputs.
  4. User-Centric: Test behavior users care about, not implementation details.

Project Structure Templates

React + TypeScript SPA

src/
  components/
    ui/           # Reusable UI components
    layout/       # Layout components
  features/
    auth/
    dashboard/
    profile/
  hooks/          # Custom hooks
  services/       # API and external services
  utils/          # Pure utility functions
  types/          # Shared TypeScript types
  constants/      # Application constants

Next.js Full-Stack App

src/
  app/            # App Router pages
  components/     # Shared components
  features/       # Feature modules
  lib/            # Utilities and configurations
  hooks/          # Custom hooks
  types/          # TypeScript definitions
  middleware.ts   # Next.js middleware

Productivity Shortcuts

XFRESH

Understand all BEST PRACTICES in this guide.
Your code MUST ALWAYS follow these web development standards.
Focus on performance, accessibility, and user experience.

XSTRAT

Analyze the existing codebase architecture and determine if your plan:
- Follows established patterns and conventions
- Minimizes complexity and dependencies
- Reuses existing components and utilities
- Maintains performance and accessibility standards
- Considers mobile and cross-browser compatibility

XBUILD

Implement your plan following these steps:
1. Create/update components with proper TypeScript types
2. Implement comprehensive tests (unit + integration)
3. Ensure accessibility compliance
4. Test responsive behavior
5. Run prettier, eslint, and type checking
6. Verify performance impact

XAUDIT

You are a SENIOR FRONTEND ARCHITECT performing a thorough code review.
Analyze every major change using:
1. Function Quality Checklist
2. Component Quality Checklist  
3. Test Quality Checklist
4. Performance implications
5. Accessibility compliance
6. Security considerations

XCOMP

You are a FRONTEND EXPERT reviewing component architecture.
For each major component added/modified, evaluate:
1. Component Quality Checklist
2. Reusability and composition patterns
3. Performance optimization opportunities
4. Accessibility implementation

XTEST

You are a QA ENGINEER reviewing test coverage.
For each test suite added/modified, check:
1. Test Quality Checklist
2. Coverage of user workflows
3. Edge case handling
4. Performance test considerations

XFLOW

Imagine you are a real user testing this feature across different devices.
Create a comprehensive test plan including:
- Happy path scenarios
- Error conditions
- Accessibility testing
- Mobile/tablet behavior
- Cross-browser compatibility
- Performance under load
Sort by business impact and user frustration potential.

XSHIP

Prepare for deployment:
1. Run full test suite and ensure 100% pass rate
2. Check bundle size impact and performance metrics
3. Verify accessibility compliance
4. Test in multiple browsers/devices
5. Add all changes to staging
6. Create conventional commit with proper scope
7. Push to feature branch for review

Commit message format:
<type>[optional scope]: <description>

Types: feat, fix, docs, style, refactor, test, chore
Scopes: ui, api, auth, dashboard, etc.

XPERF

Analyze performance implications of your changes:
1. Bundle size impact
2. Runtime performance (rendering, interactions)
3. Network requests and caching
4. Core Web Vitals impact
5. Mobile performance considerations
Suggest optimizations if needed.
Content is user-generated and unverified.
    Enhanced Claude Code Guidelines for Web Applications | Claude