Documentation

Troubleshooting Guide

Solutions to common issues and problems when installing and using SveltyCMS.

Last updated: 10/5/2025

Troubleshooting Guide

Common issues and solutions for SveltyCMS installation and usage.


Installation Issues

Issue: “Cannot find module” errors

Symptoms:

Error: Cannot find module 'mongoose'
Error: Cannot find module 'mariadb'

Solution:

  1. Install missing database driver:

    # MongoDB
    npm install mongoose
    
    # MariaDB/MySQL
    npm install mariadb
    
    # PostgreSQL
    npm install pg
  2. Or use the CLI installer:

    npm run dev
    # Follow prompts to auto-install drivers
  3. Clear cache and reinstall:

    rm -rf node_modules package-lock.json
    npm install

Issue: Port 5173 already in use

Symptoms:

Error: listen EADDRINUSE: address already in use :::5173

Solution:

  1. Find and kill the process:

    # macOS/Linux
    lsof -ti:5173 | xargs kill -9
    
    # Windows
    netstat -ano | findstr :5173
    taskkill /PID <PID> /F
  2. Or use a different port:

    PORT=3000 npm run dev
  3. Update vite.config.ts:

    export default defineConfig({
    	server: {
    		port: 3000
    	}
    });

Issue: Database connection failed

Symptoms:

MongoDB connection failed: Authentication failed
MariaDB connection failed: Access denied

Solutions:

MongoDB

  1. Check credentials:

    DB_USER=admin
    DB_PASSWORD=correct_password
  2. Verify MongoDB is running:

    # macOS/Linux
    sudo systemctl status mongod
    
    # Or check if listening
    nc -zv localhost 27017
  3. Check MongoDB Atlas whitelist:

    • Login to MongoDB Atlas
    • Network Access → Add IP Address
    • Add 0.0.0.0/0 (for development only!)
  4. Fix connection string format:

    # Local
    DB_HOST=localhost
    DB_PORT=27017
    
    # Atlas
    DB_HOST=mongodb+srv://cluster.mongodb.net
    # Note: No port needed for Atlas

MariaDB/MySQL

  1. Verify service is running:

    sudo systemctl status mariadb
    # or
    sudo systemctl status mysql
  2. Test connection manually:

    mysql -h localhost -u root -p
  3. Grant permissions:

    GRANT ALL PRIVILEGES ON sveltycms.* TO 'admin'@'localhost';
    FLUSH PRIVILEGES;
  4. Check firewall:

    # Allow MySQL port
    sudo ufw allow 3306

Issue: CLI installer not launching

Symptoms:

  • Development server starts but no setup wizard appears

Solution:

  1. Manually run installer:

    npm run installer
  2. Or navigate to setup page:

    http://localhost:5173/setup
  3. Check if already installed:

    • If .env file exists, setup is skipped
    • Delete .env to re-run setup (CAUTION: Will lose config)

Runtime Issues

Issue: “Unauthorized” errors

Symptoms:

{
	"error": "Unauthorized"
}

Solutions:

  1. Clear browser cookies:

    • Open DevTools → Application → Cookies
    • Delete session cookie
    • Refresh and login again
  2. Check session secret:

    SESSION_SECRET=your-secret-here
    • Must be set and consistent
    • Generate new: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
  3. Verify JWT secret:

    JWT_SECRET=your-jwt-secret
  4. Check token expiration:

    • Default: 24 hours
    • Login again to refresh

Issue: “Cannot read properties of undefined”

Symptoms:

TypeError: Cannot read properties of undefined (reading 'user')

Solutions:

  1. Check hooks.server.ts:

    • Ensure authentication hooks are registered
    • Verify locals.user is set
  2. Restart development server:

    # Stop server (Ctrl+C)
    npm run dev
  3. Clear build cache:

    rm -rf .svelte-kit
    npm run dev

Issue: 404 on API endpoints

Symptoms:

404 Not Found: /api/collections/posts

