redirectTarget method
Resolve a redirect target for location BEFORE the route builds.
This is the redirect-guard hook. Return a path to redirect to, or null
to allow the navigation. It is evaluated synchronously inside the router's
redirect callback, so a redirect-style guard resolves before any page
is built and the destination view mounts exactly once. Prefer this over
an imperative MagicRoute.to() inside handle: redirecting from handle
runs post-mount and remounts the destination.
Always return null when location already equals the target, otherwise
the redirect loops.
class EnsureAuthenticated extends MagicMiddleware {
@override
String? redirectTarget(String location) {
if (!Auth.check() && location != '/login') return '/login';
return null;
}
}
The default returns null (no redirect), so non-redirecting middleware
only need to implement handle.
Implementation
@override
String? redirectTarget(String location) {
if (!Gate.allows(ability, arguments) && location != unauthorizedRoute) {
return unauthorizedRoute;
}
return null;
}