set up the router by defining the behavior for each route

My goal is to redirect the user back to the homepage when they click the browser's back arrow to return to the previous page.

However, I'm facing an issue where I cannot go back to the previous page when I'm on the login page using the browser's arrow buttons.

Someone suggested using "router BeforeEach" but I'm struggling to understand how to implement it.

main.js:

    Vue.use(VueRouter)

const routes = [
    {
      path: '/',
      name: 'Home',
      component: Home,
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
      meta: { requiresAuth: true }
    },
    {
      path: '/register',
      name: 'Register',
      component: Register,
    },
    {
      path: '/complete_registration',
      name: 'Complete Registration',
      component: CompleteRegistration,
    },
    {
      path: '/profile',
      name: 'Profile',
      component: Profile,
      meta: { requiresAuth: true }
    }
]

const router = new VueRouter({routes, mode: 'history'})

router.beforeEach((to, from, next) => {

  if ( from.matched.some(record => record.meta.requiresAuth) ) {
    alert('enter')
    next('/');
  } else {
    next();
  }
});

Upon logging in, I keep getting stuck in a loop of pop-up alerts.

Answer №1

Thomas Kleßen perfectly articulated in his insightful comment:

  1. Ensure to include meta: { requiresAuth: true } only in the routes where user authentication is necessary. For instance, the login page (as well as the Register and Home pages, presumably) do not require it.
  2. Within router.beforeEach(), it is essential to verify if the destination ('to') necessitates the user to be authenticated, rather than the origin ('from'), which represents the previous page.

Nevertheless, an additional validation is crucial: redirect the user to the login page if authentication is lacking. To accomplish this, consider utilizing firebase.auth().currentUser, as demonstrated below. Refer to the relevant Firebase documentation here.

const routes = [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/login',
      name: 'Login',
      component: Login
    },
    {
      path: '/register',
      name: 'Register',
      component: Register
    },
    {
      path: '/complete_registration',
      name: 'Complete Registration',
      component: CompleteRegistration
    },
    {
      path: '/profile',
      name: 'Profile',
      component: Profile,
      meta: { requiresAuth: true }
    },
    {
      path: '/otherProtectedPage',
      name: 'OtherProtectedPage',
      component: OtherProtectedPage,
      meta: { requiresAuth: true }
    }
]

const router = new VueRouter({routes, mode: 'history'})

router.beforeEach((to, from, next) => {
    const requiresAuth = to.matched.some(record  => record.meta.requiresAuth)
    const currentUser = firebase.auth().currentUser

    if (requiresAuth && !currentUser) {
        next('/login')
    } else if (requiresAuth && currentUser) {
        next()
    } else {
        next()
    }
})

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

Unravel the encoded string to enable JSON parsing

