NextJS turn off scroll restoration on backwards navigation

878 Views Asked by At

I would like to turn off scroll restoration when clicking the back or forward button in the browser. I can't seem to find any information on how to do this.

As per the NextJS documentation:

"By default, Next.js will maintain the scroll position for backward and forward navigation."

"If you'd like to disable this behavior, you can pass scroll={false} to the component, or scroll: false to router.push() or router.replace()." ... the issue is that I am not using a Link or the Router explicitly, I am just using the back/forward button in the browser, so I'm not sure how to go about changing this.

1

There are 1 best solutions below

0
On

If you are using an app directory you can handle scroll restoration with next-scroll-restorer.

It relies on native History API. A lot of time was spent to develop this library and it is tested on the production websites. Also, there is a lot of integration tests that handles some annoying bugs that Next.js team did not fix during the past 2 years.