Solutions:

  1. Check route file exists:

    ls src/routes/api/collections/[collectionId]/+server.ts
  2. Verify SvelteKit routing:

    • Folder names must match route params
    • +server.ts required for API endpoints
  3. Check base URL:

    // ✅ Correct
    fetch('/api/collections/posts');
    
    // ❌ Wrong
    fetch('api/collections/posts'); // Missing leading /
  4. Restart server:

    npm run dev

Issue: Database queries returning empty results

Symptoms:

  • Collections exist but queries return []
  • Dashboard shows 0 entries

Solutions:

  1. Check tenant ID (multi-tenant mode):

    // Queries automatically scoped by tenant
    // Verify user is in correct tenant
    console.log(locals.tenantId);
  2. Verify data was seeded:

    # Check database directly
    
    # MongoDB
    mongo sveltycms
    db.posts.find()
    
    # MySQL
    mysql -u root -p
    USE sveltycms;
    SELECT * FROM posts;
  3. Check collection name:

    • Collection names are case-sensitive
    • Use exact name from schema
  4. Verify permissions:

    • User may not have read permission
    • Check role permissions in Settings

Issue: File upload fails

Symptoms:

Error: File size exceeds maximum allowed size
Error: File type not allowed

Solutions:

  1. Check file size limits:

    # .env
    MAX_FILE_SIZE=10485760  # 10MB in bytes
  2. Verify allowed file types:

    • Go to Settings → Media
    • Check allowed extensions
    • Add missing types
  3. Check disk space:

    df -h
  4. Verify upload directory permissions:

    chmod -R 755 static/uploads
    chown -R $USER:$USER static/uploads
  5. Check Nginx/Apache limits:

    # Nginx
    client_max_body_size 50M;
    # Apache
    LimitRequestBody 52428800

Performance Issues

Issue: Slow API responses

Symptoms:

  • API requests take > 1 second
  • Dashboard loads slowly

Solutions:

  1. Enable caching:

    CACHE_ENABLED=true
    USE_REDIS=false  # Or true if Redis available
  2. Add database indexes:

    // MongoDB
    db.posts.createIndex({ title: 'text', content: 'text' });
    db.posts.createIndex({ createdAt: -1 });
  3. Limit query results:

    // Use pagination
    fetch('/api/collections/posts?limit=25&page=1');
  4. Optimize images:

    • Use WebP format
    • Enable image processing
    • Implement lazy loading
  5. Check database connection:

    • Use connection pooling
    • Reduce connection timeout
    • Monitor active connections

Issue: High memory usage

Symptoms:

JavaScript heap out of memory
FATAL ERROR: Reached heap limit

Solutions:

  1. Increase Node memory:

    NODE_OPTIONS="--max-old-space-size=4096" npm run dev
  2. Add to package.json:

    {
    	"scripts": {
    		"dev": "NODE_OPTIONS='--max-old-space-size=4096' vite dev"
    	}
    }
  3. Clear cache:

    # Clear application cache
    curl -X POST http://localhost:5173/api/cache/clear \
      -H "Cookie: session=your-session"
  4. Optimize queries:

    • Use pagination
    • Limit field selection
    • Avoid loading large datasets

Build & Deployment Issues

Issue: Build fails with TypeScript errors

Symptoms:

Type error: Property 'user' does not exist on type 'Locals'

Solutions:

  1. Update app.d.ts:

    // src/app.d.ts
    declare global {
    	namespace App {
    		interface Locals {
    			user: import('$lib/types').User | null;
    			tenantId: string;
    		}
    	}
    }
  2. Run type check:

    npm run typecheck
  3. Install missing types:

    npm install --save-dev @types/node

Issue: Production build too large

Symptoms:

  • Build size > 5MB
  • Slow page loads

Solutions:

  1. Enable code splitting:

    // vite.config.ts
    export default defineConfig({
    	build: {
    		rollupOptions: {
    			output: {
    				manualChunks: {
    					vendor: ['svelte'],
    					utils: ['./src/utils']
    				}
    			}
    		}
    	}
    });
  2. Remove unused dependencies:

    npx depcheck
  3. Analyze bundle:

    npm run build -- --analyze
  4. Use dynamic imports:

    // Instead of
    import Widget from './Widget.svelte';
    
    // Use
    const Widget = await import('./Widget.svelte');

