Guides

Comprehensive guides for getting started, development workflow, deployment process, and troubleshooting in ShipKit applications

Guides

This section provides comprehensive guides for working with ShipKit applications, from getting started to deployment and troubleshooting.

Getting Started

Prerequisites

  1. Node.js and PNPM

    # Install Node.js 20 (LTS)
    nvm install 20
    nvm use 20
    
    # Install PNPM
    npm install -g pnpm@latest
    
    # Verify installations
    node --version  # Should be 20.x.x
    pnpm --version  # Should be 8.x.x
    
  2. Database

    # Install PostgreSQL
    brew install postgresql@15
    brew services start postgresql@15
    
    # Create database
    createdb shipkit_dev
    createdb shipkit_test
    
  3. Environment Setup

    # Clone repository
    git clone https://github.com/your-org/shipkit.git
    cd shipkit
    
    # Install dependencies
    pnpm install
    
    # Copy environment variables
    cp .env.example .env
    
    # Generate Prisma client
    pnpm prisma generate
    
    # Run database migrations
    pnpm prisma migrate dev
    

Initial Setup

  1. Configure Environment Variables

    # .env
    DATABASE_URL="postgresql://user:pass@localhost:5432/shipkit_dev"
    NEXTAUTH_URL="http://localhost:3000"
    NEXTAUTH_SECRET="your-secret"  # Generate with: openssl rand -base64 32
    
  2. Start Development Server

    # Run development server
    pnpm dev
    
    # Run with Turbo
    pnpm turbo dev
    
  3. Access Application

Development Workflow

Code Organization

src/
├── app/                 # Next.js App Router
│   ├── (app)/          # Protected routes
│   ├── (auth)/         # Authentication routes
│   ├── (marketing)/    # Public routes
│   └── api/            # API routes
├── components/         # React components
│   ├── ui/            # UI components
│   └── emails/        # Email templates
├── lib/               # Utility functions
│   ├── auth/          # Authentication utilities
│   ├── integrations/  # Third-party integrations
│   └── utils/         # Helper functions
├── server/            # Server-side code
│   ├── actions/       # Server actions
│   ├── api/           # API handlers
│   └── db/            # Database utilities
└── styles/            # Global styles

Development Commands

# Start development server
pnpm dev

# Run type checking
pnpm type-check

# Run linting
pnpm lint

# Run tests
pnpm test

# Run database migrations
pnpm prisma migrate dev

# Generate Prisma client
pnpm prisma generate

# Reset database
pnpm prisma migrate reset

Git Workflow

# Create feature branch
git checkout -b feature/your-feature

# Stage changes
git add .

# Commit with conventional commit message
git commit -m "feat: add new feature"

# Push to remote
git push origin feature/your-feature

# Create pull request
gh pr create

Code Style

// Use arrow functions for components
export const Component = () => {
  return <div>Component</div>
}

// Use function declarations for utilities
export function utilityFunction() {
  return 'utility'
}

// Use const assertions for constants
export const constants = {
  API_VERSION: 'v1',
  MAX_ITEMS: 100,
} as const

// Use type annotations for function parameters
export function processData(data: Data): Result {
  return transform(data)
}

Deployment Process

Production Deployment

  1. Build Application

    # Install dependencies
    pnpm install --frozen-lockfile
    
    # Run type checking
    pnpm type-check
    
    # Run tests
    pnpm test
    
    # Build application
    pnpm build
    
  2. Database Migration

    # Generate migration
    pnpm prisma migrate deploy
    
    # Verify migration
    pnpm prisma migrate status
    
  3. Environment Configuration

    # Set production environment variables
    vercel env pull .env.production
    
  4. Deploy to Vercel

    # Deploy to production
    vercel --prod
    
    # Deploy to preview
    vercel
    

Staging Deployment

  1. Create Staging Environment

    # Create new project
    vercel new shipkit-staging
    
    # Link project
    vercel link
    
    # Pull environment variables
    vercel env pull .env.staging
    
  2. Configure Staging

    # Deploy to staging
    vercel deploy --env staging
    
    # Promote to production
    vercel promote
    

