Troubleshooting Guide

Common issues and solutions for Litestore

Troubleshooting Guide

This guide covers common issues and solutions when working with Litestore. Issues are organized by category for easier navigation. If you can't find a solution here, check our community Discord or create an issue on GitHub.

Quick Diagnosis

Run this command to check your Litestore installation:

npx litestore diagnose

This will check:

  • Node.js version compatibility
  • Environment variables
  • Database connectivity
  • Required dependencies
  • Build configuration

Installation Issues

Build Failures

Node.js Version Issues

Error: error:0308010C:digital envelope routines::unsupported

Solution:

# Use Node.js 18+ or add legacy OpenSSL provider
export NODE_OPTIONS="--openssl-legacy-provider"
npm run build

Prevention: Use Node.js 18.17.0 or later.

Dependency Installation Issues

Error: npm ERR! code ENOTFOUND

Solution:

# Clear npm cache
npm cache clean --force

# Delete node_modules and reinstall
rm -rf node_modules package-lock.json
npm install

Prisma Client Issues

Error: PrismaClient is unable to be run in the browser

Solution:

# Regenerate Prisma client
npx prisma generate

# Clear Next.js cache
rm -rf .next

Database Connection Issues

PostgreSQL Connection Failed

Error: Can't reach database server

Solutions:

# Check if PostgreSQL is running
brew services list | grep postgresql  # macOS
sudo systemctl status postgresql      # Linux

# Test connection
psql postgresql://username:password@localhost:5432/litestore

# Reset database (development only)
npx prisma migrate reset

Environment Variable Issues

Error: DATABASE_URL is not defined

Solutions:

# Check if .env.local exists
ls -la .env.local

# Verify DATABASE_URL format
echo $DATABASE_URL

# Restart development server
npm run dev

Migration Issues

Error: Migration failed

Solutions:

# Check migration status
npx prisma migrate status

# Resolve failed migration
npx prisma migrate resolve --applied 20231201120000_migration_name

# Reset and retry (development only)
npx prisma migrate reset

Runtime Issues

Authentication Problems

Sign In Not Working

Error: Invalid login credentials

Solutions:

// Check NextAuth configuration
export const authOptions = {
  providers: [
    CredentialsProvider({
      async authorize(credentials) {
        // Verify user exists and password is correct
        const user = await prisma.user.findUnique({
          where: { email: credentials.email }
        });

        if (user && await bcrypt.compare(credentials.password, user.password)) {
          return user;
        }
        return null;
      }
    })
  ]
}

Session Issues

Error: Session not persisting

Solution:

# Check NEXTAUTH_SECRET
echo $NEXTAUTH_SECRET  # Should be 32+ characters

# Clear browser cookies
# Restart development server

AI Feature Issues

OpenAI API Errors

Error: 401 Unauthorized

Solutions:

# Check API key
echo $OPENAI_API_KEY  # Should start with 'sk-'

# Verify API key permissions
curl -H "Authorization: Bearer $OPENAI_API_KEY" \
     https://api.openai.com/v1/models

Rate Limiting

Error: 429 Too Many Requests

Solutions:

// Implement retry logic
async function generateWithRetry(content: string, maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await generateContent(content);
    } catch (error) {
      if (error.status === 429) {
        await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
        continue;
      }
      throw error;
    }
  }
}

File Upload Issues

Cloudinary Upload Failed

Error: Upload failed

Solutions:

// Check Cloudinary configuration
console.log({
  cloudName: process.env.CLOUDINARY_CLOUD_NAME,
  apiKey: process.env.CLOUDINARY_API_KEY,
  apiSecret: process.env.CLOUDINARY_API_SECRET?.slice(0, 4) + '...'
});

// Verify upload preset exists
// Check file size limits

Payment Processing Issues

Stripe Webhook Failures

Error: Webhook signature verification failed

Solutions:

// Verify webhook secret
const endpointSecret = process.env.STRIPE_WEBHOOK_SECRET;

// Ensure raw body is used
export const config = {
  api: {
    bodyParser: false,
  },
};

Performance Issues

Slow Page Loads

Causes & Solutions:

  1. Database Queries
