Question
Answer and Explanation
To redirect to the previous page after login in Next.js, you can utilize the useRouter
hook from next/router
and store the previous URL. Here’s a detailed explanation with example code:
1. Import useRouter
:
- Import the useRouter
hook from next/router
in your login component.
2. Store the Previous URL:
- You can store the previous URL in several ways, either by checking the router.asPath
in the page that redirects to the login page, or by storing it in the browser's localStorage
or a cookie before redirecting to the login page.
3. Redirect After Login:
- After a successful login, use router.push
to navigate to the stored previous URL. If no previous URL is stored, redirect to a default page (e.g., the home page).
4. Example Code:
First, in your login page (e.g., `pages/login.js`):
import { useRouter } from 'next/router';
function LoginPage() {
const router = useRouter();
const handleLogin = async () => {
// Simulate login, get token, etc.
const previousUrl = localStorage.getItem('previousUrl') || '/';
localStorage.removeItem('previousUrl');
router.push(previousUrl);
};
return (
<div>
<button onClick={handleLogin}>Login</button>
</div>
);
}
export default LoginPage;
Then, in your page that initiates the login redirect (for example, a page where a user needs to be logged in):
import { useRouter } from 'next/router';
function SecurePage() {
const router = useRouter();
const handleAuthCheck = () => {
const isLoggedIn = false; // Simulate login check
if(!isLoggedIn){
localStorage.setItem('previousUrl', router.asPath);
router.push('/login');
}
};
handleAuthCheck()
return (<div> Secure Content </div>);
}
export default SecurePage;
5. Important Considerations:
- Always check if a previousUrl
exists before redirecting to prevent unintended redirects.
- You can implement error handling in your handleLogin
if an invalid or malicious URL was stored as a previousUrl
.
- For more complex authentication flows, consider using a dedicated authentication library like NextAuth.js, which handles redirection and session management.
By following these steps, you can successfully implement redirection to the previous page after login in your Next.js application, enhancing user experience.