While working onRemotebear, I recently discovered that Next.js doesn’t handle scroll restoration automatically. So, for example, if you navigate back to a previous page of your app, Next.js will always show it scrolled to the top, regardless of the scroll position it had when you left it.
Experimental scroll restoration flag
Luckily, Next.js hasan experimentalscrollRestoration
flag that you can enable to automatically restore the scroll positions.
You can enable it in yournext.config.js
file this way:
module.exports={experimental:{scrollRestoration:true,},};
next-router-scroll
For my use case, this solution is working fine, but there are some cases where you need to take control of how your application scroll is handled; namely, you may want to restore scroll when the user is navigating within your application pages, but you need to do extra work before or after the page has changed, either by using some sort of page transition or any other feature.
In these cases, I’d suggest you give@moxy/next-router-scroll
a try: This package is built on top ofscroll-behavior
and it actively listens to Next.js router events, writing the scroll values associated with the current location in the Session Storage and reading these values wheneverupdateScroll()
is called.
Completely disabling scroll restoration
There’s one inconsistency I noticed around not making scroll restoration work automatically in Next.js: by default, scroll restoration doesn’t work when the navigation logic is being handled by JavaScript, but it works fine when it’s handled by the browser (e.g.: on a full-refresh or while navigating whit JavaScript disabled).
So, in the rare occasions where you want to fully disable scroll restoration, remember to add this snippet to the<head>
of your project:
importHeadfrom"next/head";exportdefaultfunctionScrollRestorationDisabler(){return(<Head>{/* Tell the browser to never restore the scroll position on load */}<scriptdangerouslySetInnerHTML={{__html:`history.scrollRestoration = "manual"`,}}/></Head>);}
Top comments(6)

- Email
- LocationRasht, Iran
- EducationCE at SUT
- WorkWeb Development
- Joined
Thank you!At first it was working only with hashtag navigation, but then I realized that my main scrolling element is not thebody
tag. Now it's all working properly.

- LocationIndonesia
- EducationMaster
- WorkSr. Backend Developer at Fabelio
- Joined
hey nice find dude. thanks, i need this one too
For further actions, you may consider blocking this person and/orreporting abuse