Project Documentation

A comprehensive guide to the ChabadUniverse Starter Kit.

Introduction & Tech Stack

Welcome to the ChabadUniverse Starter Kit. This project is an elegant Next.js application template designed for rapid development and scalable deployment. It uses modern, open-source technologies to provide a solid foundation for your next project.

Complete Tech Stack:

  • Framework: Next.js 15 with Pages Router
  • Frontend: React 18
  • Language: TypeScript/JavaScript hybrid architecture
  • Styling: Tailwind CSS + tailwindcss-animate
  • UI Components: 50 Custom shadcn/ui-inspired components + Radix UI primitives
  • Icons: Lucide React
  • Forms: React Hook Form + Zod validation
  • API Integration: @arkeytyp/valu-api + Custom Merkos Platform client
  • Testing: Jest 30.0.4 + React Testing Library 16.3.0 (406 passing tests)
  • Development Tools: TypeScript 5.3.3, ESLint, PostCSS

Additional Libraries:

  • UI Enhancements: vaul (drawer), sonner (toasts), cmdk (command palette)
  • Data Visualization: recharts (charts and graphs)
  • Date & Time: react-day-picker, date-fns
  • Layout: react-resizable-panels, embla-carousel-react
  • Utilities: clsx, tailwind-merge, class-variance-authority

Key Architecture Features:

  • TypeScript integration - Type safety for core application logic
  • Hybrid architecture - TypeScript for APIs/hooks, JSX for complex UI components
  • Next.js API routes - Serverless backend functionality
  • Server-side rendering (SSR) - Optimized performance and SEO
  • File-based routing - Automatic route generation
  • Next.js Link component - Optimized navigation
  • Vercel deployment ready - Zero-config deployment
Project Structure

Complete Project Structure:

chabaduniverse-starter-kit/
├── packages/                # Monorepo packages
│   └── merkos-api-client/   # Extracted Merkos API client package
│       ├── src/             # TypeScript source code
│       ├── tests/           # Jest test suite
│       ├── dist/            # Built output (gitignored)
│       └── package.json     # Package configuration
│
├── pages/                   # Next.js pages and routes
│   ├── api/                # API endpoints (serverless functions)
│   │   └── contact.ts      # Contact form API (TypeScript)
│   ├── _app.tsx            # App wrapper (TypeScript)
│   ├── _document.js        # HTML document template
│   ├── index.js            # Home page (/)
│   ├── about.js            # About page (/about)
│   ├── contact.js          # Contact page (/contact)
│   ├── documentation.jsx   # This documentation (/documentation)
│   ├── api-demo.tsx        # API demo page (/api-demo)
│   ├── test.tsx            # Test page (/test)
│   ├── valu-demo.tsx       # Valu Social demo (/valu-demo)
│   └── merkos-demo.jsx     # Merkos Platform demo (/merkos-demo)
│
├── components/
│   ├── ui/                 # 49 Radix UI + shadcn/ui components
│   │   ├── accordion.tsx   ├── navigation-menu.tsx
│   │   ├── alert.tsx       ├── pagination.tsx
│   │   ├── avatar.tsx      ├── popover.tsx
│   │   ├── badge.tsx       ├── progress.tsx
│   │   ├── button.tsx      ├── radio-group.tsx
│   │   ├── card.tsx        ├── select.tsx
│   │   ├── carousel.tsx    ├── sheet.tsx
│   │   ├── chart.tsx       ├── skeleton.tsx
│   │   ├── checkbox.tsx    ├── slider.tsx
│   │   ├── dialog.tsx      ├── switch.tsx
│   │   ├── drawer.tsx      ├── table.tsx
│   │   ├── form.tsx        ├── tabs.tsx
│   │   ├── input.tsx       ├── toast.tsx
│   │   └── 30+ more...     └── tooltip.tsx
│   ├── layout/             # Layout components
│   │   ├── Layout.jsx      # Main layout wrapper
│   │   ├── Header.jsx      # Navigation header
│   │   └── Footer.jsx      # Footer component
│   ├── merkos/             # Merkos Platform components
│   │   ├── MerkosConnectionStatus.tsx
│   │   ├── MerkosLoginForm.tsx
│   │   └── MerkosOrganizationSelector.tsx
│   ├── valu/               # Valu API components
│   │   ├── ValuConnectionStatus.tsx
│   │   └── ValuApiProvider.tsx
│   └── NoSSR.tsx           # No SSR wrapper component
│
├── hooks/                  # Custom React hooks
│   ├── useToast.ts         # Toast notifications
│   ├── useMerkosApi.ts     # Main Merkos API hook
│   ├── useMerkosAuth.ts    # Authentication hook
│   ├── useMerkosCampaigns.ts # Campaigns hook
│   ├── useMerkosForms.ts   # Forms management hook
│   ├── useMerkosOrganizations.ts # Organizations hook
│   ├── useMerkosSalesforce.ts # Salesforce integration
│   ├── useValuApi.ts       # Valu API hook
│   └── use-mobile.tsx      # Mobile detection
│
├── contexts/               # React contexts
│   ├── MerkosApiContext.tsx # Merkos API provider (legacy)
│   ├── SimpleAuthContext.tsx # Simplified authentication provider
│   └── ValuApiContext.tsx   # Valu API provider
│
├── api/                    # API client implementations
│   └── merkos/             # Merkos Platform API
│       ├── client.ts       # Base API client
│       ├── auth.ts         # Authentication service
│       ├── campaigns.ts    # Campaigns service
│       ├── forms.ts        # Forms service
│       ├── organizations.ts # Organizations service
│       ├── salesforce.ts   # Salesforce service
│       └── types.ts        # TypeScript types
│
├── lib/                    # Core utilities
│   ├── utils.ts            # Utility functions
│   ├── valu-logger.ts      # Valu API logger
│   └── fonts.ts            # Font configurations
│
├── styles/                 # Styling
│   ├── globals.css         # Global styles + Tailwind
│   └── App.css             # Additional styles
│
├── public/                 # Static assets
│   ├── images/             # Image files
│   ├── icons/              # Favicons and app icons
│   └── README.md           # Static assets docs
│
├── __tests__/              # Test files
│   ├── test-utils.ts       # Test utilities
│   ├── components/         # Component tests
│   ├── hooks/              # Hook tests
│   ├── contexts/           # Context tests
│   └── api/                # API tests
│
├── types/                  # TypeScript definitions
│   └── index.ts            # Global type definitions
│
├── .claude/                # Claude assistant files
│   ├── sessions/           # Development sessions
│   ├── commands/           # Custom commands
│   └── settings.local.json # Local settings
│
# Configuration Files
├── package.json            # Dependencies & scripts
├── tsconfig.json           # TypeScript config
├── next.config.js          # Next.js config
├── tailwind.config.js      # Tailwind CSS config
├── jest.config.mjs         # Jest testing config
├── jest.setup.js           # Jest setup
├── components.json         # UI components config
├── postcss.config.js       # PostCSS config
├── .eslintrc.json          # ESLint rules
├── CLAUDE.md               # Claude assistant docs
├── README.md               # Project documentation
└── PRD.md                  # Product requirements

