Skip to main content

Documentation Index

Fetch the complete documentation index at: https://usegately.com/docs/llms.txt

Use this file to discover all available pages before exploring further.

Auto Protect automatically enforces access control on pages matching configured URL patterns, without requiring code changes on each page.

Quick Setup

import { autoProtectPage } from '@gately/sdk'

// Protect current page
autoProtectPage({
  loginUrl: '/login',
  upgradeUrl: '/upgrade'
})

Configuration

Basic Configuration

import { createAutoProtect } from '@gately/sdk'

const autoProtect = createAutoProtect({
  // URL patterns to protect
  patterns: [
    { pattern: '/dashboard/*', requireAuth: true },
    { pattern: '/premium/*', requirePlan: 'pro' },
    { pattern: '/admin/*', requirePlan: 'enterprise' }
  ],
  
  // Redirect URLs
  loginUrl: '/login',
  upgradeUrl: '/upgrade',
  
  // Options
  checkOnLoad: true,
  showLoadingState: true
})

Pattern Options

interface ProtectionPattern {
  pattern: string           // URL pattern to match
  requireAuth?: boolean     // Require authentication
  requirePlan?: string      // Require specific plan
  requirePlans?: string[]   // Require one of these plans
  redirectUrl?: string      // Custom redirect for this pattern
  allowedRoles?: string[]   // Require specific roles
}

URL Patterns

PatternDescriptionExamples
/exactExact match/dashboard
/path/*Wildcard suffix/courses/intro, /courses/advanced
/path/*/editWildcard middle/posts/123/edit
*.pdfFile extension/docs/guide.pdf

Usage Examples

Protect Dashboard

createAutoProtect({
  patterns: [
    { pattern: '/dashboard', requireAuth: true },
    { pattern: '/dashboard/*', requireAuth: true }
  ],
  loginUrl: '/login'
})

Plan-Based Protection

createAutoProtect({
  patterns: [
    { pattern: '/free/*', requireAuth: true },
    { pattern: '/pro/*', requirePlan: 'pro' },
    { pattern: '/enterprise/*', requirePlan: 'enterprise' }
  ],
  upgradeUrl: '/pricing'
})

Multiple Plans

createAutoProtect({
  patterns: [
    { 
      pattern: '/premium/*', 
      requirePlans: ['pro', 'business', 'enterprise']
    }
  ]
})

React Integration

With Router

import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import { useAutoProtect } from '@gately/sdk'

function App() {
  const location = useLocation()
  const { checkAccess, isChecking } = useAutoProtect({
    patterns: [
      { pattern: '/dashboard/*', requireAuth: true }
    ]
  })

  useEffect(() => {
    checkAccess(location.pathname)
  }, [location.pathname])

  if (isChecking) {
    return <LoadingScreen />
  }

  return <Routes />
}

Protected Route Component

import { AutoProtect } from '@gately/sdk'

function App() {
  return (
    <AutoProtect
      patterns={[
        { pattern: '/dashboard/*', requireAuth: true },
        { pattern: '/premium/*', requirePlan: 'pro' }
      ]}
      loginUrl="/login"
      upgradeUrl="/upgrade"
      loadingComponent={<Spinner />}
    >
      <Router>
        <Routes />
      </Router>
    </AutoProtect>
  )
}

Event Handlers

createAutoProtect({
  patterns: [...],
  
  onAccessGranted: (pattern, user) => {
    console.log('Access granted to:', pattern)
    analytics.track('page_access', { pattern })
  },
  
  onAccessDenied: (pattern, reason, user) => {
    console.log('Access denied:', reason)
    
    if (reason === 'not_authenticated') {
      // Custom login redirect with return URL
      window.location.href = `/login?return=${encodeURIComponent(window.location.href)}`
      return false // Prevent default redirect
    }
    
    return true // Allow default redirect
  },
  
  onRedirect: (url) => {
    console.log('Redirecting to:', url)
  }
})

Loading States

Show Loading While Checking

createAutoProtect({
  patterns: [...],
  showLoadingState: true,
  loadingSelector: '#app', // Element to show loading state
  loadingClass: 'is-loading' // Class to add during check
})

Custom Loading UI

createAutoProtect({
  patterns: [...],
  onCheckStart: () => {
    document.getElementById('loader').style.display = 'block'
  },
  onCheckComplete: () => {
    document.getElementById('loader').style.display = 'none'
  }
})

Caching

Access checks are cached to improve performance:
createAutoProtect({
  patterns: [...],
  cacheTimeout: 5 * 60 * 1000 // 5 minutes (default)
})
To clear cache:
autoProtect.clearCache()

Server-Side Rendering

For SSR frameworks, check access on the server:
// Next.js middleware
import { NextResponse } from 'next/server'

export function middleware(request) {
  const token = request.cookies.get('gately_auth_token')
  
  if (request.nextUrl.pathname.startsWith('/dashboard')) {
    if (!token) {
      return NextResponse.redirect(new URL('/login', request.url))
    }
  }
  
  return NextResponse.next()
}

Debugging

Enable debug mode:
createAutoProtect({
  patterns: [...],
  debug: true
})
This logs:
  • Pattern matching results
  • Access check outcomes
  • Redirect decisions

Best Practices

More specific patterns should come before general ones.
Ensure your login and upgrade URLs are consistent across patterns.
Consider what happens when users navigate directly to protected URLs.
Test all patterns with different user states (logged out, free, pro, etc.).