Nuxt - How to find the previous route?

13,858

Solution 1

In your page you can add asyncData hook which have access to context object with from property:

asyncData({ from }) {
  console.log(from);
}

Solution 2

in nuxt static methods where you have access to nuxt context ex: asyncData or middlewares :

asyncData({from}){
    // do something with from
}

but if you want to get the prev route in vue instance you can use

this.$nuxt.context.from

also, remember that from can be undefined if there wasn't any prev page in the browser history

Solution 3

There is no out of the box way to get this information.

What you can do is attach a beforeRouteEnter as a global guard and save the route before navigating to a new route.

Then you can check to see if there is a previous route saved and execute this.$router.go(-1)

If you are using the router in history mode you could be tempted to use the History api that vue-router is using to get this information. But HistoryApi doesn't allow for this as this would be a huge privacy problem. You could see the entire history of the user in the current tab.

Solution 4

In the [middleware] directory you can put this script [routing.js]:

/* eslint-disable no-undef */
/* eslint-disable no-console */
export default function (context) {
  // current route
  console.log('route=', context.route.name)
  // previous route
  if (process.client) {
    const from = context.from
    console.log('from=', from)
  }
}

In [nuxt.config.js]:

router: {
  ...
  middleware: 'routing'
},

Whenever you change the current page in the client you should see a log showing the previous page. Maybe it can help you.

Solution 5

You can achieve this by implementing the Vue Navigation guards, on the component/page.

<script>
export default {
  beforeRouteEnter(to, from, next) {
    console.log(from)
    next()
  },
  data() {
    return {
      ...
      prevRoute: null,
    }
  }
}
</script>

Or there is this guy https://gist.github.com/zolotyx/b4e7fda234b3572fb7adaf11391f8eef#file-auth-js, he has made a script to help in redirecting

Share:
13,858
asanas
Author by

asanas

Updated on June 22, 2022

Comments

  • asanas
    asanas over 1 year

    I am able to use this.$router.go(-1) to redirect a user to the previous route. However, I am not able to understand how I get get the information about the previous route before redirecting.

    Basically, by first reading what the previous route was, I want to make sure that the previous route was from the same domain and only then redirect to it, otherwise do something else.

  • CodeFinity
    CodeFinity over 3 years
    Even if not using asyncData for the component: this.$nuxt.context.from
  • John Y
    John Y over 3 years
    Does this solution work in SSR mode? I'm seeing nothing in the console when I try it…