Issue: Environment variables not loaded

Symptoms:

  • process.env.DB_HOST is undefined
  • Settings not applied in production

Solutions:

  1. Check .env file location:

    # Must be in project root
    ls -la .env
  2. Verify variable names:

    # Public variables need PUBLIC_ prefix
    PUBLIC_SITE_NAME=My CMS
    
    # Private variables
    DB_PASSWORD=secret
  3. Restart server after .env changes:

    npm run dev
  4. Load .env explicitly (if needed):

    import 'dotenv/config';

Common Error Messages

“ECONNREFUSED”

Meaning: Cannot connect to database

Fix:

  • Verify database is running
  • Check host and port in .env
  • Verify firewall rules

“CORS Error”

Meaning: Cross-origin request blocked

Fix:

// svelte.config.js
export default {
	kit: {
		cors: {
			origin: ['http://localhost:3000'],
			credentials: true
		}
	}
};

“MongoServerError: Authentication failed”

Meaning: Wrong MongoDB credentials

Fix:

  • Double-check username/password
  • Verify authentication database
  • Check user permissions

“ER_ACCESS_DENIED_ERROR”

Meaning: MySQL/MariaDB access denied

Fix:

-- Grant permissions
GRANT ALL PRIVILEGES ON sveltycms.* TO 'user'@'localhost' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;

Widget Issues

Issue: Widget Dashboard Shows Wrong Counts

Symptoms:

  • Custom widgets appear in dropdowns and work correctly
  • Dashboard shows “0” custom widgets
  • File system shows widgets exist in src/widgets/
  • Database sync button available

Understanding the Dual-Layer System:

SveltyCMS uses a dual-layer widget system:

  1. File System Layer (src/widgets/):

    • Widgets physically exist as .svelte files
    • Used directly by the application at runtime
    • Works immediately without database registration
  2. Database Layer (MongoDB widgets collection):

    • Stores widget metadata for dashboard and management
    • Required for accurate dashboard counts
    • Enables widget discovery and categorization

Why This Happens:

Custom widgets in src/widgets/Display/, src/widgets/Definition/, and src/widgets/Input/ work immediately because the application loads them directly from the file system. However, the dashboard counts widgets from the database, which may not reflect recent file system changes.

Solutions:

1. Use the Sync Button

The dashboard provides a “Sync Widgets” button that:

  • Scans src/widgets/ for all widget files
  • Compares with database records
  • Adds new widgets to the database
  • Updates widget counts in the dashboard

To sync:

  1. Go to Dashboard → Widgets
  2. Click “Sync Widgets” button
  3. Wait for confirmation
  4. Refresh to see updated counts

2. Use the API Endpoint

# Trigger widget sync via API
curl -X POST http://localhost:5173/api/widgets/sync \
  -H "Cookie: session=your-session"

Response:

{
	"success": true,
	"added": 5,
	"updated": 2,
	"message": "Widgets synchronized successfully"
}

3. Manual Database Sync

# MongoDB
mongosh sveltycms
db.widgets.find({ type: "custom" }).count()

# Insert missing widget manually
db.widgets.insertOne({
	name: "CustomWidget",
	type: "custom",
	category: "Display",
	path: "src/widgets/Display/CustomWidget.svelte",
	enabled: true,
	createdAt: new Date()
})

Common Scenarios:

  1. New Custom Widget Created:

    • Widget works in collections immediately
    • Dashboard shows old count
    • Fix: Click “Sync Widgets”
  2. Widget Deleted from File System:

    • Database still has reference
    • Dashboard shows incorrect count
    • Fix: Sync to clean up orphaned entries
  3. Widget Renamed:

    • Old name in database
    • New file in file system
    • Fix: Sync to update database record
  4. Fresh Installation:

    • Core widgets exist in files
    • Database empty or partially populated
    • Fix: Run sync on first setup

Best Practices:

  • After adding custom widgets: Always run sync
  • After git pull: Sync to update database with new widgets
  • Regular maintenance: Sync monthly to keep database clean
  • CI/CD: Include widget sync in deployment scripts
