How to Implement Redirect After Login in a Next.js Application (Redux,MERN)
daiyan1998
Posted on September 6, 2024
In many web applications, you want users to return to the page they were originally trying to access after logging in. For example, if a user tries to place an order but isn’t logged in, it’s common to redirect them to a login page. After successful authentication, you want to send them back to the original page—like an order screen. This blog will show you how to implement this functionality in a Next.js application using React hooks and query parameters.
1. Setting Up the Redirect Logic on Protected Pages
In this example, we’ll use a PlaceOrderScreen
component where the user is required to log in before placing an order. We’ll check whether the user is logged in by looking at the userInfo
object from the Redux store. If the user is not logged in, we’ll redirect them to the login page, passing the current URL as a query parameter.
Here's the key code to achieve this in PlaceOrderScreen
:
import { usePathname} from "next/navigation";
const PlaceOrderScreen = () => {
const router = useRouter();
const { userInfo } = useSelector((state) => state.auth); // Get user info
const pathName = usePathname(); // Get current URL
const placeOrderHandler = async () => {
if (!userInfo) router.push(/login?redirect=${pathName}
); // Redirect to login
// Rest of the order logic...
};
return (/* UI Code */);
};
Key Points:
useRouter and usePathname: These hooks help us capture the current URL (
pathName
) and handle redirections (router.push()
).Redirect with Query Parameter: When the user is not logged in, we use
router.push(
/login?redirect=${pathName})
to redirect them to the login page and append the current page's URL as a query parameter (redirect
).
2. Handling the Redirect After Login
Once the user is successfully authenticated, they should be redirected back to the original page they were trying to access (e.g., PlaceOrderScreen
). We achieve this by retrieving the redirect
query parameter on the login screen and using it to navigate back to the original page.
Here’s the key code in your LoginScreen
:
import { usePathname, useRouter } from "next/navigation";
export default function LogInScreen() {
const router = useRouter();
const searchParams = useSearchParams(); // Get query parameters
const { userInfo } = useSelector((state) => state.auth);
React.useEffect(() => {
if (userInfo) return router.push(searchParams.get("redirect") || "/"); // Redirect after login
}, [userInfo]);
const handleSubmit = async (event) => {
event.preventDefault();
// Handle form submission and login logic...
};
return (/* UI Code */);
}
Key Points:
useSearchParams: This hook allows us to access query parameters in the URL, like
redirect
.React.useEffect: After the user logs in (i.e.,
userInfo
is available), we check if theredirect
query parameter exists. If it does, the user is redirected to that page; otherwise, they are sent to the homepage ("/"
).
3. How the Flow Works
- User Tries to Place an Order:
- If the user is not logged in, they are redirected to the login page with the current URL as a query parameter (e.g.,
/login?redirect=/place-order
).
- User Logs In:
- On the
LoginScreen
, we retrieve theredirect
parameter and redirect the user back to that page after successful authentication.
- User is Returned to the Original Page:
- The user is seamlessly redirected back to the
PlaceOrderScreen
(or any page they were originally trying to access).
Conclusion
Implementing a post-login redirect flow in Next.js involves passing the original page URL as a query parameter during login redirects and handling that parameter after the user authenticates. By using useRouter
and useSearchParams
effectively, you can create a smooth experience where users are returned to where they left off after logging in.
This approach can be applied to other scenarios where users need to authenticate before accessing a page, ensuring a seamless user experience across your Next.js app.
With this method, your application provides a more intuitive and polished experience, keeping users on track even when login is required mid-process.
Posted on September 6, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 30, 2024
November 30, 2024