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

A customizable and adaptable Tetris-inspired CSS design perfect for any screen size

If we imagine having a block like this: <div class="block"></div> There are different sizes of the block: <div class="block b1x1"></div> <div class="block b2x1"></div> <div class="block b1x2"></div> For i ...

Using a JavaScript array in Java

Currently, I am working on an Android app that requires me to download data from a JavaScript array representing the schedule for my school. The link to the data is here. I am looking for a way to parse this data into a Java array. I have considered using ...

What are some ways to leverage a promise-returning callback function?

Here is a function that I have: export const paramsFactory = (params: paramsType) => { return ... } In a different component, the same function also contains await getPageInfo({ page: 1 }) after the return .... To make this work, I need to pass a cal ...

I need help using i18N to translate the SELECT option in my VUE3 project. Can someone guide me

<n-select v-model:value="value" :options="options" /> options: [ { label: "Every Person", value: 'file', }, { label: 'Drive My Vehicle', ...

Ways to transfer a value between two different card elements

I have designed a component with three div cards side by side using bootstrap. The first card displays a list of products, and my intention is that when a product is clicked, the details should appear in the second card on the same page. However, this fun ...

Sorting and Filtering JSON Data by Value in JavaScript: A Comprehensive Guide

After successfully integrating the Star Wars API to show character names from the "people" object in this JSON array retrieved from , I now need to filter the results based on a specific value which corresponds to . The current code displays all species of ...

The Power of jQuery's .ajax() Utility

I'm a beginner with the jQuery AJAX ajax() Method and have recently created the AddATeacher() function. The function gets called successfully as I see all the alert messages popping up. However, the ajax() Method within the function is not working. Th ...

"Using jQuery to enable ajax autocomplete feature with the ability to populate the same

I am encountering a problem with jQuery autocomplete. It works perfectly fine with one textbox, but when I create multiple textboxes using jQuery with the same ID, it only works for the first textbox and not the others. My question is how can I create mult ...

Preventing JavaScript from refreshing the page when using location.replace for the second time with the identical URL

I've encountered an issue while using location.replace to reload a page that relies on GET variables for displaying a success message. The problem arises when the URL specified in the location.replace call is identical to the current one, causing the ...

Enhance Your Form Validation with jQuery UI Dialog Plugin

Currently, I am utilizing the bassistance validation plugin for form validation. I have set up a pop-up modal dialog box to contain a form that requires validation, but for some reason, the form is not getting called. I have checked all my ID's and re ...

Transmit information from a JavaScript AJAX function to a JSP page

My current goal involves a user clicking on a link on the home page, let's say /home.jsp. Upon clicking this link, I extract the value and use it to call a RESTful resource that interacts with a database and returns a response. The communication with ...

Steps to Edit After Creating:1. First, open the document or file that

Currently, I am working on a Vue/Laravel application and facing an issue with getting my edit/update button to work. The add button is functioning correctly, but the update button seems to be unresponsive without any errors being displayed on either the ba ...

How can I use Vue to close the side Navbar by targeting the body tag and clicking anywhere on the screen?

I am looking to make a change in the Navbar position by moving it right: -500px (to close the navbar) when clicking anywhere on the window. In HTML and JS, I can achieve this by targeting the body tag. How can I accomplish this in Vue? I already have funct ...

Attempting to remove certain selected elements by using jQuery

Struggling to grasp how to delete an element using jQuery. Currently working on a prototype shopping list application where adding items is smooth sailing, but removing checked items has become quite the challenge. Any insights or guidance? jQuery(docume ...

Positioning of the dropdown in Material UI AutoComplete menus

Is there a way to turn off autocomplete auto position? I would like the autocomplete options to always appear at the bottom. Check out this link for more information! ...

What is the best way to convert a 2D PHP array into a JavaScript array?

I have encountered a problem with a PHP array setup as follows: $output = array(array(1,1,1,1),array(2,2,2,2),array(3,3,3,3)); When I encoded the array to JSON, I received this output: $output = {"1":[1,1,1,1],"2":[2,2,2,2],"3":[3,3,3,3]} My goal is to ...

Customizing functions in JavaScript with constructor property

What is the best way to implement method overriding in JavaScript that is both effective and cross-browser compatible? function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; ...

Arrange my Firebase Angular users based on a specific value, encountering an error stating "sort is not a function

I'm working on an application using Firebase and Angular, and I have a database containing information about my users: My goal is to sort the users based on their "ptsTotal". In my users.service file, I have a function called getUsersByPoints. Howev ...

WebWorker - Error in fetching data from server using Ajax call

I've been experimenting with making AJAX calls to an ajax.htm file using web workers. The goal is to have the data continuously updated at set intervals. Although I'm not seeing any errors and the GET request appears to be successful, the data i ...

How can I display a nested div when the parent div's v-if condition is not met?

In my project, I am utilizing Laravel 6 in combination with Vue.js 2. To iterate through users and showcase their information within div elements, I am using a for loop outlined below. The Category names are stored in user.pivot.demo2, and the users are ...