Transfer information using beforeEnter to navigate through route components

How can I pass data from a function called with beforeEnter to the corresponding route component(s)?

The goal of using beforeEnter in this scenario is to validate the presence of a valid bearer token as a cookie.

Currently, my beforeEnter function interacts with the AWS API gateway endpoint /verify/auth, and then the component loads and makes another call to DynamoDB on /list/repos. However, both routes are already protected with a built-in JWT authorizer in AWS API GatewayV2, making the initial hit to /verify/auth redundant.

What I aim to achieve is for the beforeEnter function to directly interact with /list/repos, utilize the existing JWT authorizer, and load the next page with the data obtained from the API call. If the user is not authenticated, the beforeEnter function should prevent the user from accessing the route.

Therefore:

  • API call -> Page loads

instead of

  • API call -> Page loads -> Another API call

Below is my code. I have referenced a similar question on Stack Overflow but was unable to find a solution. passing data to route's component beforeEnter

index.js

let repositories = [];

async function listRepositories(to, from, next) {
  var isAuthenticated = false;
  console.log("testing listRepositories...");
  if (Vue.$cookies.get("Authorization")) {
    try {
      const response = await fetch(
        process.env.VUE_APP_API_GATEWAY_ENDPOINT + "/list/repos",
        {
          method: "POST",
          body: '{"repo_owner": "sean"}',
          headers: {
            Authorization: Vue.$cookies.get("Authorization")
          }
        }
      );
      repositories = await response.json();
      console.log(repositories);
      if (repositories.message != "Unauthorized") {
        isAuthenticated = true;
        // return {
        //   repositories
        // };
        next();
      }
    } catch (error) {
      console.error(error);
    }
  }
  if (!isAuthenticated) {
    console.log("error not authenticated");
    to("/");
  }
}

const routes = [
  {
    path: "/",
    name: "Login",
    component: () => import("../views/Login.vue")
  },
  {
    path: "/repos",
    name: "Repos",
    // beforeEnter: isAuthenticated,
    beforeEnter: listRepositories,
    props: repositories => {
      {
        repositories;
      }
    },
    component: () => import("../views/Repos.vue")
  }
];

./views/Repos.vue

<template>
  <div id="app" class="small-container">
    <repo-table
      :repositories="repositories"
    />
  </div>
</template>

<script>
import RepoTable from "@/components/RepoTable.vue";