Key Files to Understand:

  • pages/_app.tsx - App wrapper that provides global layout (TypeScript)
  • pages/api/contact.ts - Serverless API endpoint for contact form (TypeScript)
  • components/ui/ - 49 reusable UI components library
  • hooks/useMerkosApi.ts - Main hook for Merkos Platform integration
  • contexts/MerkosApiContext.tsx - Merkos API context provider
  • api/merkos/client.ts - Merkos Platform API client
  • components.json - UI components configuration
  • tsconfig.json - TypeScript configuration for Next.js
  • jest.config.mjs - Jest testing configuration with TypeScript support
  • CLAUDE.md - Instructions for Claude Code assistant
Local Development

Prerequisites

  • Node.js (v18 or newer)
  • npm, yarn, or pnpm

Getting Started

# 1. Clone the repository
git clone <your-repo-url>
cd chabaduniverse-starter-kit

# 2. Install dependencies
npm install

# 3. Run the development server
npm run dev

# 4. Build for production
npm run build

# 5. Start production server
npm start

# 6. Run linting
npm run lint

Open http://localhost:3000 (Next.js default port) in your browser to see the result.

Development Commands:

  • npm run dev - Start Next.js development server (http://localhost:3000)
  • npm run build - Build for production
  • npm start - Start production server
  • npm run export - Export static site
  • npm run new - Create new project instance
  • npm run lint - Run ESLint
  • npm run type-check - Run TypeScript type checking
  • npm run format - Format code with Prettier
  • npm run format:check - Check code formatting without fixing
  • npm test - Run all unit tests
  • npm run test:watch - Run tests in watch mode
  • npm run test:coverage - Generate test coverage report
  • npm run test:ci - Run tests in CI mode
Development Guidelines

Routing & Navigation

  • Use Next.js Link: import Link from 'next/link'
  • Link Syntax: <Link href="/path">Text</Link>
  • File-based routing: Create files in pages/ directory

Import Patterns

  • Relative imports: ../components/ui/button
  • File extensions: Include .jsx for React components
  • API routes: Place in pages/api/ directory
  • Static assets: Reference from public/ as /images/logo.png

Static Assets

  • Location: Store all static files in public/ directory
  • Images: Place in public/images/ for organization
  • Icons: Use public/icons/ for favicons and app icons
  • Access: Reference as /images/file.png (no public prefix)
  • Next.js Image: Use <Image src="/images/logo.png" alt="Logo" />

Component Standards

  • Functional components with hooks
  • Apple-inspired design: Clean, minimal, elegant whitespace
  • shadcn/ui patterns: Use existing UI component structure
  • Responsive design: Mobile-first with Tailwind CSS

Styling Conventions

  • Tailwind CSS: Primary styling approach
  • Class composition: Use cn() utility from @/lib/utils
  • Design system: Follow existing color scheme (blue/indigo gradients)
  • Typography: Clean, modern font stack defined in Layout.jsx
Code Quality & Formatting

Prettier Configuration

The project uses Prettier for consistent code formatting across all files:

// .prettierrc
{
  "semi": true,
  "trailingComma": "es5",
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "bracketSpacing": true,
  "arrowParens": "avoid",
  "endOfLine": "lf",
  "jsxSingleQuote": true
}

Git Hooks with Husky

Husky is configured to run code quality checks before commits:

  • Pre-commit hook: Runs lint-staged to format and lint only staged files
  • Automatic formatting: Prettier formats code on commit
  • Linting: ESLint checks and fixes issues on commit

Lint-staged Configuration

The project runs different commands based on file types:

// package.json - lint-staged config
"lint-staged": {
  "*.{js,jsx,ts,tsx}": [
    "prettier --write",
    "eslint --fix"
  ],
  "*.{json,css,md}": [
    "prettier --write"
  ]
}

Formatting Commands

  • npm run format - Format all files with Prettier
  • npm run format:check - Check formatting without making changes
TypeScript Integration

Hybrid TypeScript Architecture

This project uses a hybrid TypeScript/JavaScript architecture that provides type safety for core application logic while maintaining flexibility for complex UI components.

TypeScript Configuration

The project includes a comprehensive TypeScript setup optimized for Next.js:

// tsconfig.json - Next.js TypeScript configuration
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "es6"],
    "allowJs": true,           // Allow JavaScript files
    "skipLibCheck": true,
    "strict": false,           // Gradual adoption approach
    "noImplicitAny": false,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [{"name": "next"}],
    "baseUrl": ".",
    "paths": {"@/*": ["./*"]}
  },
  "include": [
    "next-env.d.ts",
    "types/**/*.d.ts", 
    "**/*.ts",
    "**/*.tsx",
    ".next/types/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "**/*.test.ts",           // Test files excluded for pragmatic approach
    "**/*.test.tsx", 
    "**/__tests__/**/*"
  ]
}

File Type Strategy

  • TypeScript (.ts/.tsx): API routes, hooks, utilities, contexts, and core business logic
  • JavaScript (.js/.jsx): Complex UI components, pages, and presentation layer
  • Gradual Migration: Core functionality prioritized for type safety

