This guide covers the complete setup and configuration of the NextSaaS admin system, including database migrations, super admin creation, and security configuration.
Before setting up the admin system, ensure you have:
- ✅ NextSaaS project cloned and dependencies installed
- ✅ Supabase project configured and connected
- ✅ Basic user authentication working
- ✅ Multi-tenant organization system set up
For a rapid setup, run these commands in order:
# 1. Apply admin database migrations
npm run db:migrate
# 2. Create initial super admin
npm run db:seed
# 3. Build admin package
npm run build --filter=@nextsaas/admin
# 4. Start development server
npm run devThe admin system requires specific database tables and security policies.
# Apply the super admin system migration
npx supabase db push
# Or apply specific migrations
npx supabase migration up 022_add_super_admin_system
npx supabase migration up 023_admin_dashboard_enhancements022_add_super_admin_system.sql creates:
is_system_admincolumn on users table- Admin audit logging system
- Admin-specific RLS policies
- System admin role functions
023_admin_dashboard_enhancements.sql adds:
- Dashboard metrics views
- Performance indexes
- Enhanced audit logging
- System health monitoring tables
# Run the super admin seed script
npm run db:seedThis creates a super admin user using the email from your environment:
# Required in .env.local
SUPER_ADMIN_EMAIL=admin@yourcompany.comIf you need to manually create a super admin:
-- 1. Create or update existing user
INSERT INTO users (email, name, is_system_admin)
VALUES ('admin@yourcompany.com', 'System Administrator', true)
ON CONFLICT (email)
DO UPDATE SET is_system_admin = true;
-- 2. Verify creation
SELECT id, email, name, is_system_admin
FROM users
WHERE is_system_admin = true;Add these to your .env.local file:
# Super Admin Configuration
SUPER_ADMIN_EMAIL=admin@yourcompany.com
# Admin Dashboard Configuration (Optional)
ADMIN_DASHBOARD_TITLE="NextSaaS Admin"
ADMIN_PAGINATION_LIMIT=20
# Security Configuration (Recommended)
ADMIN_SESSION_TIMEOUT=3600 # 1 hour in seconds
ADMIN_REQUIRE_2FA=false # Enable for production
ADMIN_IP_WHITELIST="" # Comma-separated IPs (optional)For production, consider these additional settings:
# Production Security
ADMIN_REQUIRE_2FA=true
ADMIN_IP_WHITELIST="203.0.113.1,203.0.113.2"
ADMIN_SESSION_TIMEOUT=1800 # 30 minutes
# Monitoring Integration
ADMIN_MONITORING_ENABLED=true
ADMIN_METRICS_ENDPOINT="https://your-monitoring-service.com/api"
# Audit Logging
ADMIN_AUDIT_RETENTION_DAYS=90
ADMIN_AUDIT_EXPORT_ENABLED=trueThe admin package should already be installed in your monorepo:
# Verify installation
npm list @nextsaas/admin
# If missing, add it
npm install @nextsaas/admin --workspace=apps/web# Build admin package and dependencies
npm run build --filter=@nextsaas/admin
# Or build all packages
npm run buildEnsure your middleware includes admin route protection:
// apps/web/middleware.ts
import { createServerClient } from '@supabase/ssr'
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export async function middleware(request: NextRequest) {
// ... existing auth middleware
// Admin route protection
if (request.nextUrl.pathname.startsWith('/admin')) {
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
// ... supabase config
)
const { data: { session } } = await supabase.auth.getSession()
if (!session) {
return NextResponse.redirect(new URL('/auth/sign-in', request.url))
}
// Check system admin status
const { data: user } = await supabase
.from('users')
.select('is_system_admin')
.eq('id', session.user.id)
.single()
if (!user?.is_system_admin) {
return NextResponse.redirect(new URL('/dashboard', request.url))
}
}
return response
}
export const config = {
matcher: [
'/admin/:path*',
'/api/admin/:path*',
// ... other protected routes
],
}Ensure your tsconfig.json includes the admin package:
{
"compilerOptions": {
"paths": {
"@nextsaas/admin": ["../packages/admin/src"],
"@nextsaas/admin/*": ["../packages/admin/src/*"]
}
}
}Check that all admin tables and functions exist:
-- Check admin column exists
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = 'users' AND column_name = 'is_system_admin';
-- Verify super admin created
SELECT email, is_system_admin
FROM users
WHERE is_system_admin = true;
-- Check audit logging function
SELECT routine_name
FROM information_schema.routines
WHERE routine_name = 'log_system_admin_action';-
Start the development server:
npm run dev
-
Test admin access:
- Navigate to
/admin - Should redirect to sign-in if not authenticated
- Sign in with super admin email
- Should see admin dashboard
- Navigate to
-
Test API endpoints:
# Test dashboard API (requires authentication) curl -X GET http://localhost:3000/api/admin/dashboard \ -H "Authorization: Bearer YOUR_SESSION_TOKEN"
- ✅ Non-admin users cannot access
/adminroutes - ✅ Admin API endpoints return 403 for non-admin users
- ✅ Audit logging captures admin actions
- ✅ Session timeout works as configured
Symptoms: Getting 403 error when accessing admin pages
Solutions:
-- Verify user has admin flag
SELECT email, is_system_admin FROM users WHERE email = 'your-email@domain.com';
-- Grant admin privileges
UPDATE users SET is_system_admin = true WHERE email = 'your-email@domain.com';Symptoms: Import errors for @nextsaas/admin
Solutions:
# Rebuild admin package
npm run build --filter=@nextsaas/admin
# Clear Next.js cache
rm -rf apps/web/.next
# Restart development server
npm run devSymptoms: Migration errors during setup
Solutions:
# Check current migration status
npx supabase migration list
# Reset migrations (CAUTION: Development only)
npx supabase db reset
# Apply migrations step by step
npx supabase migration up --target 022
npx supabase migration up --target 023Symptoms: Constant redirections or auth failures
Solutions:
- Ensure unified Supabase client usage (see
CLAUDE.md) - Clear browser cookies and localStorage
- Check environment variables are correct
Enable debug logging for troubleshooting:
# Add to .env.local
DEBUG=nextsaas:admin*
NEXT_PUBLIC_DEBUG_ADMIN=trueBefore deploying to production:
- Enable 2FA requirement (
ADMIN_REQUIRE_2FA=true) - Configure IP whitelisting if needed
- Set shorter session timeout
- Enable audit log retention policies
- Configure monitoring and alerting
- Review and test all admin permissions
- Backup database before deployment
- Database indexes on admin query paths
- CDN configuration for admin assets
- Rate limiting on admin API endpoints
- Monitoring for admin dashboard performance
Configure monitoring for:
- Admin login attempts and failures
- Admin action frequency and patterns
- System performance impact
- Security events and anomalies
After setup completion:
- Read the Admin User Guide to understand dashboard features
- Review Admin API Reference for integration details
- Check Security Documentation for security best practices
- Set up monitoring and alerting for admin system health
For additional help:
- Check the Troubleshooting Guide
- Review package documentation in
/packages/admin/README.md - Open an issue on the project repository