export default {
  name: "Home",
  components: {
    RepoTable
  },
  data() {
    return {};
  },
  props: {
    repositories: {
      type: Array
    }
  }
</script>

./components/RepoTable.vue

<template>
  <div id="repository-table">
    <table border="0">
      <tr>
        <th style="text-align:left">Repository</th>
        // omitted for brevity
      </tr>
      <tbody>
        <tr v-for="(repo, index) in repositories" :key="repo.repo_name">
          <td>
            <b>{{ repo.repo_name }}</b>
            // omitted for brevity
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  name: "repository-table",
  data() {
    return {
      // repositories: []
    };
  },
  props: {
    repositories: {
      type: Array
    }
  },

Answer №1

Implementing route params with beforeEnter

Utilize route params to transmit data through beforeEnter. By setting the value of props to true, route params can be transformed into props:

props: true

All you need is a parameter named repositories, and it will be passed as a prop to the destination. Inside your beforeEnter function, upon successful authentication of the user, you can include that parameter:

if (repositories.message != "Unauthorized") {
  isAuthenticated = true;
  to.params.repositories = repositories;  // ✅ Adding the data to the parameter
  next();
}

Additional enhancements:

  • Replace to('/') with next('/')
  • Ensure there is a next statement in every logical flow, such as in case of errors or when none of the if conditions are satisfied.
  • Whenever you invoke next, use it with return like return next

Another approach:

You can also accomplish this by utilizing the beforeRouteEnter in-component guard.

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

Node.js poses a challenge when it comes to decoding incoming request data

I am attempting to create a sample login page using the combination of node, express, and angularjs. Displayed below is my login view: <div class="login-page"> <div class="login-page-content"> <div style="margin-top:30px;padding:10px;w ...

Combining the power of AngularJS with the versatility of sails

A project I'm working on involves utilizing sails.js for back-end and AngularJS for front-end. My plan is to use the Yeoman-angular generator https://github.com/yeoman/generator-angular to create the Angular app first. Once the front-end development i ...

Searching for repeated values across disparate object fields?

Inquiring about the method to utilize mongoose for identifying duplicate values across different fields. Providing a sample document for reference: { "followers": { { "_id": "5bf6d610d3a3f31a6c75a9f4" }, ...

Encountered an error message stating "This dependency was not found" after installing a package using npm

I recently added a package called htmldiff to my Vue project using the npm install command. The next step was to try importing the package into one of my components. import { diff } from 'htmldiff'; // note that the package does not use default ...

A straightforward method of transmitting data from JavaScript to the Python back-end within a Streamlit application

Utilizing the st.components.v1.iframe, I integrated an authentication system that sends a token back to the parent when a user is authenticated. The iframe content is as follows: <script src="remote/auth.js"></script> <scri ...

What are some ways we can enhance Map.get for react-router using ES6 Maps?

I recently implemented a map using new Map() to store my RR4 configuration within my application. My goal is to retrieve the values associated with /countries/:id when accessing /countries/1. routesMap.get('/countries/1') // should provide the ...

Displaying the information of an object within an array in Vue JS

I have been working on fetching the decorTypes data from the tabs array in Vue.js. While the data is displaying in the console, it is not showing up in the devtools. Below is the script code that I am using: <script type="module"> export ...

The Click Event Is Triggering Even with Correct Callbacks Being Set

I am struggling to understand why these functions are not executing properly. I know the correct syntax for binding a function, like this: $('#idOfThing').bind('click', foofunc); function foofunc() { ///do things } However, I am facin ...

Distinguish between a function and a constructor during execution

As I work with TypeScript, I am creating a function that accepts an error factory as an argument. This factory can be either a class name or a function. The function looks something like this: // Alias from class-transformer package type ClassConstructor& ...

Use the colResize function in R Shiny to establish communication and synchronize the column sizes between R and

I'm currently using a plugin called datatables.colResize to allow manual column resizing for DataTables in my R Shiny application. My goal now is to save the column width state once a user adjusts the table size. I want this information to be passed a ...

Activate button through input using Bootstrap

I am struggling to achieve the desired functionality with my "sendit" button. I want it to be enabled as soon as there are any characters entered in the box, but I have tried multiple solutions without success. Part of HTML: <input type="password ...

Do you have any queries regarding JavaScript logical operators?

I'm struggling with understanding how the && and || operators work in my code. I created a small program to help myself, but it's just not clicking for me. The idea is that when you click a button, the startGame() function would be triggered. va ...

The error message "Vue.JS computed from VueX Store is not recognized" is displaying

Within my Vuex store, I am able to see it in the Vue Devtools tool. However, when attempting to load data into a computed property, an error message stating that it is not defined is displayed. computed: { userData(){ return this.$store.state.use ...

Using an ng-repeat directive alongside an if condition in Angular

My website contains a vast array of 30 articles, previously represented by around 300 lines of HTML code, but now condensed to just 10 lines with angularjs. However, certain articles hold special significance and require specific display criteria. Check ou ...

What causes the delay in CSS animations?

Is there a way to trigger an "updating" image to spin while a long JavaScript function is running? I am currently using JQuery to add a class called "spinning", defined in my CSS for the animation. The problem is that when I add the class and then call a l ...

Trouble with two dropdown selections in Angular and preset values

I am encountering an issue with a select input in angular 7. The scenario involves having 2 selects where selecting an option in the second select populates the corresponding values in the first select. The first select should display a default placeholder ...

What steps can I take to correct my code so that it only shows a single table?

I'm facing an issue while trying to display my dynamic JSON data. It's rendering a table for each result instead of all results in the same table. My array data is coming from the backend API. const arr = [ { "Demo": [ ...

Creating a double-layered donut chart with Chart.js

I'm attempting to create a unique pie chart that illustrates an array of countries on the first level and their respective cities on the second level. After modifying the data in a JSON file to align with my goal, it doesn't seem to be working a ...

Guide to iterating through an object and generating child components in React.js

Struggling with a React.js loop through child component issue as a newcomer to the language. I have an object and want to create child components from its values. Any help would be greatly appreciated. var o = { playerA: { name: 'a', ...

Steps to refresh a .ejs page with updated information following an ajax request

I am in need of re-rendering my homepage.ejs with new data on the server side following an ajax request. Although I am aware that you can somehow re-render the elements in the ajax callback, I am interested in finding out if it is possible to simply re-ren ...