-- Add missing indexes
CREATE INDEX idx_products_category ON products(category_id);
CREATE INDEX idx_content_creator ON creator_content(creator_id);
  1. Image Optimization
// next.config.js
module.exports = {
  images: {
    formats: ['image/webp', 'image/avif'],
    deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
  }
}
  1. API Response Caching
// Implement caching
import { unstable_cache } from 'next/cache';

export const getProducts = unstable_cache(
  async () => {
    return prisma.product.findMany();
  },
  ['products'],
  { revalidate: 3600 }
);

High Memory Usage

Solutions:

// Optimize Prisma queries
const products = await prisma.product.findMany({
  select: { // Only select needed fields
    id: true,
    name: true,
    price: true
  },
  take: 20 // Limit results
});

Database Performance

Common Issues:

  1. Slow Queries
-- Identify slow queries
SELECT query, total_time, calls, mean_time
FROM pg_stat_statements
ORDER BY mean_time DESC
LIMIT 10;
  1. Connection Pool Issues
// lib/db.ts
import { PrismaClient } from '@prisma/client'

const globalForPrisma = globalThis as unknown as {
  prisma: PrismaClient | undefined
}

export const prisma = globalForPrisma.prisma ?? new PrismaClient({
  log: ['query'],
  datasources: {
    db: {
      url: process.env.DATABASE_URL,
    },
  },
})

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma

Creator Content Issues

Content Moderation Problems

Error: Content flagged incorrectly

Solutions:

// Adjust moderation settings
const moderationConfig = {
  sensitivity: 'medium', // 'low', 'medium', 'high'
  categories: {
    spam: true,
    hate: true,
    adult: true,
    violence: false
  },
  customRules: [
    // Add custom moderation rules
  ]
}

Commission Calculation Issues

Error: Incorrect commission amounts

Solutions:

// Verify commission rules
const rules = await prisma.commissionRule.findMany({
  where: { creatorId: creator.id }
});

// Debug calculation
const commission = calculateCommission({
  amount: order.total,
  rules: rules,
  creator: creator
});

Frontend Issues

Hydration Errors

Error: Text content does not match server-rendered HTML

Solutions:

// Use useEffect for client-only content
useEffect(() => {
  setClientOnlyData(fetchData());
}, []);

// Or use dynamic imports
const ClientComponent = dynamic(() => import('./ClientComponent'), {
  ssr: false
});

Styling Issues

Error: Styles not loading

Solutions:

// Check Tailwind configuration
module.exports = {
  content: [
    './pages/**/*.{js,ts,jsx,tsx,mdx}',
    './components/**/*.{js,ts,jsx,tsx,mdx}',
    './app/**/*.{js,ts,jsx,tsx,mdx}',
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

API Issues

CORS Errors

Error: CORS policy blocked

Solutions:

// next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/api/:path*',
        headers: [
          { key: 'Access-Control-Allow-Origin', value: '*' },
          { key: 'Access-Control-Allow-Methods', value: 'GET,POST,PUT,DELETE' },
          { key: 'Access-Control-Allow-Headers', value: 'Content-Type,Authorization' },
        ],
      },
    ]
  },
}

Rate Limiting Issues

Error: Too many requests

Solutions:

// Implement client-side rate limiting
import { RateLimiter } from 'limiter';

const limiter = new RateLimiter({ tokensPerInterval: 10, interval: 'minute' });

async function apiCall() {
  const remainingRequests = await limiter.removeTokens(1);
  if (remainingRequests < 0) {
    throw new Error('Rate limit exceeded');
  }
  return fetch('/api/endpoint');
}

Deployment Issues

Build Errors in Production

Error: Module not found

Solutions:

# Clear build cache
rm -rf .next node_modules/.cache

# Check package.json
npm ls --depth=0

# Reinstall dependencies
npm ci

Environment Variables Missing

Error: process.env.VARIABLE is undefined

Solutions:

# Check deployment platform environment variables
# Ensure variables are prefixed correctly
# Restart application

Database Migration Failures

Error: Migration name already exists

Solutions:

# Check migration status
npx prisma migrate status

# Mark migration as applied
npx prisma migrate resolve --applied migration_name

# Create new migration
npx prisma migrate dev --name new_migration

Monitoring & Debugging

Enable Debug Logging

