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
}
},