Deployment Verification

# Run health check
curl https://your-domain.com/api/health

# Run E2E tests
pnpm test:e2e

# Monitor logs
vercel logs

# Check deployment status
vercel list

Troubleshooting

Common Issues

  1. Database Connection

    # Check database connection
    pnpm prisma db push
    
    # Reset database
    pnpm prisma migrate reset
    
    # Check database logs
    tail -f /usr/local/var/log/[email protected]
    
  2. Build Errors

    # Clear Next.js cache
    rm -rf .next
    
    # Clear dependency cache
    rm -rf node_modules
    pnpm install
    
    # Check TypeScript errors
    pnpm tsc --noEmit
    
  3. Runtime Errors

    # Check application logs
    vercel logs
    
    # Check error monitoring
    open https://vercel.com/your-org/your-project/monitoring
    
    # Test local production build
    pnpm build
    pnpm start
    

Debug Tools

// src/lib/debug.ts
export function debugLog(
  message: string,
  data?: Record<string, unknown>
) {
  if (process.env.NODE_ENV === 'development') {
    console.log(`[DEBUG] ${message}`, data)
  }
}

export function measurePerformance(
  name: string,
  fn: () => Promise<any>
) {
  return async (...args: any[]) => {
    const start = performance.now()
    const result = await fn(...args)
    const end = performance.now()

    debugLog(`Performance: ${name}`, {
      duration: end - start,
      args,
    })

    return result
  }
}

Error Handling

// src/lib/error-handling.ts
export class AppError extends Error {
  constructor(
    message: string,
    public code: string,
    public statusCode: number = 500
  ) {
    super(message)
    this.name = 'AppError'
  }
}

export function handleError(error: unknown) {
  if (error instanceof AppError) {
    return {
      message: error.message,
      code: error.code,
      statusCode: error.statusCode,
    }
  }

  if (error instanceof Error) {
    return {
      message: error.message,
      code: 'UNKNOWN_ERROR',
      statusCode: 500,
    }
  }

  return {
    message: 'An unknown error occurred',
    code: 'UNKNOWN_ERROR',
    statusCode: 500,
  }
}

Monitoring and Logging

// src/lib/monitoring.ts
export function monitorEndpoint(
  name: string,
  handler: (req: Request) => Promise<Response>
) {
  return async (req: Request) => {
    const start = performance.now()

    try {
      const response = await handler(req)

      // Log success metrics
      logMetric('endpoint.success', {
        name,
        duration: performance.now() - start,
        status: response.status,
      })

      return response
    } catch (error) {
      // Log error metrics
      logMetric('endpoint.error', {
        name,
        duration: performance.now() - start,
        error: error instanceof Error ? error.message : 'Unknown error',
      })

      throw error
    }
  }
}

function logMetric(
  name: string,
  data: Record<string, unknown>
) {
  // Send to monitoring service
  console.log(`[METRIC] ${name}`, data)
}

Best Practices

  1. Code Quality

    • Write tests for critical functionality
    • Use TypeScript for type safety
    • Follow consistent code style
    • Document complex logic
  2. Performance

    • Optimize images and assets
    • Use caching where appropriate
    • Implement lazy loading
    • Monitor performance metrics
  3. Security

    • Keep dependencies updated
    • Follow security best practices
    • Implement proper authentication
    • Validate user input
  4. Maintenance

    • Monitor error rates
    • Keep documentation updated
    • Review logs regularly
    • Plan for scalability

Quick Reference

Common Commands

# Development
pnpm dev           # Start development server
pnpm build         # Build for production
pnpm start         # Start production server
pnpm lint          # Run linting
pnpm test          # Run tests

# Database
pnpm prisma studio # Open Prisma Studio
pnpm db:push      # Push schema changes
pnpm db:reset     # Reset database

# Deployment
pnpm deploy       # Deploy to production
pnpm deploy:stage # Deploy to staging

Useful Links