I am developing a feature in a Next.js app where a modal, accessible via a parallel route, contains tabs that modify the searchParams of the URL as they are interacted with. The modal can be opened using , and it incorporates a ‘back’ button intended to navigate users to the previous page, using router.back().
Problem: When users open the modal by clicking the , everything works as expected. However, when users access the modal by directly entering its URL into the browser, pressing the 'back' button returns them to the browser's new tab page, not a page within my app.
This situation is challenging because I aim to maintain intuitive navigation within the app, ensuring that users can return to their initial page, despite any alterations to the URL’s searchParams caused by engaging with the modal's tabs. If the modal is accessed directly via URL entry, the 'back' button should instead lead users to the home page.
Attempted Solutions: To solve this, I tried to enforce that router.back() is only invoked if the previous page is of the same origin; otherwise, the user is redirected to the home page.
Here’s the code representing my approach:
function handleClose() {
if (window?.history?.state?.idx > 0) {
router.back();
} else {
router.push("/home");
}
}
I referred to a related GitHub discussion suggesting the use of window?.history?.state?.idx > 0 to make this decision, but it didn’t yield the expected results. It seems window.history.state does not have an idx property.
Additionally, I attempted to verify the same origin using document.referrer, but it consistently returns an empty string, rendering it unhelpful for this scenario.
I have found another StackOverflow question which is related, however the proposed solution doesn't seem to work with parallel routes. isWithinPage
is always false.
Question: How can I accurately implement the ‘back’ button so that it navigates users to the original page within the app, regardless of the route changes induced by modified searchParams, and redirects to the home page when the modal is accessed directly via the URL?
Any help or insights on how I can achieve this would be greatly appreciated.
Update I've discovered that I can solve the problem related to searchParams by adding replace={true} in the component props for each tab. Now I only need to resolve the issue related to enforcing that router.back() is only invoked if the previous page is of the same origin.
function handleClose() {
if (window?.history?.length >= 1) {
router.back();
} else {
router.push("/home");
}
}
This handles the browser default tab but not the case if the user visited another website before yours in the same tab.