'Page not scrolling to top when route changes in Nuxt JS

I'm trying to always go on the top of the page when route changes with Nuxt.

So I've put this into my app/router.scrollBehavior.js file:

export default function (to, from, savedPosition) {
  return { x: 0, y: 0 }
}

But it always returns to the last saved position (which is always null in my console by the way).

Any idea of what I could miss here?



Solution 1:[1]

At the end, GSAP was conflicting with OP's scrolling behavior.
Removing it, solved all the issues related to Nuxt, nothing was actually wrong with the router.scrollBehavior.js file.

Solution 2:[2]

According to the documentation:

https://nuxtjs.org/docs/configuration-glossary/configuration-router#scrollbehavior

The router.scrollBehavior.js file must be in the app folder, which in turn is in the project's root.

the file should name router.scrollBehavior.js.

You can console.log something in this function and check if it works.

Solution 3:[3]

For Nuxt v3.0.0-rc.3

Create file named route.global.ts on middleware/ folder

Then write this in file:

export default defineNuxtRouteMiddleware((to, from) => {
  if (to.path !== from.path && process.client) {
    window.scrollTo(0, 0)
  }
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kissu
Solution 2 Cianekjr
Solution 3 Emir Kabal