next.js

Maintain previous page scroll position on browser back button on Next.js site


when I navigate from page A to page B using Next.js Link tag and click browser back button, the page A is scrolled to the top. How can I preserve the scroll position of page A?

You can test this on my next.js blog.. scroll to bottom of this page and click on an article link and hit browser back button, it gets scrolled to the top instead of preserving the scroll position.

source code: https://github.com/GorvGoyl/Personal-Site-Gourav.io


Solution

  • fixed it by adding this flag to next.config.js

    experimental: {
          scrollRestoration: true,
        },