Redirecting the User After Login
After a successful login, the app should move the user somewhere useful instead of leaving them on the login form. Usually that is either a default page, such as a dashboard, or the protected page they originally tried to open before being asked to sign in. In a React app using React Router, you handle this with the useNavigate hook and the router's location state.
Navigating once the token arrives
Redirecting should happen only after the server has confirmed the credentials and you have stored the token. If you navigate before the response arrives, the destination page may load without a token and bounce the user straight back to login.
import { useContext, useState } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { AuthContext } from './AuthContext';
function LoginPage() {
const { login } = useContext(AuthContext);
const navigate = useNavigate();
const location = useLocation();
const [error, setError] = useState('');
const from = location.state?.from?.pathname || '/dashboard';
async function handleSubmit(event) {
event.preventDefault();
const form = new FormData(event.currentTarget);
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(Object.fromEntries(form)),
});
if (!res.ok) throw new Error('Invalid email or password');
const data = await res.json();
login(data.token);
navigate(from, { replace: true });
} catch (err) {
setError(err.message);
}
}
return (
<form onSubmit={handleSubmit}>
<input name="email" type="email" required />
<input name="password" type="password" required />
{error && <p>{error}</p>}
<button type="submit">Sign in</button>
</form>
);
}
Remembering where the user was going
The from value in the example comes from the protected route. When a signed-out user tries to open, say, /orders, the route guard sends them to /login and passes the current location along in state. After login, the app reads that state and sends them back to /orders instead of a generic page.
import { Navigate, useLocation } from 'react-router-dom';
function RequireAuth({ isLoggedIn, children }) {
const location = useLocation();
if (!isLoggedIn) {
return <Navigate to="/login" replace state={{ from: location }} />;
}
return children;
}
If someone opens the login page directly, there is no state, so the fallback '/dashboard' is used.
Why replace matters here
Passing { replace: true } swaps the login page out of the browser history instead of adding a new entry. Without it, pressing the back button after logging in takes the user back to the login form, which feels broken because they are already signed in. Replacing the entry makes back go to whatever page came before login.
Pitfall: redirecting a user who is already logged in
A user who is already signed in might visit /login through a bookmark. Showing them the form again is confusing. Check the auth state at the top of the login page and render <Navigate to="/dashboard" replace /> if they are logged in.
Be careful not to create a loop. If the dashboard guard thinks the user is logged out while the login page thinks they are logged in, each page keeps redirecting to the other. Both checks must read the same source of truth, usually one auth context.
Also, never redirect to a full URL taken from a query string without checking it. An attacker could craft a login link that forwards users to another site after they sign in. Accept only internal paths that start with a single /.
One more detail: keep the redirect logic in one place. Scattering navigate calls across several components makes it hard to change the default landing page later, and easy to miss one when you do.
What to remember
Navigate after the token is saved, send users back to the page they asked for using location state, fall back to a sensible default, and use replace so the login form drops out of history. Keep the logged-in check in one place so guards and the login page agree.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.