Preserving Return-To URLs
What you'll learn: How to capture where a user was heading before authentication and send them back there after logging in.
When you redirect an unauthenticated user to a login page, you're interrupting their journey. They clicked a link to /dashboard/reports, but got bounced to /login. Once they authenticate, the default behavior is sending them to a generic home page—frustrating! Preserving return-to URLs means remembering their original destination and completing their interrupted trip.
The Core Technique
There are two main approaches:
1. Location State (ephemeral)
When redirecting to login, pass the current location through Navigate's state:
// In your protected route/loader
if (!user) {
return <Navigate to="/login" state={{ from: location.pathname }} replace />;
}
Then in your login component, read it and redirect after success:
const location = useLocation();
const from = location.state?.from || '/';
// After successful login:
navigate(from, { replace: true });
2. Search Params (persistent across refreshes) Append the destination as a query parameter:
// Redirecting to login
<Navigate to={`/login?returnTo=${encodeURIComponent(location.pathname)}`} />
// After login
const [searchParams] = useSearchParams();
const returnTo = searchParams.get('returnTo') || '/';
navigate(returnTo, { replace: true });
When to Use Each
Use state for simple redirects within a session. Use search params when users might bookmark the login page or refresh before completing authentication.
Key Takeaway: Preserve the user's intended destination using either location state (for simplicity) or search params (for durability), then navigate there post-authentication to create a seamless experience.