// lib/logger.ts
import pino from 'pino';

export const logger = pino({
  level: process.env.LOG_LEVEL || 'info',
  transport: {
    target: 'pino-pretty',
    options: {
      colorize: true
    }
  }
});

// Usage
logger.info({ userId, action }, 'User performed action');
logger.error({ error, context }, 'Operation failed');

Performance Monitoring

// pages/_app.tsx
import { useEffect } from 'react';
import { useRouter } from 'next/router';

export default function App({ Component, pageProps }) {
  const router = useRouter();

  useEffect(() => {
    const handleRouteChange = (url) => {
      // Track page views
      console.log('Page view:', url);
    };

    router.events.on('routeChangeComplete', handleRouteChange);
    return () => {
      router.events.off('routeChangeComplete', handleRouteChange);
    };
  }, [router.events]);

  return <Component {...pageProps} />;
}

Database Query Monitoring

// lib/db.ts
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient({
  log: [
    { level: 'query', emit: 'event' },
    { level: 'info', emit: 'stdout' },
    { level: 'warn', emit: 'stdout' },
    { level: 'error', emit: 'stdout' },
  ],
})

prisma.$on('query', (e) => {
  console.log('Query: ' + e.query)
  console.log('Duration: ' + e.duration + 'ms')
})

Getting Help

Community Support

  1. Discord Community: Real-time help from other users
  2. GitHub Issues: Report bugs and request features
  3. Stack Overflow: Ask technical questions

Professional Support

For enterprise deployments and custom development:

  • Priority Support: 24/7 response times
  • Custom Development: Bespoke features and integrations
  • Migration Services: Move from existing platforms
  • Training: Team onboarding and best practices

Diagnostic Information

When reporting issues, please include this comprehensive diagnostic information:

System Information

# Versions
node --version          # Should be 18.17.0+
npm --version          # Latest stable
git --version          # Any recent version

# Operating System
uname -a               # Linux/macOS
# or
systeminfo | findstr /B /C:"OS"  # Windows

Environment Check

# Environment variables (mask sensitive data)
echo "NODE_ENV: $NODE_ENV"
echo "NEXTAUTH_URL: $NEXTAUTH_URL"
echo "DATABASE_URL: ${DATABASE_URL:0:20}..."  # First 20 chars only

# Check if required files exist
ls -la .env.local
ls -la prisma/schema.prisma

Database Status

# Migration status
npx prisma migrate status

# Database connectivity
npx prisma db push --preview-feature

# Recent migrations
ls -la prisma/migrations/

Application Logs

# Development logs
tail -n 50 .next/development.log 2>/dev/null || echo "No dev logs"

# Production logs (if applicable)
tail -n 50 logs/app.log 2>/dev/null || echo "No app logs"

# Build logs
npm run build 2>&1 | tail -n 20

Package Information

# Dependencies
npm ls --depth=0 | head -20

# Check for conflicting versions
npm ls next react @prisma/client

Browser Information (for frontend issues)

// Run in browser console on the affected page
console.log({
  userAgent: navigator.userAgent,
  url: window.location.href,
  viewport: {
    width: window.innerWidth,
    height: window.innerHeight
  },
  cookiesEnabled: navigator.cookieEnabled,
  localStorage: Object.keys(localStorage).length,
  errors: window.errors || [] // If you have error tracking
});

Issue Report Template

Please use this template when creating GitHub issues:

## Description
Brief description of the issue and its impact

## Steps to Reproduce
1. Go to '...'
2. Click on '...'
3. Scroll to '...'
4. See error

## Expected Behavior
What should happen when following the steps above

## Actual Behavior
What actually happens (include screenshots if applicable)

## Environment
- Litestore version: [run `npm list litestore` or check package.json]
- Node.js version: [run `node --version`]
- Browser: [e.g., Chrome 120, Safari 17]
- OS: [e.g., macOS 14.0, Windows 11, Ubuntu 22.04]
- Database: [PostgreSQL version]

## Additional Context
- Error messages from console/terminal
- Screenshots of the issue
- Any recent changes that might have caused this
- Diagnostic information (from above)
- Reproduction repository (if possible)

Pro Tip

Enable debug logging in development to catch issues early: DEBUG=* npm run dev

On this page