Sub topic 10
Sending Deep Links Through Login
A deep link to /products/42 often points at a screen that needs a signed-in user. This chapter covers how to send signed-out users to login and bring them back to the screen the link named. It also covers the startup case, where the app doesn't yet know whether anyone is signed in.
This chapter assumes you have a working go_router setup with path parameters (see the earlier chapters on routing) and that you know what ChangeNotifier does.
The problem
A signed-out user taps https://example.com/products/42. Three outcomes are possible:
- The app shows the product anyway. This leaks protected content.
- The app shows the login screen, and after login the user lands on the home screen. This loses the link.
- The app shows the login screen, and after login the user lands on product 42. This is the one you want.
To get the third outcome, the app has to remember the original destination while the user logs in. The usual way is to put it in a query parameter on the login URL.
How go_router redirects work
GoRouter accepts a top-level redirect callback. It runs on every navigation, including the one caused by an incoming link. It returns one of two things:
null, which means "let this navigation proceed".- A location string, which means "go there instead".
If the callback returns a location, the router runs redirect again on that new location. This continues until it returns null or hits redirectLimit (default 5). A redirect that always returns a location, such as one that sends /login back to /login, throws an error once the limit is hit.
The refreshListenable parameter takes a Listenable. When it notifies, the router re-evaluates redirect for the current location. This is how a login or logout moves the user without any explicit context.go call.
flowchart TD
A["Link opens /products/42"] --> B{"Auth state restored?"}
B -- "No" --> C["Redirect to /splash?from=/products/42"]
C --> B
B -- "Yes" --> D{"Signed in?"}
D -- "Yes" --> E["Show ProductScreen"]
D -- "No" --> F["Redirect to /login?from=/products/42"]
F --> G["User signs in"]
G --> H["refreshListenable fires"]
H --> I["Redirect to /products/42"]
I --> EThe diagram above is a sketch, so it gives the two phases as labels. The code below implements both.
Tracking auth state
The guard needs more than a boolean. On a cold start the app may still be reading a token from secure storage, and during that time "not logged in" is not yet true. Treat this as a third state.
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class AuthController extends ChangeNotifier {
bool _initialized = false;
bool _loggedIn = false;
bool get isInitialized => _initialized;
bool get isLoggedIn => _loggedIn;
/// Call once at startup, before or just after runApp.
Future<void> restoreSession() async {
// Replace with a real read from secure storage.
await Future<void>.delayed(const Duration(milliseconds: 300));
_loggedIn = false;
_initialized = true;
notifyListeners();
}
Future<void> signIn() async {
_loggedIn = true;
notifyListeners();
}
void signOut() {
_loggedIn = false;
notifyListeners();
}
}
final auth = AuthController();The redirect function
The guard has four jobs:
- While auth is not restored, send everything to
/splash, remembering the target. - When auth is restored, send
/splashon to the remembered target. - If the user is signed out and the target is protected, send them to
/login, remembering the target. - If the user is signed in and on
/login, send them to the remembered target.
const _publicPaths = {'/', '/login', '/splash'};
String _withFrom(String path, String target) =>
Uri(path: path, queryParameters: {'from': target}).toString();
/// Accepts only in-app paths. Anything else becomes '/'.
String safeFrom(String? from) {
if (from == null || from.isEmpty) return '/';
if (!from.startsWith('/') || from.startsWith('//')) return '/';
final uri = Uri.tryParse(from);
if (uri == null || uri.hasScheme || uri.hasAuthority) return '/';
if (uri.path == '/login' || uri.path == '/splash') return '/';
return from;
}
String? authRedirect(BuildContext context, GoRouterState state) {
final location = state.matchedLocation;
if (!auth.isInitialized) {
return location == '/splash'
? null
: _withFrom('/splash', state.uri.toString());
}
if (location == '/splash') {
return safeFrom(state.uri.queryParameters['from']);
}
if (!auth.isLoggedIn && !_publicPaths.contains(location)) {
return _withFrom('/login', state.uri.toString());
}
if (auth.isLoggedIn && location == '/login') {
return safeFrom(state.uri.queryParameters['from']);
}
return null;
}Some details matter here:
state.uri.toString()includes the query string, so?ref=emailsurvives the round trip.Uri(path:, queryParameters:)percent-encodes the value. When you readstate.uri.queryParameters['from'], it is already decoded. Don't callUri.decodeComponenton it again, because a target containing%would be corrupted.matchedLocationis the matched path without query parameters, which is what you want for comparing against/login.
Wiring it into the router
final router = GoRouter(
initialLocation: '/',
refreshListenable: auth,
redirect: authRedirect,
routes: [
GoRoute(path: '/', builder: (c, s) => const HomeScreen()),
GoRoute(path: '/splash', builder: (c, s) => const SplashScreen()),
GoRoute(path: '/login', builder: (c, s) => const LoginScreen()),
GoRoute(
path: '/products/:id',
builder: (c, s) => ProductScreen(
id: s.pathParameters['id']!,
ref: s.uri.queryParameters['ref'],
),
),
],
errorBuilder: (c, s) => NotFoundScreen(uri: s.uri),
);
void main() {
auth.restoreSession();
runApp(MaterialApp.router(routerConfig: router));
}The login screen does not navigate. It only changes the auth state:
class LoginScreen extends StatelessWidget {
const LoginScreen({super.key});
@override
Widget build(BuildContext context) => Scaffold(
body: Center(
child: FilledButton(
onPressed: auth.signIn,
child: const Text('Sign in'),
),
),
);
}When signIn calls notifyListeners, the router re-runs authRedirect for /login?from=%2Fproducts%2F42. The signed-in branch returns /products/42, and the user lands there. Because the redirect carries the navigation, the same code works whether the user logs in with a button, a biometric prompt, or an OAuth callback.
The remaining screens (HomeScreen, SplashScreen, ProductScreen, NotFoundScreen) are ordinary widgets from the earlier chapters. SplashScreen can be a Scaffold with a CircularProgressIndicator.
Cold start versus a running app
Both cases go through the same redirect, but they behave differently:
| Situation | What happens |
|---|---|
| Cold start, no stored session | Auth is not initialized, so the link goes to `/splash?from=...`. After `restoreSession` finishes, the redirect goes to `/login?from=...`. |
| Cold start, valid stored session | Same path through `/splash`, but the final redirect returns the original link. |
| App running, signed in | Auth is initialized, so the link opens directly. |
| App running, session expired | `signOut` notifies, and `refreshListenable` moves the user to login. The current screen becomes the `from` target. |
Without the splash step, a cold-start link would be evaluated while isLoggedIn is still false. A user with a valid session would be sent to login for a moment. If your login screen then auto-signs in, the flow can still recover. A visible login flash is poor behavior, and an expired-token check can make it worse.
Per-route redirects
You don't have to put all rules in one function. A GoRoute accepts its own redirect, which runs only when that route matches. This suits rules about one area, such as an admin section:
GoRoute(
path: '/admin',
redirect: (context, state) =>
auth.isAdmin ? null : '/',
builder: (c, s) => const AdminScreen(),
),The top-level redirect runs first, then route-level ones. Keep the "is the user signed in" rule at the top level, so you have one place to read when a link lands on the wrong screen.
Common errors
- Redirect loop.
/loginis not in the public set, so a signed-out user is sent from/loginto/login?from=...repeatedly. The router throws afterredirectLimitredirects. - Nothing happens after login.
refreshListenableis missing, orsignInforgotnotifyListeners. The router never re-evaluates. fromgrows on each bounce. The redirect wraps an existing/login?from=...target in a newfrom. Check_publicPathsbefore building a new login URL, asauthRedirectdoes.- Query parameters lost. You stored
state.matchedLocationinstead ofstate.uri.toString(). - Double-decoded target. You called
Uri.decodeComponenton a value thatqueryParametershad already decoded. - Guard reads stale state. The
redirectclosure captured a copy of the auth value. Read from the liveauthobject each time.
Summary
Remember the original URL in from, validate it before using it, and let refreshListenable plus redirect move the user after login. Add an initialization state so cold-start links wait for the session check instead of being treated as signed out.
Exercise
A signed-out user opens /products/42?ref=email. Using the code in this chapter, what are the exact locations the router visits if auth restore takes 300 ms and the user then has no stored session, and which part of the code prevents the ref value from being lost?
Show answer
The router first redirects to /splash?from=%2Fproducts%2F42%3Fref%3Demail because isInitialized is false. When restoreSession finishes and notifies, authRedirect runs on /splash, reads and validates from, and returns /products/42?ref=email. That location is evaluated again. The user is signed out and the path is not public, so the router redirects to /login?from=%2Fproducts%2F42%3Fref%3Demail. After sign-in, the redirect returns /products/42?ref=email. The ref value survives because _withFrom is given state.uri.toString(), which includes the query string, and Uri(queryParameters:) encodes it.
Exercise
Why does safeFrom reject the value //evil.example/path even though it starts with /?
Show answer
A value starting with // is a scheme-relative URL. Parsed as a URI it has an authority (evil.example), so it points to another host. safeFrom rejects it with the explicit startsWith('//') check and with the hasAuthority check, and returns / instead.