Troubleshooting & FAQ
This section covers frequently asked questions, common issues, and troubleshooting guides for FastSvelte development and deployment.
Frequently Asked Questions
General Questions
Q: What is FastSvelte? A: FastSvelte is a production-ready fullstack SaaS starter kit built with FastAPI (Python) and SvelteKit (TypeScript). It includes authentication, user management, payments, admin tools, and deployment configurations.
Q: Is FastSvelte suitable for both B2B and B2C applications?
A: Yes! FastSvelte supports both models through the FS_MODE
environment variable. B2B mode supports team-based organizations with invitations, while B2C mode creates personal organizations for each user.
Q: Can I use FastSvelte for non-SaaS applications? A: Absolutely. While optimized for SaaS, FastSvelte works well for any web application needing user management, authentication, and a modern tech stack.
Architecture Questions
Q: Why do we use suffixes like _model
, _repo
, _service
, and _route
in file names?
Here's a comparison of file structures with and without suffixes:
With suffixes (FastSvelte approach):
backend/app/
├── api/route/user_route.py
├── service/user_service.py
├── model/user_model.py
└── data/repo/user_repo.py
Without suffixes:
Why suffixes win:
- IDE clarity - When you have multiple user.py
tabs open, you can't tell which is which
- Search efficiency - Easier to find "user_service" than filtering through multiple "user" files
- Code navigation - Jump-to-file works better with descriptive names
- Team collaboration - No confusion about which file handles what
Q: Why are repositories registered as providers.Factory
instead of Singleton
?
We use Factory
when components might maintain state or need fresh instances. Singleton
is used for stateless components:
# Singleton for stateless services
user_service = providers.Singleton(UserService, user_repo=user_repo)
# Factory for repositories that might have transaction state
user_repo = providers.Factory(UserRepo, db_config=db_config)
Q: Why do we have both service-level and route-level error handling?
Service layer throws domain-specific exceptions:
Route layer converts to HTTP responses:
# Route
try:
user = await user_service.create_user(email, password)
except UserAlreadyExistsException as e:
raise HTTPException(status_code=409, detail=str(e))
This separates business logic from HTTP concerns and makes services testable independently.
Development Questions
Q: How do I add a new API endpoint?
A: Follow these steps:
1. Add route in app/api/route/
2. Add service method in app/service/
3. Add repository method if needed in app/data/repo/
4. Update models in app/model/
5. Run cd frontend && npm run generate
to update API client
Q: How do I add a new database table?
A: Use Sqitch migrations:
1. cd db && sqitch add table_name -n "Description"
2. Edit deploy/table_name.sql
with CREATE TABLE
3. Edit revert/table_name.sql
with DROP TABLE
4. Run ./sqitch.sh dev deploy
Q: How do I customize the admin dashboard?
A: Admin components are in frontend/src/routes/(protected)/admin/
. You can:
- Modify existing admin pages
- Add new admin routes
- Update the admin layout in (protected)/admin/+layout.svelte
- Add new dashboard widgets
Authentication Questions
Q: Why session-based auth instead of JWT? A: Session-based auth provides better security: - HTTP-only cookies prevent XSS attacks - Server-side session control - instant revocation - Simpler client code - no token management - Built-in CSRF protection with SameSite cookies
Q: How do I add social login providers?
A: FastSvelte includes Google OAuth. To add others:
1. Add provider credentials to settings
2. Implement provider-specific OAuth flow in app/util/oauth_util.py
3. Add OAuth routes in app/api/route/auth_route.py
4. Update frontend login page
Q: How do I customize user roles?
A: Roles are defined in the database. To add new roles:
1. Insert new role in fastsvelte.role
table
2. Update role checks in services and routes
3. Add UI permissions in frontend components
Common Issues & Solutions
Setup Issues
Issue: pip install
fails with dependency conflicts
python3.12 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
Issue: PostgreSQL connection refused
Solution: Ensure PostgreSQL is running:# Using Docker
docker compose up db -d
# Check if running
docker ps | grep postgres
# Verify connection
psql postgres://postgres:postgres@localhost/fastsvelte -c "SELECT 1;"
Issue: Database does not exist
Solution: Create the database:# Connect to PostgreSQL and create database
psql postgres://postgres:postgres@localhost -c "CREATE DATABASE fastsvelte;"
# Or use Docker
docker exec -it fastsvelte-db psql -U postgres -c "CREATE DATABASE fastsvelte;"
Development Issues
Issue: API client generation fails
Solution: Ensure backend is running before generating client:# Start backend first
cd backend && uvicorn app.main:app --reload
# Then generate in another terminal
cd frontend && npm run generate
Issue: Import errors with absolute imports
Solution: Always use absolute imports fromapp
package:
# ✅ Correct
from app.service.user_service import UserService
# ❌ Incorrect
from ..service.user_service import UserService
Issue: Dependency injection not working
Solution: Ensure your module is added to wiring configuration:# app/config/container.py
wiring_config = containers.WiringConfiguration(
modules=[
"app.api.route.your_new_route", # Add this line
# ... existing modules
]
)
Database Issues
Issue: Migration fails with "relation already exists"
Solution: UseIF NOT EXISTS
in migrations:
Issue: Sqitch deploy fails with permission denied
Solution: Make script executable:Issue: Connection pool exhausted
Solution: Adjust connection pool settings:# app/data/db_config.py
self.pool = await asyncpg.create_pool(
self.dsn,
min_size=5, # Reduce if needed
max_size=10, # Reduce if needed
command_timeout=60
)
Frontend Issues
Issue: CORS errors in development
Solution: Check CORS configuration in backend:# app/config/settings.py
@property
def cors_origins(self) -> list[str]:
return {
"dev": ["http://localhost:5173", "http://localhost:4173"],
# ... other environments
}.get(self.environment, [])
Issue: Authentication not persisting
Solution: Ensure cookies are configured properly:// src/lib/api/axios.js
export const axiosInstance = Axios.create({
baseURL: PUBLIC_API_BASE_URL,
withCredentials: true // This is crucial
});
Issue: Svelte components not updating
Solution: Use Svelte 5 runes correctly:Production Issues
Issue: Static assets not loading
Solution: Check build configuration and base path:Issue: Database connection timeouts in production
Solution: Increase connection timeout and pool settings:Issue: High memory usage
Solution: Optimize container resources and add memory limits:# Dockerfile
FROM python:3.12-slim # Use slim image
# Add memory-efficient settings
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
Environment-Specific Troubleshooting
Development Environment
Issue: Hot reload not working
Solution: Check file watchers and ports:# Backend
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
# Frontend
npm run dev -- --host 0.0.0.0 --port 5173
Issue: Docker volumes not mounting
Solution: Create external volume:Production Environment
Issue: SSL certificate errors
Solution: Ensure proper SSL configuration:# Check certificate
openssl s_client -connect yourdomain.com:443
# Verify DNS
nslookup yourdomain.com
Issue: Rate limiting too aggressive
Solution: Adjust rate limiting configuration:# app/api/middleware/rate_limiter.py
def get_rate_limit(request: Request) -> str:
if is_production():
return "100/minute" # Increase for production
return "10/minute"
Performance Troubleshooting
Slow Database Queries
Issue: Queries taking too long
Solution: Add indexes and optimize queries:-- Find slow queries
SELECT query, mean_exec_time, calls
FROM pg_stat_statements
WHERE mean_exec_time > 100
ORDER BY mean_exec_time DESC;
-- Add missing indexes
CREATE INDEX CONCURRENTLY idx_user_organization_active
ON fastsvelte."user"(organization_id) WHERE is_active = true;
High Memory Usage
Issue: Memory usage constantly increasing
Solution: Check for memory leaks:# Add connection cleanup
async def cleanup_connections():
await db_config.pool.close()
# Monitor connection pools
async def get_pool_status():
return {
"size": db_config.pool.get_size(),
"active": db_config.pool.get_active_count(),
"idle": db_config.pool.get_idle_count()
}
Security Issues
Authentication Bypass
Issue: Users accessing protected routes without login
Solution: Verify route protection:@router.get("/admin/users")
async def list_users(
current_user: CurrentUser = Depends(min_role_required(Role.SYSTEM_ADMIN))
):
# Ensure dependency is applied
Session Hijacking
Issue: Sessions being stolen or reused Solution: Implement proper session security:
# Rotate session tokens on login
async def login(email: str, password: str):
# ... authenticate user
# Generate new session token
new_token = secrets.token_urlsafe(32)
# Invalidate old sessions for this user
await session_repo.delete_by_user_id(user.id)
# Create new session
await session_repo.create(user.id, hash_token(new_token))
Monitoring & Debugging
Application Logs
View backend logs:
View frontend logs: - Open browser DevTools → Console - Check Network tab for API errors - Monitor Application tab for localStorage/cookies
Database Monitoring
Check active connections:
Monitor query performance:
SELECT
query,
mean_exec_time,
calls,
total_exec_time
FROM pg_stat_statements
ORDER BY mean_exec_time DESC
LIMIT 10;
Health Checks
API health check:
Database connectivity:
External services:
Getting Help
Self-Help Resources
- Check logs - Always start with application and error logs
- Review configuration - Verify environment variables and settings
- Test connections - Verify database, API, and external service connectivity
- Consult documentation - Review relevant sections in this documentation
Community Support
- GitHub Issues - Report bugs and feature requests
- Documentation - Check all sections of this documentation
- API Documentation - Use interactive docs at
/docs
endpoint - Code Examples - Review example implementations in the codebase
When Reporting Issues
Include the following information:
- Environment details - Development/production, OS, versions
- Error messages - Complete error traces and logs
- Configuration - Relevant environment variables (sanitized)
- Steps to reproduce - Minimal reproduction steps
- Expected behavior - What should happen vs what actually happens
Quick Diagnostics Script
#!/bin/bash
# FastSvelte Health Check
echo "=== FastSvelte Diagnostics ==="
# Check Python version
echo "Python version: $(python --version)"
# Check Node version
echo "Node version: $(node --version)"
# Check database connection
if psql $FS_DB_URL -c "SELECT 1;" &>/dev/null; then
echo "✅ Database connection: OK"
else
echo "❌ Database connection: FAILED"
fi
# Check backend API
if curl -s http://localhost:8000/health &>/dev/null; then
echo "✅ Backend API: OK"
else
echo "❌ Backend API: FAILED"
fi
# Check frontend
if curl -s http://localhost:5173 &>/dev/null; then
echo "✅ Frontend: OK"
else
echo "❌ Frontend: FAILED"
fi
echo "=== End Diagnostics ==="
This comprehensive troubleshooting guide should help resolve most common FastSvelte issues. For additional help, consult the other documentation sections or create an issue in the repository.