Sub topic 13
Redirects and authentication guards
This chapter shows how to send users to a different location before a screen builds. The main use is keeping signed-out users away from protected screens. It assumes you can set up a GoRouter with MaterialApp.router, as in the previous chapter, and that you know ChangeNotifier and async/await in Dart.
What a redirect does
A redirect is a function that go_router runs each time it resolves a location. The location can come from context.go, context.push, a deep link, or the browser's address bar. The function receives the BuildContext and a GoRouterState and returns one of two things:
- A
String, which is a new location. go_router discards the original target and navigates there. null, which means "leave this navigation alone".
Redirects run before any builder, so a guarded screen never builds for a user who should not see it. That is the difference from checking the login state inside the screen's build method, which lets the screen flash briefly and can start network calls it should not start.
The signature is FutureOr<String?> Function(BuildContext, GoRouterState). The function can therefore be async, for example to read a token from secure storage. Keep it fast, though, because navigation waits for it.
How redirects are evaluated
gorouter runs the top-level redirect first, then the redirect of each matched GoRoute, from parent to child. If any of them returns a location, gorouter restarts the process with that new location. It stops when every redirect returns null.
The loop has a cap. GoRouter.redirectLimit defaults to 5. If the redirects keep producing new locations beyond that count, go_router shows its error page, and in debug builds it throws an assertion. This is how you find out about a redirect loop.
A complete authentication guard
The example below is a runnable app. AuthNotifier holds the login state. The router redirects signed-out users to /login and remembers where they were going.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class AuthNotifier extends ChangeNotifier {
bool _loggedIn = false;
bool get isLoggedIn => _loggedIn;
void logIn() {
_loggedIn = true;
notifyListeners();
}
void logOut() {
_loggedIn = false;
notifyListeners();
}
}
final AuthNotifier authNotifier = AuthNotifier();
final GoRouter router = GoRouter(
initialLocation: '/',
refreshListenable: authNotifier,
redirect: (context, state) {
final loggedIn = authNotifier.isLoggedIn;
final atLogin = state.matchedLocation == '/login';
if (!loggedIn) {
if (atLogin) return null;
final from = Uri.encodeComponent(state.uri.toString());
return '/login?from=$from';
}
if (atLogin) {
final from = state.uri.queryParameters['from'];
if (from != null && from.startsWith('/')) return from;
return '/';
}
return null;
},
routes: [
GoRoute(
path: '/',
builder: (context, state) => const HomeScreen(),
routes: [
GoRoute(
path: 'products/:id',
builder: (context, state) =>
ProductScreen(id: state.pathParameters['id']!),
),
],
),
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'),
actions: [
IconButton(
icon: const Icon(Icons.logout),
onPressed: authNotifier.logOut,
),
],
),
body: Center(
child: ElevatedButton(
onPressed: () => context.go('/products/42'),
child: const Text('Open product 42'),
),
),
);
}
}
class ProductScreen extends StatelessWidget {
const ProductScreen({super.key, required this.id});
final String id;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Product $id')),
body: Center(child: Text('Details for product $id')),
);
}
}
class LoginScreen extends StatelessWidget {
const LoginScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sign in')),
body: Center(
child: ElevatedButton(
onPressed: authNotifier.logIn,
child: const Text('Sign in'),
),
),
);
}
}Four details in this code matter.
state.matchedLocationversusstate.uri.matchedLocationis the path that matched a route, without query parameters. It is the right value for comparing against/login.state.uriis the full location including the query, so it is what you save as the return target.- Both branches of the login check. The first
ifsends signed-out users to the login page. The second sends signed-in users away from it. Without the second, a signed-in user could open/loginthrough a stale deep link. - No navigation call after sign-in. The login button only calls
authNotifier.logIn(). Because the router listsauthNotifieras itsrefreshListenable, the notifier'snotifyListeners()makes the router re-runredirectfor the current location (/login?from=...). The second branch then returns the saved target. - Validating
from. The value comes from the URL, so it is untrusted input. Requiring it to start with/stops a crafted link from sending users to an unexpected target. Also encode it withUri.encodeComponent, because the saved location contains?and&characters that would otherwise corrupt the outer query string.
Route-level redirects
A top-level redirect applies to every location, so rules about one area of the app belong on that area's route. A GoRoute accepts its own redirect. It runs only when the location matches that route or one of its children.
GoRoute(
path: 'admin',
// authNotifier.isAdmin is an app-defined getter.
redirect: (context, state) => authNotifier.isAdmin ? null : '/',
builder: (context, state) => const AdminScreen(),
),A common split is to keep the sign-in check at the top level and put role checks, such as admin-only or premium-only areas, on the routes they protect. Route-level redirects run after the top-level one, so by then you know the user is signed in.
Handling the startup state
Real apps often do not know the login state at launch, because the token is still being read from storage. If the redirect treats "unknown" as "signed out", the user sees the login screen for a moment and then jumps to the home screen. Model three states instead, and add a splash route.
enum AuthStatus { unknown, signedOut, signedIn }
String? guard(AuthStatus status, String location) {
switch (status) {
case AuthStatus.unknown:
return location == '/splash' ? null : '/splash';
case AuthStatus.signedOut:
return location == '/login' ? null : '/login';
case AuthStatus.signedIn:
return (location == '/login' || location == '/splash') ? '/' : null;
}
}Call guard(authNotifier.status, state.matchedLocation) from the top-level redirect. A plain function like this is also easy to unit test with no widgets. Each state returns null for its own page, which is what prevents a loop.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| The login route is not exempt from the redirect | Redirect loop, then the error page after 5 hops | Return `null` when already at `/login` |
| Missing `refreshListenable` | Signing in or out changes nothing until the next navigation | Pass the auth `ChangeNotifier` |
| Comparing `state.uri.toString()` to `/login` | The guard fails when the URL has a query string | Compare `state.matchedLocation` |
| Reading auth state from a widget tree you cannot reach | `redirect` cannot find the state | Use a global or injected object, as `authNotifier` is here |
| Treating "unknown" as signed out | Login screen flashes at launch | Add an `unknown` status and a splash route |
| Guarding only with a hidden button | Deep links still reach the screen | Always enforce the rule in `redirect` |
Limits of a client-side guard
A redirect decides what the app shows. It does not protect data. Anyone who can modify the app can bypass it, so the server must still reject unauthorized requests. Treat the guard as a user-experience tool that prevents confusing screens and wasted requests.
Also decide how back navigation behaves after a redirect. context.go replaces the stack, so after sign-in the user cannot press back to return to the login screen. That is usually what you want.
Exercise
Exercise
In the guard above, a signed-in user opens the link /login?from=%2Fproducts%2F42. What does the top-level redirect return, and why does it not loop?
Show answer
It returns /products/42. The user is signed in and matchedLocation is /login, so the second branch reads the from query parameter, finds it starts with /, and returns it. go_router then re-runs the redirect for /products/42. That location is not /login and the user is signed in, so the redirect returns null and the screen builds. The loop ends because the second pass returns null.
Exercise
A signed-out user taps a notification that opens /products/7. Describe the sequence of locations the router visits until the user is looking at product 7, assuming they sign in on the login screen.
Show answer
The router first resolves /products/7. The redirect sees a signed-out user and returns /login?from=%2Fproducts%2F7. The redirect runs again for that location, sees atLogin is true, and returns null, so the login screen builds. When the user signs in, notifyListeners() makes the router re-run the redirect for the current location. The user is now signed in at /login, so it returns /products/7, and the redirect runs once more and returns null, so the product screen builds.