Skip to Content
📚 MyStoryFlow Docs — Your guide to preserving family stories
Use Cases & TestingMiddleware & Routing Rules

Middleware & Routing Rules

Document Purpose: Comprehensive specification of authentication middleware, route protection, and navigation logic that controls user access across the application.

Last Updated: July 12, 2025
Version: 1.0
File Location: /lib/supabase/middleware.ts


📋 Table of Contents

  1. Overview
  2. Setup Completion Requirements
  3. Route Protection Logic
  4. Business Use Cases
  5. Testing Scenarios

Overview

The middleware layer controls access to protected routes based on user authentication status and setup completion. This ensures users follow the proper onboarding flow while allowing exceptions for specific business scenarios like gift purchases.

Core Functions

  • Authentication Verification - Validate user sessions
  • Setup Completion Checks - Ensure users complete onboarding
  • Route Protection - Control access to dashboard and features
  • Business Logic Routing - Handle special cases for gift purchasers

Setup Completion Requirements

General Rule

Dashboard access requires setup_completed = true in user profile

Route Classifications

Protected Routes (Require Setup)

  • /dashboard/* - Main dashboard and sub-pages
  • Standard user features and analytics

Exception Routes (No Setup Required)

  • /dashboard/purchase-gift - Gift purchase flow
  • /families/* - Family workspace access
  • Authentication pages
  • Public marketing pages

Special Handling Routes

  • /campaigns/create - Redirects based on setup status

Route Protection Logic

Authentication Check

const { data: { user } } = await supabase.auth.getUser() if (!user) { // Not authenticated, let page handle redirect return response } ``` --> ### Setup Completion Check ```typescript const { data: profile } = await supabase .from('profiles') .select('setup_completed') .eq('id', user.id) .single() const setupCompleted = !!profile?.setup_completed ``` --> ### Dashboard Protection ```typescript // Lines 100-106 if (isDashboard && !setupCompleted && !isPurchaseGift) { // Redirect to campaign creation to complete setup const redirectUrl = incompleteCampaignId ? `/campaigns/create?step=1&campaign_id=${incompleteCampaignId}` : '/campaigns/create?step=1' return NextResponse.redirect(new URL(redirectUrl, request.url)) } ``` --> ### Family Workspace Exception ```typescript // Lines 113-118 if (isFamilyWorkspace && !setupCompleted) { // Allow access - gift purchasers need immediate family access return response } ``` --> --- ## Business Use Cases ### UC-001: New User Onboarding **Scenario**: First-time user tries to access dashboard - **Trigger**: User accesses `/dashboard` with `setup_completed = false` - **Action**: Redirect to `/campaigns/create?step=1` - **Rationale**: Ensure users complete initial campaign setup ### UC-002: Gift Purchaser Access **Scenario**: User completes gift purchase and clicks "Go to Family Workspace" - **Trigger**: User accesses `/families/{id}` with `setup_completed = false` - **Action**: Allow access (no redirect) - **Rationale**: Gift purchasers have paid for family features and should access them immediately ### UC-003: Gift Purchase Flow **Scenario**: User starts gift purchase without completing setup - **Trigger**: User accesses `/dashboard/purchase-gift` with `setup_completed = false` - **Action**: Allow access (no redirect) - **Rationale**: Gift purchases shouldn't require full onboarding ### UC-004: Completed User Campaign Access **Scenario**: Setup-completed user tries to access campaign creation - **Trigger**: User accesses `/campaigns/create` with `setup_completed = true` - **Action**: Redirect to `/dashboard` - **Rationale**: Prevent duplicate campaign creation for completed users ### UC-005: Resume Incomplete Campaign **Scenario**: User has incomplete campaign and accesses dashboard - **Trigger**: User accesses `/dashboard` with incomplete campaign and `setup_completed = false` - **Action**: Redirect to `/campaigns/create?step=1&campaign_id={id}` - **Rationale**: Allow users to continue where they left off --- ## Testing Scenarios ### Functional Testing #### TC-MW-001: Authentication Flow Testing - **Test**: Access protected routes without authentication - **Expected**: Allow page to handle authentication redirect - **Verify**: No middleware-level blocking for unauthenticated users #### TC-MW-002: Setup Completion Enforcement - **Test**: Access dashboard with `setup_completed = false` - **Expected**: Redirect to `/campaigns/create?step=1` - **Verify**: User is guided through onboarding #### TC-MW-003: Gift Purchase Exception - **Test**: Access `/dashboard/purchase-gift` with `setup_completed = false` - **Expected**: Allow access without redirect - **Verify**: Gift purchase flow works for new users #### TC-MW-004: Family Workspace Exception - **Test**: Access `/families/123` with `setup_completed = false` - **Expected**: Allow access without redirect - **Verify**: Gift purchasers can access family workspace immediately #### TC-MW-005: Campaign Creation Redirect - **Test**: Access `/campaigns/create` with `setup_completed = true` - **Expected**: Redirect to `/dashboard` - **Verify**: Completed users don't duplicate campaigns ### Edge Case Testing #### TC-MW-006: Incomplete Campaign Resume - **Test**: Access dashboard with incomplete campaign - **Expected**: Redirect to campaign creation with campaign ID - **Verify**: User can resume incomplete setup #### TC-MW-007: Database Query Failures - **Test**: Simulate profile query failure - **Expected**: Graceful fallback (allow access or safe redirect) - **Verify**: Application doesn't crash on database errors #### TC-MW-008: Multiple Route Access - **Test**: Rapidly access multiple protected routes - **Expected**: Consistent middleware behavior - **Verify**: No race conditions or inconsistent redirects ### Performance Testing #### TC-MW-009: Middleware Performance - **Test**: Measure middleware execution time - **Expected**: < 100ms response time - **Verify**: Middleware doesn't slow down navigation #### TC-MW-010: Database Query Optimization - **Test**: Monitor database queries during route protection - **Expected**: Minimal queries per request - **Verify**: Efficient profile and campaign lookups --- ## Configuration ### Route Patterns ```typescript const isDashboard = pathname.startsWith('/dashboard') const isPurchaseGift = pathname.startsWith('/dashboard/purchase-gift') const isFamilyWorkspace = pathname.startsWith('/families') const isCampaignCreate = pathname.startsWith('/campaigns/create') ``` --> ### Matcher Configuration ```typescript export const config = { matcher: [ '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)', ], } ``` --> --- ## Error Handling ### Database Connection Failures - **Behavior**: Allow access to prevent blocking users - **Logging**: Log errors for monitoring - **Recovery**: Retry on next request ### Profile Query Failures - **Behavior**: Default to requiring setup completion - **Safety**: Err on the side of security - **Monitoring**: Track query failure rates ### Invalid Routes - **Behavior**: Pass through to Next.js routing - **Handling**: Let application handle 404s - **Performance**: Minimize middleware processing for invalid routes --- ## Maintenance ### When to Update - New protected routes are added - Business logic changes for user onboarding - Authentication requirements change - Performance optimizations needed ### Testing After Changes 1. Run authentication test suite 2. Test all protected route scenarios 3. Verify gift purchase flow still works 4. Check performance impact 5. Validate error handling --- *Last Updated: July 12, 2025* *Maintained by: Development Team*