Display a modal when a user is not authorized in vue-router

After stumbling upon this post on Medium, I decided to implement its concepts into my project.

My goal was to verify a user's authorization to access a particular route, and if unauthorized, display a modal pop-up.

In order to achieve this, I made some adjustments to my routes:

function isAuthorized(data) {
  return data;
}
function isAdmin(to, from, next) {
  const isUserAdmin = store.state.authentication.isAdmin;
  if (!isUserAdmin) {
    next(false);
    isAuthorized(true);
  } else {
    isAuthorized(false);
    next();
  }
}

const router = new Router({
  ...
  routes: [
  {
  path: '/admin',
  component: Sidebar,
  meta: { showModal: isAuthorized },
  children: [
    {
      path: 'sample',
      name: 'Sample',
      component: Sample,
      beforeEnter: isAdmin,
      meta: { title: 'Sample Page' },
    },
  ...

Additionally, in my Sidebar.Vue

UnauthorizedModal(:show-modal="showUnauthModal"
                  @toggle-modal="toggleModal")

export default {
  name: 'Sidebar',
  components: {
    UnauthorizedModal,
  },
  data() {
    return {
      showUnauthModal: this.$route.meta.showModal,
    };
  },
  watch: {
    '$route.meta'({ showModal }) {
      this.showUnauthModal = showModal;
    },
  },

As for my UnauthorizedModal component

<template lang="pug">
b-modal.simple-modal(
  :active="showModal"
  scroll="keep"
  @close="toggleModal"
)
  .modal-container
    header
      h1
      | Unauthorized
</template>

<script>
export default {
  name: 'UnauthorizedModal',
  props: {
    showModal: {
      type: Boolean,
      required: true,
    },
  },
  methods: {
    toggleModal() {
      this.$emit('toggle-modal');
    },
  },
};
</script>

However, upon testing the functionality, I encountered an error in my console.

Invalid prop: type check failed for prop "showModal". Expected Boolean, got Undefined in UnauthorizedModal.vue

This indicates that the modal is not receiving the necessary data from the routes.

I do not wish for any page redirection, just simply the display of a modal when the user lacks authorization for a specific route.

What could be the issue or mistake in my implementation?

Answer №1

Within the child component (sample), there seems to be no meta.showModal defined, resulting in it being undefined when accessed from the child component.

To resolve this issue, consider adding showModal to the child component.

const router = new Router({
  ...
  routes: [
  {
  path: '/admin',
  component: Sidebar,
  meta: { showModal: false },
  children: [
    {
      path: 'sample',
      name: 'Sample',
      component: Sample,
      beforeEnter: isAdmin,
      meta: { title: 'Sample Page', showModal: false },
    },

It's uncertain whether you can modify the router's meta data within the beforeEnter function, but you can attempt to do so with the following approach:

function isAdmin(to, from, next) {
  const isUserAdmin = store.state.authentication.isAdmin;
  if (!isUserAdmin) {
    next(false);
    to.meta = {
      ...to.meta,
      showModal: true
    }
  } else {
     to.meta = {
      ...to.meta,
      showModal: true
    }
    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

How to refresh an array in Angular 4 after inserting a new element using splice method?

I have a Angular list displayed in a table, and I need to insert an element at a specific position. I have tried using the following code: array.splice(index, 0, element); While everything seems fine in the console with the element being added at the corr ...

Steps for adding a React Class Component into a Modal that is not within the React Tree

Our project is built using PHP MVC Framework and we initially used jQuery as our main JavaScript framework for handling UI activities. However, we have now transitioned to using React.js. My query is about how to inject or append a React Functional/Class-b ...

What is the method for achieving the equivalent effect of "background-size: cover" on an <img>?

I am looking to ensure that an <img> has the smallest possible size without any empty spaces inside a div, while also being perfectly centered both horizontally and vertically. The image size may vary. To better illustrate, here is an example: http: ...

Encountering an issue while attempting to replicate the Spotify app on localhost:3000. The error message "TYPEERROR: Cannot read property 'url' of undefined" is hind

As a first-time user of stackoverflow, I am unfamiliar with its rules and regulations, so I apologize in advance for any mistakes I may make. Currently, I am attempting to create a Spotify clone using React. Everything was going smoothly until I completed ...

Retrieve information from an API and assign the corresponding data points to the graph using Material UI and React

I have 4 different APIs that I need to interact with in order to fetch specific details and visualize them on a bar graph. The data should be organized based on the name, where the x-axis represents the names and the y-axis represents the details (with 4 b ...

Saving information in binary format to a file

I have a script for setting up an installation. This specific script is designed to access a website where users can input values and upload a certificate for HTTPS. However, the outcome seems to be different from the expected input file. Below is the cod ...

How can I enable two-finger scrolling on mobile web browsers?

I am currently tackling a project that involves dragging operations on a canvas, making scrolling with a single finger impractical. My goal is to enable scrolling using two fingers instead. After testing different touch-action values, I discovered that pi ...

Updating the title of a page on CoreUI's CBreadcrumbRouter dynamically

I'm currently developing a project with VueJS and the CoreUI admin template. Is there a way I can change the title of the current page as shown on the CBreadcrumbRouter? The GitHub documentation mentions that the script typically displays meta.label ...

Show a Kendo Pie Chart that reflects information from the grid dataset

I am using KendoUI - Grid component Is there a way to transform this into a Kendo Grid? For example: I have set up a Kendo grid (table) with local data. When I click on the "Generate chart" button, I want the filtered data from the table to be used to cr ...

How can we implement :focus-within styling on Material-UI Select when the input is clicked?

I am currently implementing a Select component inside a div element: <div className="custom-filter custom-filter-data"> <DateRangeIcon className="search-icon"/> <FormControl variant='standard& ...

Adjust the size of the image to fit within the div container following

<div id="homePage" style="position: relative; margin: 0px; width: 320px; height: 420px;"> <img id="userImg" src="images/5.jpg" width="100%" height="100%" onclick="imageClick()" style=" z-index: -1; margin: 0 ...

Using TypeScript to Add Items to a Sorted Set in Redis

When attempting to insert a value into a sorted set in Redis using TypeScript with code like client.ZADD('test', 10, 'test'), an error is thrown Error: Argument of type '["test", 10, "test"]' is not assigna ...

The 'fs' module does not seem to have an immediate impact; a server restart may be necessary for the changes to take

This NodeJS project involves starting the server with npm start. The project reads files from a folder called "./mydir/" using 'fs.readdirSync'. It then pushes these files into an array and prints them on the console. var fs = require('fs ...

What could be causing replace() to malfunction in Node.js?

I am dealing with some data in Node.js and I am trying to replace the ampersands with their escape key. Below is the code snippet I am using: let newValue = data; for (label in labelData.data) { let key = "Label " + label; newValue = newValue.rep ...

The error message "Unexpected token < in JSON at position 0" is indicating a SyntaxError in the

I am facing an issue with the API on this specific page. Although the API is working fine on other pages, it seems to be encountering a problem here. I'm not sure what's causing the issue. Below is the code snippet: export async function getStati ...

Enhancing ReactJS functionality by incorporating custom logic prior to resolving promises

In one of my components, there is a function as follows: this.props.firebase.getDropSites("123456").then(data => { console.log(data); }); This function in turn calls the following method from my utilities class: getDropSites(dropSiteId) { return th ...

What is the best way to develop interactive components using Google App Scripts for Google Sites?

I am currently working on building dynamic app script components that can be seamlessly integrated into my website, each with unique data for every instance of the script. I initially attempted using parameters but I'm uncertain if this is the most ef ...

Unable to access HTTP response headers during Ext.ajax.request callback in ExtJS 4.2.1

When making an Ext.ajax.request, I am attempting to read the headers of the response that is coming. Here is the code snippet: Ext.Ajax.request({ url: 'http://localhost:3000/v0.1/login' , method: 'POST', scope:this, jsonDat ...

What could be causing the malfunction of material-UI Tabs?

My Material UI Tabs seem to have stopped working after a recent update. I suspect it may be related to the react-tap-event-plugin update I installed. Initially, I thought it was due to tab indexing but even using values like value='a', value=&apo ...

Updating the value of an Angular select on change is not being reflected

If the select element is changed, the value should be set to something different from what was selected. There's a feature in place that only allows 4 item types to be selected at a time; if more than 4 are chosen, the value reverts back to its origin ...