How to use Next.js Middleware for authentication guards, role-based redirects, geolocation, and request modification. Runs at the edge before your pages load.
This is a strong, production-ready Next.js middleware pattern that:
Uses Supabase SSR client correctly at the Edge
Skips static assets and non-critical paths for performance
Implements clear route tiers: public, protected, admin
Adds timeouts and graceful failure handling
Preserves redirect intent after login
Supports advanced user validation (banned/inactive) and preview mode
Below is a distilled, reusable version that combines the best ideas from your OpportunIQ and Hoop Almanac setups into a single, opinionated middleware you can drop into other projects.
Change route tiers: Edit PUBLIC_PATHS, PROTECTED_PATHS, and ADMIN_PATHS.
Swap auth provider: Replace the Supabase client with your auth library but keep the same control flow.
Customize validation: Extend validateUser with your own flags (e.g. emailVerified, plan, trialExpired).
Preview/demo flows: Adjust the isPreviewMode logic and exceptions around onboarding or demo routes.
This gives you a single, centralized, edge-optimized guardrail for authentication, authorization, and user state handling across your app.