Here is an example of my JSON string structure [{"id":0,"nextCallMills":0,"delay":0,"start":"... I am facing an issue with JSON.parseString() Even after trying unescape() a ...

Leverage Next.js routing in plain JavaScript without relying on React hooks

I am working on a NextJS app and I need to implement a function that can redirect to any page using Next.js routing. For example, after a user completes the signup process, I want them to be redirected to a specific page. So, I tried creating a reusable ...

Focusing on a particular iframe

I am currently using the "Music" theme from Organic Theme on my WordPress site and have inserted this code to prevent SoundCloud and MixCloud oEmbeds from stretching the page width: iframe, embed { height: 100%; width: 100%; } Although the fitvid ...

Save picture in localStorage

Hello, I am currently working on a page where I need to retrieve an image from a JSON file and store it locally. Below is the code I have been using: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.10.1.min. ...

The method continues to receive null values from Ajax despite successfully retrieving the data from Facebook

My current challenge involves creating a login using Facebook. The console indicates that the requested data (email, first_name, etc.) is being retrieved successfully, but for some reason, the AJAX request keeps sending null data to the PHP method. Below ...

Error: Property 'barcodeScanner' is not readable

Currently, I am utilizing barcodescanner.js for scanning QR codes. I have successfully downloaded and linked the CaptureActivity android library to my project. However, when attempting to execute the following code: window.plugins.barcodeScanner.scan(sca ...

Retrieve my information stored within a public transportation vehicle

Hello everyone, I am currently working on a Vue project and encountering a problem that I cannot seem to resolve. The issue at hand: I am trying to transfer data between components using a bus that I have defined in my main.js file. However, I am struggl ...

What is the best way to showcase a div on top of all other elements in an HTML page?

As a newcomer to html and css, I have successfully created a div that contains city names. The issue I am currently facing is when I click on a button to display the div, it gets hidden behind the next section of my page. Take a look at the image below for ...

Centralizing images in a Facebook gallery/lightbox during the loading process

Is the image width and height stored in Facebook's gallery database? In typical JavaScript usage, the image width and height cannot be determined until the image is fully loaded. However, on Facebook, images are pre-loaded before being displayed, ens ...

How to handle non-ASCII characters when encoding in JSON?

I understand that json_encode requires UTF-8 encoding, and I have already ensured that my data is encoded as such. However, when attempting to pass a PHP array to JavaScript, I am encountering difficulties in transferring the data successfully. To test th ...

What is the best way to show customized text from a data member within the :items object array for the item title in a v-select (Vuetify) dropdown menu

Currently, I am new to Vue and exploring Vuetify while working on building a dropdown using "v-select". If there is a simpler way to achieve this, it would be awesome! Otherwise, my plan is to create a new array, convert data for certain members into obje ...

How to apply a CSS class to the body element using Angular 2

I am working with three components in my Angular application: HomeComponent, SignInComponent, and AppComponent. The Home Page (HomeComponent) is displayed when the application is opened, and when I click the "Sign In" button, the signin page opens. I want ...

Using string replacement for effective search finding: Unleashing the power of substring matching

I have a method that adds an anchor tag for each instance of @something. The anchor tag links to a specific sub URL. Check out the code: private createAnchors(text: string) { return text.replace(/(@[^ @]+)/ig, '<a href="/home/user/$1">$1& ...

Generating dynamic dropdown menus using data from a database with the help of PHP and Ajax technologies

I'm currently working on creating a dynamic dropdown menu that will be populated with data retrieved from a database. I've hit a roadblock in parsing the data from a multidimensional array sent by a PHP file. Here's a snippet of my code: Se ...

The method of altering a menu link in WordPress using jQuery varies according to whether the user is logged in or not

I need to update the last link on my menu. When a user is logged in, it should display a profile link; otherwise, it should show a sign-up link. ...

Showcasing a JSON file in the interface using $http in AngularJS

I am a beginner in angularjs (and programming). I am attempting to showcase a json file on my view (home.html) using $http and ngRepeat, but unfortunately, it is not working as expected. Upon inspecting the angular responses, I noticed that there are numer ...

What is the best way to automatically adjust the size of this HTML Menu to match the width of its

I am in the process of converting a Drupal 6 theme to Drupal 7 and I'm encountering some difficulties with this particular section. Below is the HTML code snippet: <ul id="nav" class=" scaling-active scaling-ready"> <li><a href="/demos ...

What could be the reason for the sender message to only display once the recipient sends a message? (socketio) (nodejs) (reactjs)

Currently, I am working on developing a real-time chat application using Node.js, React, and Socket.io. The chat functionality is operational in theory, but there seems to be an issue where the sender's message only appears on the recipient's scr ...

Troubleshooting issues with JavaScript progress bar functionality

I have implemented a progress bar using HTML5, JavaScript and Ajax to showcase file uploads in PHP. The issue I am facing is that the progress bar is not displaying the progress correctly. In addition to that, the echo statements in the PHP code are no ...

Tips for managing large amounts of data retrieval from an API

As a beginner, I am attempting to retrieve data from an API and display it using the v-for directive. However, this process is causing my app to lag. It freezes when new data is fetched or when I search within the list. The following code snippet shows whe ...