The Problem: When using Next.js with internal links (next/link
), you might find that navigating to dynamic routes works fine. However, when you try to go back to a previous page using the browser's back button, the URL changes but the page content does not. This issue occurs specifically with dynamic routes.
What's Happening: When you navigate through internal links and then hit the browser’s back button, the content of the previous page may "freeze" and not load correctly. This happens because of how the browser history is managed in your application. Moving forward again works fine, but going back remains problematic until you reach a non-dynamic route or a page not navigated through next/link
.
Probable Cause: The issue may arise if your code is manually updating the browser’s history using window.history.replaceState
or window.history.pushState
. For example, you might have code that updates the URL’s hash parameter based on user interaction:
useEffect(() => {
newHash
? window.history.replaceState(null, null, `#${newHash}`)
: window.history.replaceState(null, null, " ");
}, [newHash]);
This manual manipulation can interfere with Next.js’s internal handling of navigation.
The Solution: To fix this, ensure that you pass the current state of the window history when updating it. Here’s how you can adjust your code:
useEffect(() => {
newHash
? window.history.replaceState(window.history.state, "", `#${newHash}`)
: window.history.replaceState(window.history.state, "", " ");
}, [newHash]);
By passing window.history.state
, you maintain the integrity of the history object, allowing Next.js to handle navigation properly.
For more details and discussion on this issue, refer to this GitHub issue thread.
Implementing this solution should resolve the navigation issue and ensure smooth transitions between pages in your Next.js application.