go_guardian

NestJS-style route guards for GoRouter. Declare guards on routes, inherit them through shells, compose them with existing redirects.

Works with every state management approach — Provider, Bloc, Riverpod, GetX, Signals, or plain singletons.

GuardedRoute(
  path: '/dashboard',
  guards: [AuthGuard.stateless(isAuthenticated: () => auth.isLoggedIn)],
  builder: (_, __) => DashboardScreen(),
)

Full documentation →


Install

dependencies:
  go_guardian: ^0.2.1

One import gives you everything — go_guardian re-exports go_router:

import 'package:go_guardian/go_guardian.dart'; // includes GoRouter, GoRoute, etc.

30-second overview

1. Pick a guard — four are built-in:

Guard What it checks Default redirect
AuthGuard Is the user logged in? /login
RoleGuard Does the user have a required role? /unauthorized
OnboardingGuard Has the user finished onboarding? /onboarding
MaintenanceGuard Is the app under maintenance? /maintenance

2. Attach it to a route:

GuardedRoute(
  path: '/admin',
  guards: [RoleGuard.stateless(hasRole: (roles) => user.hasAny(roles))],
  guardMeta: GuardMeta({'roles': ['admin']}),
  builder: (_, __) => AdminScreen(),
)

3. Or inherit through a shell:

GuardedShellRoute(
  guards: [
    AuthGuard.stateless(isAuthenticated: () => auth.isLoggedIn),
    OnboardingGuard.stateless(isOnboarded: () => auth.isOnboarded),
  ],
  builder: (ctx, state, child) => AppShell(child: child),
  routes: [
    GuardedRoute(path: '/home', ...),   // inherits Auth + Onboarding
    GuardedRoute(path: '/profile', ...), // inherits Auth + Onboarding
    GuardedRoute(
      path: '/admin',
      guards: [RoleGuard(...)],         // inherits Auth + Onboarding + own RoleGuard
    ),
    GoRoute(path: '/about', ...),       // plain GoRoute — NOT affected
  ],
)

Shell guards are prepended to each child GuardedRoute's own guards at construction time. Plain GoRoute children opt out of the guard system.

4. Redirect away from routes with DiscardedRoute:

DiscardedRoute.stateless(
  path: '/login',
  discardWhen: () => auth.isLoggedIn,
  redirectTo: '/home',
  builder: (_, __) => LoginScreen(),
)

5. Reactive re-evaluation:

GoRouter(
  refreshListenable: GuardRefreshNotifier.from([authNotifier, configNotifier]),
  routes: [ ... ],
)

That's it. Guards run in priority order, the first redirect wins.


State management

Every built-in guard has two constructors — one that receives BuildContext, one that doesn't:

// Provider / Bloc
AuthGuard(isAuthenticated: (ctx) => ctx.read<AuthService>().isLoggedIn)

// Riverpod
AuthGuard.stateless(isAuthenticated: () => ref.read(authProvider).isLoggedIn)

// GetX
AuthGuard.stateless(isAuthenticated: () => Get.find<AuthCtrl>().isLoggedIn)

// Signals
AuthGuard.stateless(isAuthenticated: () => isLoggedIn.value)

// Singleton
AuthGuard.stateless(isAuthenticated: () => AuthService.instance.isLoggedIn)

Custom guards

Extend RouteGuard and implement check():

class SubscriptionGuard extends RouteGuard {
  @override
  int get priority => 15; // lower = runs first

  @override
  FutureOr<String?> check(BuildContext context, GoRouterState state, GuardMeta meta) {
    if (hasActiveSubscription) return null; // allow
    return '/subscribe';                    // redirect
  }
}

Guard composition

Combine guards inline with & (AND), | (OR), and ~ (NOT):

guards: [AuthGuard(...) & (PremiumGuard(...) | TrialGuard(...))]

Brownfield migration

Already have redirect: functions? Wrap them with GuardChain:

redirect: GuardChain
  .existing(myOldRedirect)
  .then(AuthGuard.stateless(isAuthenticated: () => auth.isLoggedIn))
  .existingWins(), // old redirect runs first; swap to .guardsWin() when ready

Debugging

if (kDebugMode) GoGuardian.observer = DebugGuardObserver();

Prints every guard evaluation with timing to the console.

Testing

Unit-test guards without a widget tree:

final harness = GuardTestHarness();
final result = await harness.check(AuthGuard.stateless(isAuthenticated: () => true));
expect(result, isNull); // null = allowed

Example app

The example/ folder is an "everything demo" — start as a guest and progressively unlock access:

Flow: Login → OnboardingGuard redirects to /onboarding → Complete → Home (with toggles for every guard)

Tab / Screen Feature
Login DiscardedRoute + deep link ?continue= banner
Onboarding OnboardingGuard redirect (via shell inheritance)
Home Inherited shell guards, toggle controls, access status
Admin RoleGuard + GuardMeta
Premium Custom PremiumGuard (extends RouteGuard)
VIP Guard composition: RoleGuard | PremiumGuard
Settings GuardChain brownfield migration
Maintenance MaintenanceGuard (priority -10)

Also demonstrates GuardRefreshNotifier, DebugGuardObserver, and shell guard inheritance.

Requirements

Dart >=3.0.0, Flutter >=3.10.0, go_router >=13.0.0 <16.0.0.

License

MIT

Libraries

go_guardian
NestJS-style declarative route guards for GoRouter.