Complete Setup Guide
Complete Setup Guide
Section titled “Complete Setup Guide”This comprehensive guide walks you through setting up astro-basics with all its features including authentication, database integration, role-based access control, and security features.
Overview
Section titled “Overview”Astro-basics is a production-ready web development framework with:
- ✅ Authentication - Clerk integration with protected routes
- ✅ Database Support - Supabase (PostgreSQL) and Turso (LibSQL) backends
- ✅ Role System - Configurable roles with TypeScript type safety
- ✅ Security - CSRF protection, rate limiting, RLS policies
- ✅ Testing - Unit tests (Vitest) and E2E tests (Playwright)
- ✅ PWA Ready - Progressive Web App capabilities
Quick Start (5 Minutes)
Section titled “Quick Start (5 Minutes)”For experienced developers who want to get running quickly:
# 1. Install and configuregit clone https://github.com/shawn-sandy/astro-basics.gitcd astro-basicsnpm install # ~4 minutesnpm run prepare # Setup hookscp .env.example .env # Copy template
# 2. Add Clerk keys to .env (required)# PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_...# CLERK_SECRET_KEY=sk_test_...
# 3. Setup database (optional)npm run db:wizard # Interactive setup
# 4. Start developingnpm run start # Dev server + SCSS watcherVisit http://localhost:4321 to see your site!
Detailed Setup
Section titled “Detailed Setup”Step 1: Installation
Section titled “Step 1: Installation”Prerequisites
Section titled “Prerequisites”- Node.js v18.0.0 or higher
- npm v9.0.0 or higher
- Git for version control
Clone and Install
Section titled “Clone and Install”# Clone repositorygit clone https://github.com/shawn-sandy/astro-basics.gitcd astro-basics
# Install dependencies (takes ~4 minutes, warnings are expected)npm install
# Setup pre-commit hooks (Husky + lint-staged)npm run prepare
# Install Playwright browsers (for E2E tests)npx playwright installStep 2: Authentication Setup
Section titled “Step 2: Authentication Setup”Authentication is required for protected routes and user features.
Create a Clerk Application
Section titled “Create a Clerk Application”- Sign up at clerk.com (free tier available)
- Create a new application
- Choose authentication methods (email, Google, GitHub, etc.)
Get API Keys
Section titled “Get API Keys”From your Clerk dashboard:
- Navigate to API Keys
- Copy Publishable Key →
PUBLIC_CLERK_PUBLISHABLE_KEY - Copy Secret Key →
CLERK_SECRET_KEY - (Optional) Copy Webhook Secret →
CLERK_WEBHOOK_SECRET
Configure Environment
Section titled “Configure Environment”# Copy environment templatecp .env.example .env
# Edit .env filevim .envAdd your Clerk keys:
# Authentication (Required)PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_...CLERK_SECRET_KEY=sk_test_...CLERK_WEBHOOK_SECRET=whsec_... # OptionalProtected Routes
Section titled “Protected Routes”These routes require authentication (configured in src/middleware.ts):
/dashboard/*- User dashboard and profile/forum/*- Community forum features/organization/*- Organization management
Unauthenticated users are automatically redirected to sign-in.
Step 3: Database Setup
Section titled “Step 3: Database Setup”Choose one or both database backends:
- Supabase (PostgreSQL): Real-time features, native Clerk integration, RLS
- Turso (LibSQL): Edge-first SQLite, low latency, global distribution
Option A: Guided Setup (Recommended)
Section titled “Option A: Guided Setup (Recommended)”Use the interactive database wizard:
npm run db:wizardThe wizard will:
- Detect available database credentials
- Guide you through configuration
- Set up database schema automatically
- Verify connection
Option B: Manual Setup - Supabase
Section titled “Option B: Manual Setup - Supabase”1. Create Supabase Project
- Sign up at supabase.com
- Create a new project
- Wait for initialization (~2 minutes)
2. Get Credentials
Navigate to Project Settings → API to find your credentials:
Steps to locate your API keys:
- Open Supabase Dashboard: https://supabase.com/dashboard
- Select your project from the project list
- Click “Settings” (gear icon) in the left sidebar
- Navigate to “API” section
- Find “Project API keys” section:
anon(public) - This is yourSUPABASE_ANON_KEY✅service_role(secret) - This is yourSUPABASE_SERVICE_ROLE_KEY🔒
- Find “Project URL” at the top - This is your
SUPABASE_URL
Add these to your .env file:
SUPABASE_URL=https://your-project.supabase.coSUPABASE_ANON_KEY=eyJ...SUPABASE_SERVICE_ROLE_KEY=eyJ... # Required for server operations
# Public keys (for client-side)PUBLIC_SUPABASE_URL=https://your-project.supabase.coPUBLIC_SUPABASE_ANON_KEY=eyJ...3. Run Migrations
# Apply database schema (users, roles, organizations, comments)npm run db:migrate
# Verify migration statusnpm run db:migrate:status
# Set up Clerk-Supabase user syncnpm run db:setup-usersSee the Clerk-Supabase Integration Guide for detailed instructions.
Option C: Manual Setup - Turso
Section titled “Option C: Manual Setup - Turso”1. Install Turso CLI
curl -sSfL https://get.tur.so/install.sh | bashturso auth login2. Create Database
# Create databaseturso db create astro-basics
# Get connection detailsturso db show astro-basics3. Configure Environment
# Get database URLturso db show astro-basics --url# → TURSO_DATABASE_URL
# Create auth tokenturso db tokens create astro-basics# → TURSO_AUTH_TOKENAdd to .env:
TURSO_DATABASE_URL=libsql://your-db.turso.ioTURSO_AUTH_TOKEN=eyJ...4. Initialize Database
npm run db:setupDatabase Switching
Section titled “Database Switching”The project includes a unified database abstraction layer:
# Check current database statusnpm run db:status
# Switch databases (with automatic backup)npm run db:switch:supabasenpm run db:switch:tursonpm run db:switch:auto # Auto-detect
# Backup and restorenpm run db:backupnpm run db:restoreKey Features:
- Automatic backup before switching
- Provider auto-detection via
DATABASE_PROVIDERenv var - Unified TypeScript types
- Zero code changes required
See the Database Switching Guide for complete documentation.
Step 4: Role Configuration
Section titled “Step 4: Role Configuration”The project includes a configurable role system for setup-time customization.
Understanding Roles
Section titled “Understanding Roles”Roles control user access with hierarchical privilege escalation:
Level 3: super_admin ⚡ Full system access │Level 2: admin 👔 Manage users & settings │Level 1: member 👤 View content (default)Default Behavior: Higher-level roles automatically inherit lower-level permissions.
Default Configuration
Section titled “Default Configuration”Pre-configured roles in config/roles.config.ts:
member(level 1) - Default for new usersadmin(level 2) - Administrative accesssuper_admin(level 3) - Full system access
Customizing Roles
Section titled “Customizing Roles”1. Edit Configuration
vim config/roles.config.ts2. Add Custom Roles
export const roleConfig: RoleConfig = { roles: [ { id: 'member', level: 1, name: 'Member', isDefault: true }, { id: 'author', level: 2, name: 'Author' }, // New { id: 'moderator', level: 3, name: 'Moderator' }, // New { id: 'admin', level: 4, name: 'Admin' }, { id: 'super_admin', level: 5, name: 'Super Admin' }, ],}3. Generate Types and Migrations
# Preview changesnpm run setup:roles:dry-run
# Generate filesnpm run setup:rolesThis creates:
- TypeScript types in
src/types/generated-roles.ts - Database migrations in
scripts/migrations/
4. Apply Migration
npm run db:migrate5. Commit Changes
git add config/ src/types/ scripts/migrations/git commit -m "Configure custom roles"Using Role Guards
Section titled “Using Role Guards”Protect components and pages:
---import { RoleGuard } from '#components/react/RoleGuard'---
<!-- Hierarchical (default): members, admins, super_admins can access --><RoleGuard allowedRoles={['member']} client:load> <Dashboard /></RoleGuard>
<!-- Exact matching: only admins can access --><RoleGuard allowedRoles={['admin']} useHierarchy={false} client:load> <AdminPanel /></RoleGuard>See the Configurable Roles Guide and Role Guard Usage Guide for complete documentation.
Development Workflow
Section titled “Development Workflow”Starting Development
Section titled “Starting Development”# Recommended: Dev server + SCSS watcher togethernpm run start
# Or start separately:npm run dev # Astro dev server (port 4321)npm run sass # SCSS watcherProject Structure
Section titled “Project Structure”src/├── components/ # Reusable components│ ├── astro/ # Server-rendered (.astro)│ ├── react/ # Client-side (.tsx)│ └── dashboard/ # Protected components├── pages/ # Route pages & API endpoints├── content/ # Content collections (MDX)│ ├── posts/ # Blog posts│ ├── docs/ # Documentation│ └── content/ # General content├── layouts/ # Page layouts├── styles/ # SCSS stylesheets├── libs/ # Database clients & utilities├── utils/ # Helper functions└── middleware.ts # Authentication middlewareImport Patterns
Section titled “Import Patterns”Use # path aliases for clean imports:
// ✅ Recommendedimport Header from '#components/astro/Header.astro'import { SITE_TITLE } from '#utils/site-config'import type { User } from '#types/users'
// ❌ Avoidimport Header from '../../components/astro/Header.astro'Code Quality
Section titled “Code Quality”Before committing:
# Fix all auto-fixable issuesnpm run fix:all
# Or run individually:npm run lint # ESLintnpm run format # Prettiernpm run type-check # TypeScriptnpm run lint:styles:fix # StyleLintnpm run lint:md:fix # MarkdownPre-commit hooks (Husky) automatically run on staged files.
Testing
Section titled “Testing”Unit Tests (Vitest)
Section titled “Unit Tests (Vitest)”# Run all unit testsnpm test
# Run specific testnpm test path/to/test.test.ts
# Watch modenpm test -- --watchE2E Tests (Playwright)
Section titled “E2E Tests (Playwright)”# Run all E2E testsnpm run test:e2e
# Run with UInpx playwright test --ui
# View reportnpm run test:e2e:reportNote: Dev server must run on port 4321 for E2E tests.
Database Management
Section titled “Database Management”Common Commands
Section titled “Common Commands”# Status and validationnpm run db:status # Check configurationnpm run db:schema # Validate schema
# Migrationsnpm run db:migrate # Run migrationsnpm run db:migrate:status # Check statusnpm run db:migrate:rollback # Rollback
# Data managementnpm run db:seed:messages # Seed datanpm run db:reset # Reset (deletes all data)See the Database Troubleshooting Guide for help with common issues.
Building for Production
Section titled “Building for Production”# Create production buildnpm run build
# Preview locallynpm run preview
# Deploy to Netlifynpm run deploy:prodBuild time: ~10-15 seconds
Output: dist/ directory
Deployment Adapters
Section titled “Deployment Adapters”Configure via .env:
ASTRO_ADAPTER=netlify # or 'node', 'vercel'Troubleshooting
Section titled “Troubleshooting”Authentication Errors
Section titled “Authentication Errors”Problem: “Clerk keys not configured”
Solution:
# Verify keys in .envgrep CLERK .env
# Keys should start with:# PUBLIC_CLERK_PUBLISHABLE_KEY: pk_test_ or pk_live_# CLERK_SECRET_KEY: sk_test_ or sk_live_Database Connection Issues
Section titled “Database Connection Issues”Problem: “Failed to connect to database”
Solution:
# Check statusnpm run db:status
# Verify connectionnpm run db:check
# See troubleshooting guide# /guide/database-troubleshooting/Missing Tables
Section titled “Missing Tables”Problem: “Table does not exist” errors
Solution:
# Run migrationsnpm run db:migrate
# Verify schemanpm run db:schemaBuild Warnings
Section titled “Build Warnings”Problem: getStaticPaths warnings
Solution: These are expected for dynamic routes and don’t affect functionality.
Pre-commit Failures
Section titled “Pre-commit Failures”Problem: Commits fail due to linting
Solution:
# Fix all issuesnpm run fix:allNext Steps
Section titled “Next Steps”Now that you’re set up:
-
Explore Features
- Configurable Roles - Custom role system
- Database Switching - Provider flexibility
- Role Guard Usage - Access control patterns
-
Learn the Stack
- Components - Available components
- API Reference - Detailed API docs
- MCP Servers - Model Context Protocol integration
-
Build Your App
- Create components in
src/components/ - Add content to collections in
src/content/ - Build API endpoints in
src/pages/api/
- Create components in
Getting Help
Section titled “Getting Help”- Documentation - Browse this guide for detailed information
- GitHub Issues - Report bugs or request features
- Examples - Check
/src/pages/for usage examples
Happy coding! 🚀