Retrieve the previous URL for redirection purposes

I have a specific route set up in my application. If the user is not logged in, they are redirected to the login page. I am currently working on capturing the previous route that the user came from so that I can redirect them back there after they have successfully logged in.

Here is the structure of my route:

{
  path: '/builder/:pin?',
  name: 'Builder',
  component: Builder,
  props: true,
  meta: {
    requiresAuth: true, roles: ['XXXX', 'XXXX', 'XXXX']
  }
}

router.beforeEach((to, from, next) => {
  // Check if the route requires authentication
  if (to.meta.requiresAuth) {
    let user = store.getters.getUser
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        if(!user.emailVerified) {
          next({ name: 'Login' })
          store.dispatch('setLoginFeedback', {code: 'resubmit-verification', message: 'Your email is not verified'})
          return
        }
        // Get current user
        let ref = db.collection('users').where('email', '==', user.email)
        ref.get().then(snapshot => {
          if (!snapshot.empty) {
            snapshot.forEach(doc => {
              this.user = doc.data()
              // Check for roles
              if(!to.meta.roles) {
                next()
              } else if(to.meta.roles) {
                const hasRole = this.user.roles.find(val => to.meta.roles.includes(val))
                if (hasRole) {
                  next()
                } else {
                  alert('You do not have permission to enter')
                }
              } else {
                // next({ name: 'Dashboard' })
              }

            })
          } else {
            // No user found
            // if (!this.user) {
              next({ name: 'Login' })
            // }
          }
        })
      } else {
        next({ name: 'Login' })
      }
    })
  } else {
    // console.log('Does not require authentication')
    next()
  }


})

Within my Login component, I have included the following code snippet:

beforeRouteEnter(to, from, next) {
    next((vm) => {
        vm.prevRoute = from;
    });
    console.log(to, from, next)
},

I am currently running my application on a local server. When I navigate to localhost:8080/builder, it correctly redirects me to the Login page, but in the console, the 'From' value appears as follows:

{name: null, meta: {}, path: "/", hash: "", query: {}, …}

I am wondering why I am not getting /builder as the path in the 'From' object?

Answer №1

If you want to go back, you can simply use the following code:

this.$router.back();

Executing this will navigate you to the previous route on your application.

To learn more about programmatic navigation in Vue Router, check out: https://router.vuejs.org/guide/essentials/navigation.html

Answer №2

It appears that when you use the next({ name: 'Login' }) function to redirect to the login page, it does not update the from attributes. This is because you are internally routing, which is different from using router.push.

An easy solution for this type of redirection is to include a query param:

next({
  name: "bar",
  query: { redirect: to.fullPath }
});

You can then access this parameter in your component using $route.query.redirect or in a router navigation guard with from.query.redirect.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transmit responses from PHP script

I am in the process of creating a signup form where, upon clicking the submit button, all form data is sent to a PHP file for validation. My goal is to display an error message next to each input field if there are multiple errors. How can I achieve this ...

Determine the size of v-flex in Vue / Vuetify

Vuetify provides the v-resize directive, which is demonstrated in an example using window size. I am interested in utilizing this directive to monitor the size of a specific component (e.g. v-flex). In the provided codesandbox example, the objective is t ...

Vue paired with Rainyday.js

I attempted to incorporate Vue with rainyday.js by following different resources, but unfortunately could not find any relevant information. Can anyone provide guidance on how to successfully implement rainyday.js with Vue? <body onload="run();"> ...

A guide on updating data dynamically in Vue.js

I am facing an issue with Vue JS in my frontend development. Here is the data for my component - data: () => ({ email: "", showError : false }), Below is the corresponding HTML code - <div v-show='showError' c ...

AngularJS controller exceeding allowed complexity (SonarLint alert)

While utilizing SonarLint in Eclipse, I encountered an issue while working on an AngularJS application. Specifically, I was cleaning up a controller to improve readability when SonarLint flagged the following problem: The function has a complexity of 11 ...

Recent Google algorithm changes impact websites built on AngularJS and JavaScript

Exciting news from Google today (May 28, 2014) - JavaScript content will now be rendered by the Googlebot itself! This means there's no need to worry about serving pre-rendered pages just for crawling purposes. You can find out more details on this an ...

Deleting a string from a parameter

I have a string that reads: France (Republic of France) I am trying to extract only "France" and remove the rest of the string in parentheses. France (Republic of France) Any tips on how to achieve this? Thank you. ...

Exploring the implementation of Chain Map or Chain Filter within an Angular Http request that delivers a promise

I have a dataset in JSON format that I am working with, and I need to filter out specific key values using lodash. I want to reject multiple keys that I don't need. My initial approach is to either chain the map function and then use the reject funct ...

Emulate a Click Using Pure JavaScript

I am looking to add a click event to my custom dropdown, which replaces a SELECT element. The purpose of this click event is to trigger the corresponding OPTION item when an LI element is clicked. It seems like Woocommerce uses some JavaScript or PHP func ...

Directive fails to trigger following modification of textarea model

There is a block of text containing newline separators and URLs: In the first row\n you can Find me at http://www.example.com and also\n at http://stackoverflow.com. The goal is to update the values in ng-repeat after clicking the copy button. ...

What is the method for a Greasemonkey script to divide a link into three interconnected links?

My goal is to use Greasemonkey to link Redmine issue numbers found in cgit commit messages to their respective issues or projects. The cgit commit message HTML source looks like this: <a href='/editingmodule/commit/?id=49e4a33e0f8b306ded5'&g ...

What could possibly be causing a syntax error in my JavaScript code?

<script type="text/javascript> $(document).ready(function(){ $("a.grouped_elements").fancybox( 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'speedIn' : 600, ...

How to pass the ng-repeat $index value as a parameter in AngularJS

Within the code snippet provided, there is a shell page index.html and a partial view currently utilized by two different controllers. The static data in AppController is connected to the list.html partial view and displayed as a table. In the JavaScript p ...

Steps for inserting new rows into a table from text fields1. Begin

As someone who is brand new to jquery/html, I am eager to create a diary specifically for logging my long distance running times in a neat table format. Here's the HTML code I have been working on: <head> <title>Running Diary</titl ...

Vue.js: EventBus.$on is not properly transmitting the received value

I recently started working with Vue and am currently exploring the best way to organize my event bus. In my project, I have a main layout view (Main.vue) that includes a router view where I pass emitted information from a child component like this: <te ...

setting a callback function as a variable

I have encountered an issue where I am passing a callback function but unable to call it when the onreadystatechange changes its value, specifically request.onreadystatechange = func. Even though I receive a response from the server when making the ajax ...

Error: Unable to locate module '@/components/Header' in Next.js project

I'm currently facing an issue while working on my Next.js project. The problem arises when I attempt to import a component into my 'page.js' file. In the 'src' folder, I have a subdirectory named 'components' which contai ...

I encountered a validation error and a 404 error while trying to input data into all fields. Kindly review and check for accuracy. Additionally, I have included an

click here for image description Despite providing all details in the form fields, I keep receiving an error message prompting me to enter all fields... I am also encountering a "/api/user 404 Not Found" error and unsure of the reason. Interestingly, wh ...

Receiving a reply from the axios function

Whenever I try to call the lookUpItem function from ItemSearch.vue, I always get an undefined response. Code snippet from ItemSearch.vue: <script setup lang="ts"> import { lookUpItem } from '../systemApi' async fu ...

When embedding HTML inside an Angular 2 component, it does not render properly

Currently, I am utilizing a service to dynamically alter the content within my header based on the specific page being visited. However, I have encountered an issue where any HTML code placed within my component does not render in the browser as expected ( ...