TypeScript Files in the Project

  • pages/api/contact.ts - Contact form API with proper Next.js types
  • pages/_app.tsx - Main app component with AppProps typing
  • hooks/*.ts - All custom hooks with proper typing
  • contexts/*.tsx - React contexts with TypeScript interfaces
  • api/merkos/*.ts - Merkos API client with comprehensive typing
  • lib/utils.ts - Utility functions with proper type definitions
  • components/ui/button.tsx - UI components with polymorphic typing

Type Definitions

The project includes comprehensive type definitions for:

// API Response Types
interface ContactResponse {
  success: boolean;
  message: string;
  data?: ContactFormData;
  error?: string;
}

// Component Props with Generics
interface ButtonProps<T extends React.ElementType = 'button'> {
  as?: T;
  variant?: ButtonVariant;
  size?: ButtonSize;
  children: React.ReactNode;
}

// API Client Types  
interface ApiClient {
  get<T>(endpoint: string): Promise<T>;
  post<T>(endpoint: string, data: any): Promise<T>;
  put<T>(endpoint: string, data: any): Promise<T>;
  delete<T>(endpoint: string): Promise<T>;
}

Jest Testing with TypeScript

The testing setup includes TypeScript support:

  • Test files (.test.ts/.test.tsx): TypeScript test files are supported
  • Mock typing: Proper typing for Jest mocks and test utilities
  • Test utilities: TypeScript helper functions in __tests__/test-utils.ts
  • Pragmatic approach: Test files excluded from strict TypeScript checking

Development Experience

  • IDE Support: Full IntelliSense and type checking in VS Code
  • Error Prevention: Catch type errors at compile time
  • Refactoring Safety: Confident refactoring with type checking
  • API Safety: Type-safe API calls and responses
  • Component Props: Comprehensive prop validation

Build Process

TypeScript is fully integrated into the Next.js build process:

# TypeScript compilation happens automatically
npm run build    # Includes TypeScript checking
npm run dev      # Hot reload with TypeScript support
npm run lint     # ESLint with TypeScript rules

Migration Strategy

The current hybrid approach allows for gradual TypeScript adoption:

  • Phase 1 (Complete): Core APIs, hooks, and utilities migrated to TypeScript
  • Phase 2 (Optional): UI components can be migrated as needed
  • Phase 3 (Future): Enable stricter TypeScript settings gradually

Best Practices

  • Type imports: Use import type for type-only imports
  • Interface naming: Use PascalCase for interfaces (ContactFormData)
  • Generic components: Use generics for reusable component patterns
  • API typing: Always type API request/response interfaces
  • Null safety: Handle undefined/null cases explicitly
Note: Test files are currently excluded from TypeScript checking for a pragmatic development approach. This allows focus on application logic while maintaining test functionality.
Component Library

This starter kit includes 49 professionally designed, accessible UI components built with Radix UI primitives and styled with Tailwind CSS. All components follow shadcn/ui patterns for consistency and customizability.

Available Components

Layout Components
  • Card - Container component with header and content areas
  • Separator - Visual divider between content sections
  • Aspect Ratio - Maintains consistent aspect ratios for media
  • Scroll Area - Custom scrollable container with styled scrollbars
  • Resizable - Panels that can be resized by dragging
Form Components
  • Input - Text input field with variants
  • Textarea - Multi-line text input
  • Select - Dropdown selection component
  • Checkbox - Single checkbox with label
  • Radio Group - Set of radio buttons
  • Switch - Toggle switch component
  • Slider - Range slider input
  • Input OTP - One-time password input
  • Form - Form wrapper with React Hook Form integration
  • Label - Accessible form labels
Navigation Components
  • Navigation Menu - Complex dropdown navigation
  • Breadcrumb - Breadcrumb trail navigation
  • Tabs - Tabbed interface component
  • Pagination - Page navigation controls
  • Command - Command palette (cmd+k style)
  • Context Menu - Right-click context menus
  • Dropdown Menu - Dropdown menu component
  • Menubar - Application menubar
Feedback Components
  • Alert - Alert messages with variants
  • Alert Dialog - Confirmation dialogs
  • Toast - Toast notifications
  • Toaster - Toast notification container
  • Sonner - Enhanced toast notifications
  • Progress - Progress bar indicator
  • Skeleton - Loading skeleton placeholders
  • Badge - Status badges and labels
Overlay Components
  • Dialog - Modal dialog windows
  • Sheet - Slide-out panel from edges
  • Drawer - Mobile-friendly drawer (vaul)
  • Popover - Floating content panels
  • Tooltip - Hover tooltips
  • Hover Card - Rich hover content
Data Display
  • Table - Data table with sorting/filtering
  • Avatar - User avatar component
  • Chart - Chart components (via recharts)
  • Carousel - Image/content carousel
  • Calendar - Date picker calendar
  • Accordion - Collapsible content sections
  • Collapsible - Simple collapsible container
Utility Components
  • Button - Button with multiple variants and sizes
  • Toggle - Toggle button component
  • Toggle Group - Group of toggle buttons

Using Components

// Import components from the ui directory
import { Button } from '@/components/ui/button'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'

// Use with shadcn/ui patterns
<Card>
  <CardHeader>
    <CardTitle>Example Card</CardTitle>
  </CardHeader>
  <CardContent>
    <Button variant="outline" size="sm">
      Click me
    </Button>
  </CardContent>
</Card>

Component Customization

All components are built with customization in mind:

  • Variants: Most components support multiple visual variants
  • Sizes: Consistent sizing system (sm, md, lg, xl)
  • Styling: Override with className prop using Tailwind classes
  • Composition: Components are composable and work together
  • Accessibility: Built on Radix UI for full accessibility support

Component Configuration

Components are configured in components.json:

{
  "style": "default",
  "rsc": true,
  "tsx": true,
  "tailwind": {
    "config": "tailwind.config.js",
    "css": "styles/globals.css",
    "baseColor": "slate",
    "cssVariables": true
  },
  "aliases": {
    "components": "@/components",
    "utils": "@/lib/utils"
  }
}
Adding New Features

Adding New Pages

  1. Create file in pages/ directory (e.g., pages/new-page.js)
  2. Export default React component wrapped with Layout
  3. Update navigation in Header.jsx if needed

Adding New API Routes

  1. Create file in pages/api/ directory
  2. Export default function that handles request/response
  3. Follow Next.js API route patterns

Adding New UI Components

  1. Follow shadcn/ui patterns in components/ui/
  2. Use Radix UI primitives where appropriate
  3. Maintain consistent styling with existing components

Form Integration

  1. Use React Hook Form for form state
  2. Add Zod schema for validation
  3. Submit to API routes with proper error handling
Demo Pages Guide

This starter kit includes several demo pages that showcase the integrated features and provide interactive testing interfaces for various API integrations.

Available Demo Pages

/api-demo - API Testing Interface

A comprehensive API testing page that allows you to experiment with various API endpoints and see real-time responses.

  • Test contact form API submissions
  • View request/response data
  • Experiment with different payloads
  • Monitor API performance
/merkos-demo - Merkos Platform Integration

Interactive demo showcasing the Merkos Platform API integration with simplified authentication and multiple tabs for different features:

  • Authentication Tab: Test all login methods (username/password, Google OAuth, Chabad.org SSO, Bearer Token) using simplified authentication
  • Organizations Tab: Simplified demo mode with API test buttons
  • Campaigns Tab: Demo functionality with placeholder API operations
  • Forms Tab: Demo form builder interface with simulated operations
  • Salesforce Tab: Demo CRM integration with test functionality
  • API Testing: Run simplified API tests with demo responses
  • Responsive Design: Fully mobile-responsive navigation tabs that stack properly on narrow screens
/valu-demo - Valu Social Integration

Demo page for testing Valu Social platform integration when running as an iframe:

  • Connection Status: Real-time connection state monitoring
  • Quick Actions: One-click buttons for common operations (open chat, channels)
  • Console Commands: Interactive command testing interface
  • Event Log: Live stream of all API events and responses
  • Channel Controls: Test opening specific chat channels with custom parameters
/test - Component Testing Page

A dedicated page for testing various UI components and features in isolation:

  • Component showcase with different states
  • Form validation testing
  • Layout experiments
  • Performance testing

Using Demo Pages

// Access demo pages directly in development
http://localhost:3000/api-demo
http://localhost:3000/merkos-demo
http://localhost:3000/valu-demo
http://localhost:3000/test

// Demo pages are TypeScript-enabled for type safety
// Source files:
pages/api-demo.tsx
pages/merkos-demo.jsx
pages/valu-demo.tsx
pages/test.tsx

Demo Page Features

  • Real-time Updates: See live data as you interact with APIs
  • Error Handling: Graceful error states with helpful messages
  • State Persistence: Some demos maintain state between page refreshes
  • Mobile Responsive: All demos work on mobile devices
  • Documentation: In-page help and API documentation

Security Considerations

Important: Demo pages are intended for development and testing only. Consider disabling or protecting these routes in production environments to prevent unauthorized API access.

Customizing Demo Pages

You can extend or modify demo pages for your specific needs:

  • Add New Demos: Create new pages in the pages/ directory
  • Modify Existing: Demo pages use standard React components
  • Integrate Features: Use hooks and contexts from the codebase
  • Style Consistently: Follow the existing UI component patterns
Testing & Quality Assurance

Unit Testing Setup

This project includes a comprehensive unit testing setup using Jest and React Testing Library, configured specifically for Next.js applications.

Testing Dependencies

  • Jest 30.0.4: JavaScript testing framework
  • React Testing Library 16.3.0: Simple and complete testing utilities for React components
  • Jest DOM 6.6.3: Custom Jest matchers for DOM assertions
  • User Event 14.6.1: Fire events the same way the user does
  • Node Mocks HTTP 1.17.2: Mock HTTP requests for API route testing

Testing Commands

# Run all tests once
npm test

# Run tests in watch mode (auto-reruns on file changes)
npm run test:watch

# Generate coverage report
npm run test:coverage

# Run tests in CI mode (no watch, coverage included)
npm run test:ci

Test Configuration

The testing setup includes:

  • jest.config.js: Next.js-optimized Jest configuration with path mapping
  • jest.setup.js: Global test setup with mocks for Next.js components
  • Coverage thresholds: 70% minimum coverage for branches, functions, lines, and statements
  • Environment mocks: window.matchMedia, IntersectionObserver, ResizeObserver

Available Test Files

  • Header Component Tests: Navigation, mobile menu, styling, accessibility
  • Button Component Tests: Variants, sizes, event handling, forwarded refs
  • Contact API Tests: Request validation, error handling, CORS, success cases
  • Utils Function Tests: Class name composition utility testing

Writing New Tests

Follow these patterns when adding tests:

// Component test example
import React from 'react'
import { render, screen, fireEvent } from '@testing-library/react'
import MyComponent from '../MyComponent'

describe('MyComponent', () => {
  test('renders correctly', () => {
    render(<MyComponent />)
    expect(screen.getByText('Expected Text')).toBeInTheDocument()
  })

  test('handles user interaction', () => {
    const mockFn = jest.fn()
    render(<MyComponent onClick={mockFn} />)
    
    fireEvent.click(screen.getByRole('button'))
    expect(mockFn).toHaveBeenCalledTimes(1)
  })
})

API Route Testing

// API test example
import { createMocks } from 'node-mocks-http'
import handler from '../api/my-endpoint'

describe('/api/my-endpoint', () => {
  test('handles POST request', async () => {
    const { req, res } = createMocks({
      method: 'POST',
      body: { data: 'test' },
    })

    await handler(req, res)

    expect(res._getStatusCode()).toBe(200)
    const data = JSON.parse(res._getData())
    expect(data.success).toBe(true)
  })
})

Test Structure Guidelines

  • Location: Place tests in __tests__ directories or use .test.jsx suffix
  • Naming: Use descriptive test names that explain what is being tested
  • Organization: Group related tests in describe blocks
  • Mocking: Mock external dependencies (API calls, Next.js router, etc.)
  • Coverage: Aim for 70%+ coverage on all metrics

Continuous Integration

The testing setup is CI-ready with the test:ci command that:

  • Runs all tests without watch mode
  • Generates coverage reports
  • Exits with proper status codes for CI/CD pipelines
  • Works with GitHub Actions, GitLab CI, and other CI services

Best Practices

  • Test user behavior: Focus on testing what users see and do
  • Avoid implementation details: Test the interface, not the internals
  • Use semantic queries: Prefer getByRole, getByLabelText, etc.
  • Mock sparingly: Only mock what you need to isolate the unit under test
  • Test error cases: Include tests for error handling and edge cases
MongoDB Database Integration

Overview

The starter kit includes complete MongoDB integration using Mongoose ODM, providing a robust database layer for your application. The setup includes connection management, TypeScript-based models, and production-ready configuration.

Configuration

Set up your MongoDB connection by adding the connection string to your environment variables:

# .env file
MONGODB_URI=mongodb://localhost:27017/chabaduniverse

# For MongoDB Atlas (cloud)
MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/database

Connection Management

The MongoDB connection is managed in lib/mongodb.ts with features including:

  • Connection Pooling: Efficient connection reuse and management
  • Hot Reload Support: Cached connections during development
  • Error Handling: Comprehensive error handling and logging
  • Graceful Shutdown: Proper cleanup on application termination
  • Connection Status: Real-time connection monitoring

Database Models

Two example models are provided to demonstrate best practices:

  • User Model: Full-featured user model with authentication integration
  • Contact Model: Contact form submissions with status tracking
User Model Features
// models/User.ts
const userSchema = new Schema({
  email: { type: String, required: true, unique: true },
  username: { type: String, unique: true, sparse: true },
  name: String,
  role: { type: String, enum: ['user', 'admin', 'moderator'] },
  authProvider: { type: String, enum: ['local', 'google', 'chabad', 'bearer'] },
  organizations: [String],
  lastLogin: Date,
  isActive: { type: Boolean, default: true }
}, { timestamps: true })
Contact Model Features
// models/Contact.ts
const contactSchema = new Schema({
  name: { type: String, required: true },
  email: { type: String, required: true },
  subject: String,
  message: { type: String, required: true },
  status: { type: String, enum: ['unread', 'read', 'replied', 'archived'] },
  userId: { type: Schema.Types.ObjectId, ref: 'User' }
}, { timestamps: true })

Using Models in Your Code

import dbConnect from '@/lib/mongodb'
import { User, Contact } from '@/models'

// In API routes or server-side code
export default async function handler(req, res) {
  // Connect to database
  await dbConnect()
  
  // Create a new user
  const user = await User.create({
    email: 'user@example.com',
    name: 'John Doe',
    authProvider: 'local'
  })
  
  // Find users
  const users = await User.find({ isActive: true })
  
  // Update user
  await User.findByIdAndUpdate(userId, { lastLogin: new Date() })
}

Best Practices

  • Always connect first: Call dbConnect() before any database operations
  • Use TypeScript: Leverage TypeScript interfaces for type safety
  • Index important fields: Add indexes for frequently queried fields
  • Validate input: Use Mongoose validation for data integrity
  • Handle errors: Implement proper error handling for database operations
GraphQL API Integration

Overview

The starter kit includes a complete GraphQL API implementation using Apollo Server and Apollo Client. This provides a modern, type-safe API layer with real-time capabilities and efficient data fetching.

GraphQL Server

The GraphQL server is available at /api/graphql with features including:

  • Apollo Server: Production-ready GraphQL server
  • Type Definitions: Modular schema with User and Contact types
  • Resolvers: Full CRUD operations with authentication
  • GraphQL Playground: Interactive API explorer at /graphql-playground
  • Authentication: Integrated with SimpleAuthContext

Available Queries

# Get current user
query Me {
  me {
    id
    email
    name
    role
    authProvider
  }
}

# Get server info
query ServerInfo {
  serverInfo {
    version
    environment
    mongoStatus {
      isConnected
    }
  }
}

# Get contact statistics (admin only)
query ContactStats {
  contactStats {
    unread
    read
    replied
    total
  }
}

Available Mutations

# Submit contact form
mutation SubmitContact($input: CreateContactInput!) {
  submitContact(input: $input) {
    id
    name
    email
    message
    status
  }
}

# Update user profile
mutation UpdateProfile($input: UpdateUserInput!) {
  updateProfile(input: $input) {
    id
    name
    email
  }
}

Apollo Client Setup

The Apollo Client is configured in lib/apollo-client.ts with:

  • Authentication: Automatic token inclusion from localStorage
  • Error Handling: Global error handling with retry logic
  • Caching: InMemoryCache with type policies
  • DevTools: Apollo DevTools support in development

Using GraphQL in Components

import { useQuery, useMutation, gql } from '@apollo/client'

// Define queries/mutations
const ME_QUERY = gql`
  query Me {
    me {
      id
      email
      name
    }
  }
`

const SUBMIT_CONTACT = gql`
  mutation SubmitContact($input: CreateContactInput!) {
    submitContact(input: $input) {
      id
      message
    }
  }
`

// Use in component
function MyComponent() {
  // Query data
  const { data, loading, error } = useQuery(ME_QUERY)
  
  // Mutation
  const [submitContact] = useMutation(SUBMIT_CONTACT, {
    onCompleted: (data) => {
      console.log('Contact submitted:', data)
    }
  })
  
  const handleSubmit = (formData) => {
    submitContact({ 
      variables: { 
        input: formData 
      } 
    })
  }
  
  if (loading) return <p>Loading...</p>
  if (error) return <p>Error: {error.message}</p>
  
  return <div>{data?.me?.name}</div>
}

Authorization

The GraphQL API implements role-based access control:

  • Public: Health check, server info, contact submission
  • Authenticated: User profile queries and updates
  • Admin/Moderator: User management, contact viewing
  • Admin Only: User deletion, system statistics

Testing GraphQL

Visit the GraphQL demo page at /graphql-demo to:

  • Test queries and mutations interactively
  • View real-time server and database status
  • Submit test contact forms
  • Access the GraphQL Playground

Best Practices

  • Use fragments: Share common fields across queries
  • Error boundaries: Implement error boundaries for GraphQL components
  • Optimistic updates: Use optimistic responses for better UX
  • Batch queries: Combine related queries for efficiency
  • Type generation: Consider using GraphQL Code Generator for types
Valu Social Integration

Overview

This application includes full integration with the Valu Social platform through the @arkeytyp/valu-api package. When running as an iframe within Valu Social, the app can communicate with the parent application to access various features and services.

Valu API Features

  • Iframe Detection: Automatically detects when running inside Valu Social
  • API Communication: Secure message-based communication with parent app
  • Event System: Subscribe to and emit events across the iframe boundary
  • Console Commands: Execute Valu Social commands programmatically
  • Version Support: API versioning for backward compatibility

Available Components

  • useValuApi Hook: React hook for accessing Valu API functionality
  • ValuApiProvider: Context provider for app-wide API access
  • ValuConnectionStatus: Visual connection status indicator
  • Demo Page: Interactive testing interface at /valu-demo

Basic Usage

// Using the Valu API hook
import { useValuApiContext } from '../contexts/ValuApiContext'

function MyComponent() {
  const { 
    isInIframe, 
    isConnected, 
    isReady, 
    openTextChat, 
    runConsoleCommand 
  } = useValuApiContext()

  const handleOpenChat = async () => {
    if (isReady) {
      await openTextChat()
    }
  }

  return (
    <div>
      <p>Status: {isConnected ? 'Connected' : 'Disconnected'}</p>
      <button onClick={handleOpenChat}>Open Chat</button>
    </div>
  )
}

Available API Methods

  • openTextChat(): Opens the Valu text chat interface
  • openChannel(roomId, propId): Opens a specific chat channel
  • runConsoleCommand(command): Executes console commands
  • getApiPointer(apiName, version): Gets API pointer for specific modules
  • subscribeToEvents(apiName, eventName, handler): Subscribe to API events

Console Commands

Test various Valu Social features using console commands:

// Open text chat
await runConsoleCommand('app open text_chat')

// Open specific channel  
await runConsoleCommand('chat open-channel roomId xyz123 propId abc456')

// Get help for app API
await runConsoleCommand('app -h')

// Get help for chat API
await runConsoleCommand('chat -h')

Event Handling

// Subscribe to app events
const unsubscribe = await subscribeToEvents('app', 'app-open', (event) => {
  console.log('App opened:', event)
})

// Subscribe to chat events
const unsubscribeChat = await subscribeToEvents('chat', 'message-received', (event) => {
  console.log('New message:', event)
})

// Clean up subscriptions
unsubscribe()
unsubscribeChat()

Connection States

  • Standalone Mode: App running outside of Valu Social (normal web browser)
  • Iframe Detected: App is running inside an iframe but not yet connected
  • Connecting: API connection is being established
  • Connected & Ready: Full API access available
  • Error State: Connection failed or API error occurred

Demo Page Features

Visit /valu-demo to access the interactive testing interface:

  • Connection Status: Real-time connection monitoring
  • Quick Actions: One-click buttons for common operations
  • Console Commands: Interactive command testing with preset commands
  • Event Log: Real-time display of all API events and responses
  • Channel Controls: Test opening specific chat channels

Development vs Production

  • Development: When running locally, the app detects it's not in an iframe and disables Valu features gracefully
  • Production: When deployed and embedded in Valu Social, full API functionality is available
  • Fallback Behavior: All Valu-dependent features degrade gracefully when not available

Testing Valu Integration

The integration includes comprehensive unit tests covering:

  • Hook Testing: useValuApi hook with mocked Valu API
  • Context Testing: ValuApiProvider and context consumption
  • Component Testing: ValuConnectionStatus component states
  • Error Handling: Network failures and API errors
  • Event System: Event subscription and cleanup
Important: Valu API functionality is only available when the application is running as an iframe within the Valu Social platform. When developing locally or running standalone, the API gracefully degrades to a non-connected state.
Merkos Platform API Integration

Overview

This application includes comprehensive integration with the Merkos Platform API, providing access to user management, organization operations, campaign management, form building, and Salesforce CRM integration within the Chabad network.

Merkos API Features

  • Simplified Authentication: Streamlined authentication using SimpleAuthContext with support for username/password, Google OAuth, Chabad.org SSO, and Bearer Token methods
  • Organization Management: Role-based access control and multi-tenant architecture (demo mode)
  • Campaign Management: Fundraising campaigns with member tracking and analytics (demo mode)
  • Form Builder: Dynamic form creation with submission management (demo mode)
  • Salesforce Integration: CRM data synchronization and SOQL queries (demo mode)
  • JWT Authentication: Bearer token authentication with secure token handling
  • Responsive UI: Mobile-first design with responsive navigation and forms

Complete API Documentation

For comprehensive API documentation including all endpoints, authentication methods, request/response formats, and examples, see the complete Merkos Platform API Documentation.

Available Services

  • Users Service: Authentication, user management, and group operations
  • Organizations Service: Organization management, user roles, and permissions
  • Campaigns Service: Campaign creation, member management, and analytics
  • Forms Service: Form builder, submissions, and public form access
  • Salesforce Service: CRM integration and data operations

React Integration

The Merkos API is integrated with React through a simplified authentication system using SimpleAuthContext:

// Using the simplified auth hook
import { useSimpleAuth } from '../contexts/SimpleAuthContext'

function MyComponent() {
  const { 
    isAuthenticated, 
    isLoading,
    error,
    user, 
    token,
    loginWithCredentials,
    loginWithBearerToken,
    logout 
  } = useSimpleAuth()

  const handleLogin = async () => {
    try {
      await loginWithCredentials('username', 'password')
      console.log('Login successful')
    } catch (error) {
      console.error('Login failed:', error)
    }
  }

  const handleBearerLogin = async () => {
    try {
      await loginWithBearerToken('your-jwt-token')
      console.log('Bearer authentication successful')
    } catch (error) {
      console.error('Bearer auth failed:', error)
    }
  }

  return (
    <div>
      <h2>User: {user?.name || user?.email || 'Not logged in'}</h2>
      <p>Status: {isAuthenticated ? 'Connected' : 'Disconnected'}</p>
      <button onClick={handleLogin}>Login with Credentials</button>
      <button onClick={handleBearerLogin}>Login with Bearer Token</button>
      <button onClick={logout}>Logout</button>
    </div>
  )
}

Authentication Examples

// Multiple authentication methods with simplified auth
const { 
  loginWithCredentials, 
  loginWithGoogle, 
  loginWithChabadOrg, 
  loginWithBearerToken,
  logout 
} = useSimpleAuth()

// Username/password authentication
await loginWithCredentials('username', 'password', 'siteId')

// Google OAuth authentication
await loginWithGoogle('google-auth-code', 'hostname', 'siteId')

// Chabad.org authentication
await loginWithChabadOrg('chabad-org-key', 'siteId')

// Bearer token authentication (JWT)
await loginWithBearerToken('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...', 'siteId')

// Logout
await logout()

Organization Operations

// Organization management
const { organizations } = useMerkosApi()

// List organizations
const orgList = await organizations.listOrganizations()

// Search organizations
const searchResults = await organizations.searchOrganizations('search-term', {
  type: 'nonprofit',
  region: 'north-america'
})

// User management within organization
const users = await organizations.listUsers()
const newUser = await organizations.createUser({
  name: 'John Doe',
  email: 'john@example.com',
  roles: ['member']
})

// Department management
const departments = await organizations.listDepartments()
const newDept = await organizations.createDepartment({
  name: 'IT Department',
  description: 'Information Technology',
  head: 'user-id'
})

Campaign Management

// Campaign operations
const { campaigns } = useMerkosApi()

// Create campaign
const newCampaign = await campaigns.createCampaign({
  name: 'Fundraising Campaign 2024',
  description: 'Annual fundraising campaign',
  goal: 50000,
  startDate: '2024-01-01',
  endDate: '2024-12-31',
  type: 'fundraising'
})

// Manage campaign members
const members = await campaigns.listMembers(campaignId)
await campaigns.addMember(campaignId, {
  userId: 'user-id',
  role: 'member',
  target: 1000
})

// Get analytics
const analytics = await campaigns.getCampaignAnalytics(campaignId)
const leaderboard = await campaigns.getLeaderboard(campaignId, 10)

Form Builder Integration

// Form operations
const { forms } = useMerkosApi()

// Create form
const newForm = await forms.createForm({
  name: 'Contact Form',
  description: 'Customer contact form',
  questions: [
    {
      type: 'text',
      label: 'Name',
      required: true
    },
    {
      type: 'email',
      label: 'Email Address',
      required: true
    }
  ]
})

// Publish form
await forms.publishForm(formId, 'contact-form-slug', true)

// Handle submissions
const submissions = await forms.listSubmissions(formId)
const csvData = await forms.exportSubmissions(formId, 'csv')

Salesforce Integration

// Salesforce operations
const { salesforce } = useMerkosApi()

// Initialize connection
const roomId = salesforce.generateRoomId()
const elmId = salesforce.generateElementId()

await salesforce.initializeConnection(roomId, elmId, {
  objectType: 'Contact',
  fields: ['Id', 'Name', 'Email']
})

// Execute SOQL query
const query = 'SELECT Id, Name, Email FROM Contact LIMIT 10'
const results = await salesforce.executeQuery(roomId, elmId, query)

// CRUD operations
await salesforce.createRecord(roomId, elmId, 'Contact', {
  Name: 'John Doe',
  Email: 'john@example.com'
})

await salesforce.updateRecord(roomId, elmId, 'Contact', 'recordId', {
  Name: 'Jane Doe'
})

Available Components

  • MerkosConnectionStatus: Visual connection status with detailed information using simplified authentication
  • MerkosLoginForm: Multi-method authentication form with responsive design and Bearer Token support
  • MerkosOrganizationSelector: Organization context switching (demo mode)
  • Demo Page: Comprehensive testing interface at /merkos-demo with fully responsive design

Environment Configuration

The API client automatically detects the environment and configures appropriate base URLs with support for custom overrides:

  • Development: http://localhost:3005
  • Staging: https://sandbox.shop.merkos302.com
  • Production: https://shop.merkos302.com

Custom Configuration: Set environment-specific variables to override default URLs:

  • NEXT_PUBLIC_MERKOS_API_URL_DEVELOPMENT - Override development URL
  • NEXT_PUBLIC_MERKOS_API_URL_STAGING - Override staging URL
  • NEXT_PUBLIC_MERKOS_API_URL_PRODUCTION - Override production URL

Note: The NEXT_PUBLIC_ prefix ensures these variables are available on both server and client sides in Next.js.

Error Handling

The integration includes comprehensive error handling with user-friendly messages:

// Error handling example
try {
  await campaigns.createCampaign(campaignData)
} catch (error) {
  // Errors are automatically formatted for user display
  if (error.code === 'AUTHENTICATION_FAILED') {
    showMessage('Please log in to continue')
  } else if (error.code === 'VALIDATION_ERROR') {
    showErrors(error.details)
  } else {
    showMessage('An unexpected error occurred')
  }
}

Testing

The Merkos API integration includes comprehensive unit tests covering:

  • API Client: Request handling, authentication, and error management
  • Authentication Hook: Login methods, token management, and session handling
  • Service Hooks: All organization, campaign, and form operations
  • UI Components: Connection status, login form, and organization selector
  • Context Providers: State management and event handling

Demo Page Features

Visit /merkos-demo to access the interactive testing interface:

  • Authentication Tab: Test all login methods including Bearer Token authentication
  • Organizations Tab: Simplified demo with API test functionality
  • Campaigns Tab: Demo campaign operations with placeholder responses
  • Forms Tab: Demo form builder interface
  • Salesforce Tab: Demo CRM integration functionality
  • API Testing: Run simplified API tests with demo responses
  • Responsive Design: Navigation tabs that stack properly on mobile devices
  • Event Log: Disabled in simplified mode with appropriate messaging
Important: The Merkos Platform API requires valid authentication credentials. Contact your system administrator for access to the API and organization identifiers.
Merkos API Client Package

Overview

The Merkos Platform API integration has been extracted into a standalone TypeScript/JavaScript package located at packages/merkos-api-client/. This modular approach improves code organization, reusability, and maintainability while maintaining 100% backward compatibility.

Package Features

  • Complete Type Safety: Full TypeScript definitions for all API operations
  • Zero Dependencies: Lightweight with only peer dependency on fetch
  • Multiple Build Formats: CommonJS, ES Modules, and TypeScript definitions
  • Comprehensive Testing: 100% test coverage with Jest
  • Professional Documentation: Detailed README with examples
  • Backward Compatible: Existing imports continue to work unchanged

Package Structure

packages/merkos-api-client/
├── src/                    # Source code
│   ├── client/            # Core API client
│   ├── services/          # Service modules
│   │   ├── users.ts       # Authentication
│   │   ├── organizations.ts
│   │   ├── campaigns.ts
│   │   ├── forms.ts
│   │   └── salesforce.ts
│   └── types/             # TypeScript types
├── tests/                 # Test suite
├── dist/                  # Built output
└── README.md             # Documentation

Using the Package

The package can be imported directly from its location in the monorepo:

// Import the main client
import { merkosApiClient } from '../packages/merkos-api-client/src';

// Import specific services
import { 
  usersService,
  organizationsService,
  campaignsService,
  formsService,
  salesforceService
} from '../packages/merkos-api-client/src';

// Import types
import type {
  User,
  Organization,
  Campaign,
  AuthResponse
} from '../packages/merkos-api-client/src/types';

Backward Compatibility

All existing imports through api/merkos/ continue to work:

// These imports still work (backward compatibility)
import { merkosApiClient } from '../api/merkos/client';
import organizationsService from '../api/merkos/organizations';

// They now re-export from the package
export { merkosApiClient } from '../../packages/merkos-api-client/src';

Building the Package

cd packages/merkos-api-client

# Install dependencies
npm install

# Build all formats
npm run build

# Run tests
npm test

# Generate coverage report
npm run test:coverage

Key Benefits

  • Modularity: Clean separation of API logic from application code
  • Reusability: Can be used in multiple projects
  • Type Safety: Complete TypeScript coverage with strict typing
  • Testing: Isolated test suite with mocks and fixtures
  • Documentation: Comprehensive API documentation and examples
  • Future Publishing: Ready to publish as npm package

Migration Path

While not required due to backward compatibility, you can gradually migrate to direct package imports:

// Step 1: Update imports (optional)
- import { merkosApiClient } from '../../api/merkos/client';
+ import { merkosApiClient } from '../../packages/merkos-api-client/src';

// Step 2: Use new utilities
import { parseJwtToken, isTokenExpired } from '../../packages/merkos-api-client/src';

// Step 3: Leverage TypeScript types
import type { AuthUser, ApiError } from '../../packages/merkos-api-client/src/types';

Package Documentation

For detailed package documentation, see:

  • Package README: /packages/merkos-api-client/README.md
  • Migration Guide: /MIGRATION_GUIDE.md
  • API Documentation: /docs/merkos-api-client.md
Note: The package is currently part of the monorepo and not published to npm. To use it in external projects, you'll need to either copy the package or wait for npm publication.
Deployment

Deploy to Vercel (Recommended)

Vercel provides the best Next.js deployment experience:

  1. Push your code to a Git repository (GitHub, GitLab, etc.)
  2. Sign up for a free Vercel account and connect your Git repository
  3. Vercel will auto-detect Next.js and deploy with zero configuration
  4. All API routes become serverless functions automatically

Other Deployment Options

  • Netlify: Supports Next.js with Edge Functions
  • Railway: Full-stack hosting with database support
  • Docker: Use official Next.js Docker examples
API Integration

Included API Routes

This project includes fully functional API routes in pages/api/ for serverless backend functionality.

Available Endpoints

  • Contact Form API: /api/contact - POST endpoint for contact form submissions
  • Production ready: Includes validation, error handling, and CORS

Using API Routes

// Frontend integration example
const handleSubmit = async (formData) => {
  try {
    const response = await fetch('/api/contact', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(formData),
    });

    if (!response.ok) {
      throw new Error('Failed to submit form');
    }

    const result = await response.json();
    console.log('Success:', result);
  } catch (error) {
    console.error('Error:', error.message);
  }
};

Features Included

  • ✅ Input validation and sanitization
  • ✅ CORS headers for cross-origin requests
  • ✅ Error handling and logging
  • ✅ TypeScript-ready structure
  • ✅ Serverless deployment ready

Adding a Database

Popular choices for Next.js applications:

  • Vercel Postgres: Integrated PostgreSQL database
  • Supabase: PostgreSQL with real-time features
  • PlanetScale: MySQL with branching
  • MongoDB Atlas: NoSQL cloud database
Claude Sessions

Overview

Claude Sessions is a development workflow feature that helps track and document your coding sessions. It automatically creates session files to record progress, goals, and development activities throughout your project work.

Session Management Commands

  • /session-start [description]: Start a new development session
  • /project:session-update: Add progress notes to the current session
  • /project:session-end: Close and finalize the current session

Session File Structure

Session files are stored in .claude/sessions/ with the naming format:

YYYY-MM-DD-HHMM-description.md
# Example: 2025-07-17-1340-implement-claude-sessions.md

Getting Started

# Start a new session with description
/session-start implement new feature

# Start a session without description (uses timestamp only)
/session-start

# Update session with progress notes
/project:session-update

# End the current session
/project:session-end

Session File Format

Each session file contains structured information about your development work:

# Feature Implementation - 2025-07-17 13:40

## Session Overview
**Start Time:** July 17, 2025 at 1:40 PM  
**Session Type:** Feature Implementation  
**Focus:** Implement Claude sessions functionality

## Goals
- Implement Claude sessions system for tracking development work
- Create session file management infrastructure
- Enable session tracking and updates throughout development workflows
- Integrate with existing .claude/ directory structure

## Progress
*Session started - ready for implementation work*

### 13:45 - Initial Setup
- Created .claude/sessions/ directory structure
- Implemented session file creation with timestamp
- Added .current-session tracking file

### 14:20 - Documentation Update
- Added comprehensive Claude Sessions section to documentation
- Included usage examples and session file structure
- Updated with real session data example

---
*Use /project:session-update to add progress notes*  
*Use /project:session-end to close this session*

Session Directory Structure

.claude/
├── sessions/
│   ├── .current-session              # Tracks active session filename
│   ├── 2025-07-17-1340-implement-claude-sessions.md
│   ├── 2025-07-16-0900-fix-navigation-bug.md
│   └── 2025-07-15-1500-add-api-integration.md
└── commands/                         # Other Claude configuration files

Benefits of Using Sessions

  • Progress Tracking: Document what was accomplished in each coding session
  • Context Preservation: Maintain context between development sessions
  • Goal Setting: Define clear objectives for each session
  • Historical Record: Keep a chronological log of project development
  • Team Communication: Share session files to communicate progress
  • Learning Documentation: Record discoveries and solutions for future reference

Best Practices

  • Descriptive Names: Use clear descriptions when starting sessions
  • Regular Updates: Add progress notes throughout your session
  • Clear Goals: Define specific, achievable objectives
  • Document Blockers: Record any obstacles or issues encountered
  • Include Context: Note relevant file paths, functions, and line numbers
  • Close Sessions: Always end sessions to maintain clean records

Example Session Workflow

# 1. Start session for bug fix
/session-start fix contact form validation

# 2. Work on the issue, then update progress
/project:session-update
# Add notes about what was discovered and fixed

# 3. Continue development, add more updates as needed
/project:session-update
# Document testing results and final implementation

# 4. End the session when work is complete
/project:session-end
# Summarize accomplishments and next steps

Integration with Development Workflow

Claude Sessions integrates seamlessly with your existing development process:

  • Git Integration: Session files can be committed to track development history
  • Issue Tracking: Reference issue numbers and ticket IDs in session notes
  • Code Reviews: Use session files to provide context for pull requests
  • Documentation: Sessions serve as informal documentation of changes
  • Debugging: Track investigation steps and solution approaches
Note: Session files are stored locally in your project directory. Consider committing them to your repository to share development context with your team, or add .claude/sessions/ to .gitignore if you prefer to keep sessions private.
Claude Subagents

Overview

Claude Subagents are specialized AI assistants that enhance your development workflow by providing expert knowledge in specific domains. Each subagent has focused expertise, uses its own context window, and can be invoked automatically or explicitly.

Available Subagents

The ChabadUniverse Starter Kit includes 9 specialized subagents tailored to the project:

Core Development Subagents
  • nextjs-component-creator: Expert in creating React components with shadcn/ui patterns, responsive design, and the project's hybrid TypeScript/JSX architecture.
  • form-builder: Specializes in React Hook Form with Zod validation, creating complete form flows with API integration.
  • test-writer: Writes comprehensive Jest and React Testing Library tests, maintaining 70%+ coverage across all metrics.
  • tailwind-stylist: Optimizes Tailwind CSS classes, implements responsive designs, and maintains the Apple-inspired aesthetic.
  • typescript-migrator: Handles gradual TypeScript adoption following the project's hybrid architecture approach.
  • performance-optimizer: Optimizes Next.js features (SSR, code splitting), improves bundle sizes, and implements React best practices.
API Expert Subagents
  • merkos-api-expert: Deep expertise in Merkos Platform API including JWT authentication, organization management, campaigns, forms, and Salesforce integration.
  • valu-api-expert: Specializes in Valu Social API integration, iframe communication, event-driven architecture, and postMessage protocols.
  • api-integration-specialist: General API integration expert for creating hooks, contexts, error handling, and authentication flows.

Using Subagents

Subagents can be used in two ways:

1. Automatic Delegation

Claude automatically delegates tasks to appropriate subagents based on context. For example, when you ask to create a new component, the nextjs-component-creator subagent will handle it.

2. Explicit Invocation

Request a specific subagent by mentioning it in your command:

# Use specific subagent
"Use the test-writer subagent to add tests for the UserProfile component"
"Have the merkos-api-expert help me implement organization switching"
"Ask the performance-optimizer to analyze our bundle size"

Subagent Location

All project subagents are stored in .claude/agents/ as Markdown files with YAML frontmatter:

.claude/
├── agents/
│   ├── nextjs-component-creator.md
│   ├── form-builder.md
│   ├── test-writer.md
│   ├── tailwind-stylist.md
│   ├── typescript-migrator.md
│   ├── performance-optimizer.md
│   ├── merkos-api-expert.md
│   ├── valu-api-expert.md
│   └── api-integration-specialist.md

Benefits of Using Subagents

  • Specialized Expertise: Each subagent has deep knowledge in its specific domain
  • Faster Development: Subagents provide immediate, accurate solutions for their areas
  • Consistent Patterns: All subagents follow project conventions and best practices
  • Context Preservation: Each subagent uses its own context window, keeping the main conversation focused

Example Usage Scenarios

# Creating a new feature page
"Create a new dashboard page with charts and data tables"
# nextjs-component-creator automatically handles this

# Adding form validation
"Add a contact form with email and phone validation"
# form-builder subagent creates the form with Zod schemas

# Improving performance
"The homepage is loading slowly, can you optimize it?"
# performance-optimizer analyzes and implements improvements

# API integration
"How do I implement bearer token authentication for Merkos API?"
# merkos-api-expert provides the exact implementation
Subagents are version controlled in the repository. Any modifications to subagent configurations will affect the entire team, so coordinate changes with your team members.
Development Workflow

Recommended Development Flow

This project uses a structured development workflow that integrates session tracking with code commits and deployments:

Step-by-Step Workflow

  1. Start Session: Begin each development session with /session-start [description]
  2. Implementation: Write code and track progress using todo lists
  3. Complete Session: When work is finished, Claude will prompt to run /session-end
  4. Commit Changes: After session ends, Claude will prompt to run /save for commits
  5. Create PR: After successful commit, the system will prompt for pull request creation

Session Management

# Start a development session
/session-start implement user authentication

# During development - Claude tracks todos automatically
# When work is complete, Claude prompts:
# "Your todos are complete. Would you like to end this session with /session-end?"

# After session documentation:
# "Would you like to commit and push your changes with /save?"

# After successful /save:
# "Would you like to create a pull request for these changes?"

Key Benefits

  • Structured Progress: Clear separation between development and commit phases
  • User Control: Developer decides when to commit and create PRs
  • Session Tracking: Complete documentation of development activities
  • Quality Assurance: The /save command runs all pre-commit checks automatically
  • Consistent Commits: Standardized commit messages with conventional format

The /save Command

The /save command handles all git operations automatically:

  • Pre-commit Checks: Runs tests, linting, and build verification
  • Conventional Commits: Creates standardized commit messages with emojis
  • Automatic Push: Pushes changes to the remote repository
  • PR Prompting: Asks if you want to create a pull request

Best Practices

  • Descriptive Sessions: Use clear descriptions when starting sessions
  • Complete Work: Finish all todos before ending sessions
  • Review Changes: Check what will be committed before running /save
  • Test First: Ensure all tests pass before committing
  • Document Progress: Use session updates to track important discoveries

Example Workflow

# 1. Start working on a feature
/session-start add dark mode toggle

# 2. Claude creates todos and implements the feature
# - Create toggle component
# - Add state management  
# - Update existing components
# - Write tests

# 3. When todos complete, Claude prompts:
# "Your todos are complete. Would you like to end this session with /session-end?"

# 4. After session documentation:
# "Would you like to commit and push your changes with /save?"

# 5. Run /save command:
/save

# 6. System prompts:
# "Would you like to create a pull request for these changes?"
Important: Claude will never automatically commit code. All git operations require explicit user approval through the /save command, giving you full control over when and what gets committed.
Future Roadmap

Completed Features

  • ✅ TypeScript Integration: Hybrid TypeScript/JavaScript architecture implemented
  • ✅ Comprehensive Testing: Jest and React Testing Library setup with 241 passing tests (100% pass rate)
  • ✅ API Integration: Full Merkos Platform and Valu Social API integration

Planned Features

  • Database Integration: Vercel Postgres or Supabase
  • Authentication: NextAuth.js implementation
  • CMS Capabilities: Admin dashboard
  • Stricter TypeScript: Gradual migration to stricter type checking
  • Middleware: Advanced request handling

Design Philosophy

  • Minimalism: Apple-inspired clean design
  • Performance: Optimized for speed and user experience
  • Scalability: Structured for easy expansion
  • Developer Experience: Modern tooling and clear patterns

Contributing

This starter kit is designed to be easily customizable. When making changes:

  1. Follow existing code patterns and conventions
  2. Write unit tests for new components and API routes
  3. Run tests with npm test to ensure nothing is broken
  4. Test changes with npm run build
  5. Run linting with npm run lint
  6. Maintain test coverage above 70% threshold
  7. Update this documentation when adding new features
  8. Update CLAUDE.md for Claude Code assistant guidance