Sub topic 9
Redirects and authentication guards
This chapter assumes you know how to declare a GoRouter with GoRoute entries and how context.go differs from context.push. It also assumes you can write a ChangeNotifier. You will learn how redirect decides where a navigation ends up, how to protect routes by login state, and how to avoid the errors that most often break guards.
What a redirect is
A redirect is a function that go_router calls before it builds any page for a new location. It receives the BuildContext and a GoRouterState describing the location being requested. It returns one of two things:
null, which means "this location is fine, continue".- A location string such as
'/login', which means "go there instead".
The signature is FutureOr<String?> Function(BuildContext context, GoRouterState state). The function can be synchronous or async. Because the redirect runs before the page is built, the user never sees a flash of the protected screen.
A redirect is part of the routing step and not part of navigation history. When a redirect fires, the original location is never added to the stack. The user cannot press back and land on a page they were not allowed to see.
A top-level authentication guard
The simplest guard is a single redirect on the GoRouter. It applies to every location in the app.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class AuthState extends ChangeNotifier {
bool _loggedIn = false;
bool get loggedIn => _loggedIn;
void logIn() {
_loggedIn = true;
notifyListeners();
}
void logOut() {
_loggedIn = false;
notifyListeners();
}
}
final AuthState auth = AuthState();
String? authRedirect(BuildContext context, GoRouterState state) {
final bool atLogin = state.matchedLocation == '/login';
if (!auth.loggedIn) {
if (atLogin) return null;
final String from = Uri.encodeComponent(state.uri.toString());
return '/login?from=$from';
}
if (atLogin) {
final String? from = state.uri.queryParameters['from'];
final bool safe =
from != null && from.startsWith('/') && !from.startsWith('//');
return safe ? from : '/';
}
return null;
}
final GoRouter router = GoRouter(
initialLocation: '/',
refreshListenable: auth,
redirect: authRedirect,
routes: <RouteBase>[
GoRoute(path: '/', builder: (context, state) => const HomeScreen()),
GoRoute(path: '/login', builder: (context, state) => const LoginScreen()),
],
);
void main() => runApp(MaterialApp.router(routerConfig: router));
class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Center(
child: ElevatedButton(
onPressed: auth.logOut,
child: const Text('Log out'),
),
),
);
}
}
class LoginScreen extends StatelessWidget {
const LoginScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Login')),
body: Center(
child: ElevatedButton(
onPressed: auth.logIn,
child: const Text('Log in'),
),
),
);
}
}The guard has three branches:
- Signed out and already on
/login: returnnull. Without this branch the redirect would send the user to/loginforever. - Signed out anywhere else: return
/login, with the requested location saved in afromquery parameter. - Signed in and on
/login: send the user to the saved location, or to/if there is none.
The refreshListenable: auth line makes the router run the redirect again whenever auth calls notifyListeners. That is why the login button only changes state and never calls context.go. The next chapter covers refreshListenable in detail.
How a redirect is evaluated
When a redirect returns a string, go_router does not navigate there directly. It runs the redirect again on the new location. The process repeats until the function returns null. This is why the atLogin check is needed. It is the case that ends the chain.
Which location to compare
GoRouterState offers several properties that look similar. Choosing the wrong one is a common source of bugs.
| Property | Contains | Use in a redirect |
|---|---|---|
| `state.matchedLocation` | The matched path, with parameters filled in and no query string, such as `/books/42` | Comparing against fixed paths like `/login` |
| `state.uri` | The full `Uri`, including the query string | Saving the original location, reading query parameters |
| `state.fullPath` | The route pattern, such as `/books/:id` | Matching a whole family of routes |
| `state.pathParameters` | Decoded path parameters | Per-resource checks |
Comparing state.uri.toString() with '/login' fails as soon as the login URL carries ?from=.... That mismatch produces a redirect loop. Use matchedLocation for path comparisons.
Public and protected areas
Real apps usually have more than one public page, such as a landing page or a password reset screen. A set of public paths keeps the guard readable.
const Set<String> publicPaths = <String>{'/login', '/signup', '/about'};
String? guard(BuildContext context, GoRouterState state) {
final bool isPublic = publicPaths.contains(state.matchedLocation);
if (!auth.loggedIn && !isPublic) {
return '/login?from=${Uri.encodeComponent(state.uri.toString())}';
}
return null;
}If some public paths also have sub-routes, test with startsWith on a prefix such as /auth. Be careful with prefixes: '/authors'.startsWith('/auth') is true. Compare against '/auth/' or match exact paths.
Route-level redirects
GoRoute has its own redirect parameter. It runs only when that route is part of the matched location. Use it for rules that belong to one area, such as an admin section.
GoRoute(
path: '/admin',
redirect: (context, state) => auth.isAdmin ? null : '/',
builder: (context, state) => const AdminScreen(),
),The top-level redirect runs first. Route-level redirects run afterwards, from the parent route down to the child. Keep authentication in the top-level function and put role or feature checks on the routes they affect. Then no one needs to read every route to know whether the app is protected.
Redirects and deep links
A deep link, or a URL typed into a browser, enters the app at an arbitrary location. The redirect sees that location like any other. A signed-out user who opens /books/42 is sent to /login?from=%2Fbooks%2F42. After login, the redirect returns the saved location and the user arrives at the book they asked for. Saving the original location is what makes guards work with deep links.
Async redirects
A redirect can return a Future. You might use this to read a token from secure storage when the app starts.
Future<String?> asyncGuard(BuildContext context, GoRouterState state) async {
final bool signedIn = await tokenStore.hasValidToken();
if (!signedIn && state.matchedLocation != '/login') return '/login';
return null;
}Use this sparingly. The router waits for the future before it shows anything, so a slow check leaves a blank screen. A better pattern is to load the session once at startup, store the result in your ChangeNotifier, and keep the redirect synchronous.
Common errors
- Redirect loop. Two rules send the user to each other, or the guard forgets the
nullcase for the login page. go_router stops afterredirectLimitredirects, which is 5 by default, and shows the error page. Fix the logic instead of raising the limit. - Guard never re-runs after login. The router only evaluates a redirect when a navigation happens. Without
refreshListenable, a change inAuthStatedoes nothing until the next navigation. - Using
contextto find auth state in the wrong place. The redirect'scontextcomes from the router, which may sit above your providers. If your auth object lives in a widget belowMaterialApp.router,context.readcan fail. Create the auth object before the router and share it, asauthis above. - Comparing the wrong location property. See the table above.
- Putting the check only in the UI. Hiding a button does not protect a route. Any URL can be opened directly, so the redirect is the real guard.
Exercise
A signed-out user opens the deep link /books/42?tab=reviews. Using the guard from this chapter, which location does the router show first, and where does the user end up after logging in?
Show answer
The guard returns /login?from=%2Fbooks%2F42%3Ftab%3Dreviews, so the login screen appears. It stores the full original URI, including the query string, because it encodes state.uri.toString(). After logIn calls notifyListeners, refreshListenable re-runs the redirect on the current location, where matchedLocation is /login. The user is now signed in, so the guard decodes the from parameter, sees that it starts with a single slash, and returns /books/42?tab=reviews. The user lands on the book page with the query intact.
Exercise
Why does the guard return null when the user is signed out and already at /login, and what happens if you remove that check?
Show answer
The router runs the redirect again on every location it returns. Without the null case, /login would redirect to /login, and so on. After redirectLimit redirects (5 by default) go_router stops and shows the error page instead of the login screen.