# Add to deployment script
npm run build
npm run db:migrate
npm run widgets:sync  # Custom script to call sync endpoint

Preventing Issues:

  1. Use Widget Generator CLI:

    npm run widget:create
    # Automatically registers in database
  2. Enable Auto-Sync (if configured):

    WIDGET_AUTO_SYNC=true  # Syncs on server start
  3. Monitor Logs:

    tail -f logs/app.log | grep "widget"

Issue: Custom Widget Not Appearing in Collection Builder

Symptoms:

  • Widget file exists in src/widgets/
  • Widget works when hardcoded
  • Not visible in collection builder dropdown

Solutions:

  1. Sync widgets to database:

    • Click “Sync Widgets” in dashboard
    • Widget must be registered in database to appear in builder
  2. Check widget export:

    // ✅ Correct
    export default MyWidget;
    
    // ❌ Wrong
    export { MyWidget }; // Named export not supported
  3. Verify widget category:

    • Display widgets go in src/widgets/Display/
    • Input widgets go in src/widgets/Input/
    • Definition widgets go in src/widgets/Definition/
  4. Check widget metadata:

    <script lang="ts">
    	// Widget metadata for registration
    	export const metadata = {
    		name: 'MyWidget',
    		category: 'Display',
    		description: 'My custom widget'
    	};
    </script>
  5. Restart development server:

    npm run dev

Issue: Widget Fails to Load

Symptoms:

Failed to load widget: Cannot find module './widgets/CustomWidget.svelte'
Error: Widget 'CustomWidget' not found

Solutions:

  1. Check file path and naming:

    # Widget filename must match registration
    ls src/widgets/Display/CustomWidget.svelte
  2. Verify import in widget factory:

    // src/widgets/widgetFactory.ts
    const displayWidgets = {
    	CustomWidget: () => import('./Display/CustomWidget.svelte')
    };
  3. Check widget is enabled:

    // Database check
    db.widgets.findOne({ name: 'CustomWidget' });
    // Verify: { enabled: true }
  4. Clear build cache:

    rm -rf .svelte-kit
    npm run dev

Issue: Widget Props Not Working

Symptoms:

  • Widget renders but props undefined
  • Console error: “Cannot read property of undefined”

Solutions:

  1. Define props with proper types:

    <script lang="ts">
    	import type { WidgetProps } from '$lib/types';
    
    	export let data: WidgetProps['data'];
    	export let config: WidgetProps['config'] = {};
    	export let mode: WidgetProps['mode'] = 'display';
    </script>
  2. Provide default values:

    <script lang="ts">
    	export let title: string = 'Default Title';
    	export let count: number = 0;
    </script>
  3. Check parent component:

    <!-- ✅ Correct -->
    <Widget {data} {config} mode="edit" />
    
    <!-- ❌ Wrong -->
    <Widget {data} />
    <!-- Missing other required props -->

Getting More Help

Debug Mode

Enable verbose logging:

LOG_LEVEL=debug
DEBUG=sveltycms:*

Check System Requirements

# Node version
node --version  # Should be >= 20.10.0

# npm version
npm --version

# Git version
git --version

# Database version
mongo --version  # MongoDB
mysql --version  # MySQL/MariaDB

Collect Debug Information

Before reporting issues, collect:

# System info
node --version
npm --version
cat package.json | grep version

# Error logs
cat logs/app.log

# Environment (without secrets!)
cat .env | grep -v PASSWORD | grep -v SECRET

Report an Issue

Include in your bug report:

  1. Environment:

    • OS (Windows/macOS/Linux)
    • Node version
    • Package manager (npm/bun/yarn)
    • Database type and version
  2. Steps to reproduce:

    • What you did
    • What you expected
    • What actually happened
  3. Error messages:

    • Full error text
    • Stack trace
    • Console output
  4. Screenshots:

    • Error screens
    • Console errors
    • Network tab

Submit issues: GitHub Issues


Additional Resources

troubleshootingdebuggingsupportfaq