Struggling with Navigation Guard integration in a Vue 3 + Quasar + TypeScript application

Currently, I am developing an application using the Quasar Framework in conjunction with Vue 3 and TypeScript, specifically utilizing the Composition API. My objective is to incorporate a Navigation Guard within my routes.ts file for handling route authentication. However, during this process, I've encountered the following error:

ERROR in src/router/index.ts:26:5
TS2740: Type 'Router' is missing the following properties from type 'readonly RouteRecordRaw[]': length, concat, join, slice, and 16 more.
    24 |   const Router = createRouter({
    25 |     scrollBehavior: () => ({ left: 0, top: 0 }),
  > 26 |     routes,
       |     ^^^^^^
    27 |
    28 |     // Leave this as is and make changes in quasar.conf.js instead!
    29 |     // quasar.conf.js -> build -> vueRouterMode

Here are the steps I have taken so far:

  1. I initially followed the standard Vue 3 documentation to set up the Navigation Guard.
  2. Upon encountering the error, I tried modifying the vueRouterMode in the quasar.config.js file to 'history' from 'hash', based on recommendations from various forums.
  3. I also double-checked for any typos or misconfigurations in my code and ensured that all dependencies are up to date.
  4. Despite these efforts, the error persists, even though I anticipated that changing the vueRouterMode or reviewing the code for errors would resolve the issue.

routes.ts

...

auth-store.ts

...

src/router/index.ts

...

Answer №1

It appears that the router is being created twice, once in index.ts and again in routes.ts. To streamline this process, I recommend consolidating the creation of the router within index.ts and simply adding the guard there. Remove the following code from routes.ts, leaving only routes:

const router = createRouter({
  history: createWebHistory(),
  routes,  // This is correct
});

router.beforeEach((to, from, next) => {
  const auth = useAuthStore();

  if (to.matched.some(record => record.meta.requiresAdmin)) {
    if (auth.isAdminUser) {
      next();
    } else {
      next('/');
    }
  } else {
    next();
  }
});

Then, include the following code in index.ts:

export default route(function (/* { store, ssrContext } */) {
  const createHistory = process.env.SERVER
    ? createMemoryHistory
    : (process.env.VUE_ROUTER_MODE === 'history' ? createWebHistory : createWebHashHistory);

  const Router = createRouter({
    scrollBehavior: () => ({ left: 0, top: 0 }),
    routes,

    history: createHistory(
      process.env.MODE === 'ssr' ? void 0 : process.env.VUE_ROUTER_BASE
    ),
  });

  Router.beforeEach((to, from, next) => {
    const auth = useAuthStore();

    if (to.matched.some(record => record.meta.requiresAdmin)) {
      if (auth.isAdminUser) {
        next();
      } else {
        next('/');
      }
    } else {
      next();
    }
  });

  return Router;
});

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

405 we're sorry, but the POST method is not allowed on this page. This page does

I'm currently working on a small Form using the kit feature Actions. However, I'm facing an issue when trying to submit the form - I keep receiving a "405 POST method not allowed. No actions exist for this page" error message. My code is quite st ...

Transferring dynamic parameters from a hook to setInterval()

I have a hook that tracks a slider. When the user clicks a button, the initial slider value is passed to my setInterval function to execute start() every second. I want the updated sliderValue to be passed as a parameter to update while setInterval() is r ...

Performing a conditional query on a Many-to-Many relationship in TypeORM

Operating under a many-to-many relationship between Category and Product entities In need of filtering products based on category ID Attempted to implement the following code after referring to some examples, but encountered difficulties in making it fun ...

Error in GoogleMapReact with Next.js: TypeError occurs when trying to read properties of undefined, specifically 'getChildren'

Currently, I am working on a basic nextjs application using the google-map-react component and nextjs. However, I keep encountering an error whenever I try to utilize the component. The error message reads as follows: "TypeError: can't access propert ...

In Typescript, it is not possible to utilize numbers or arrays within URLSearchParams

The method signature for appending to a URLSearchParams object in TypeScript is defined as append(name: string, value: string): void;. While I successfully appended an array and number in the browser, it resulted in an error when running the TypeScript co ...

Error encountered in Angular 2 due to an unexpected token

After updating nodejs, I encountered an error with Angular 2 that was working fine before. Now, after updating the node_modules, it has stopped working and I am unsure of where the error is or how to fix it. (index):29 Error: (SystemJS) Unexpected token & ...

How can I create an input field in MUI that restricts input to letters, numbers, and dashes

Is there a way to configure an MUI input field so that it only accepts letters, numbers, and dashes while excluding spaces and symbols such as (*&^%$#@!,.<>{}[])? Specifically, I want to allow characters that wouldn't disrupt a URL, like . Tha ...

Is it necessary for 'ts-loader' to have 'typescript' installed in order to function properly? I personally did not encounter any issues with this

The npm documentation for using ts-loader suggests installing typescript. The official Typescript guide in webpack documentation also recommends the same, but without providing a clear explanation. However, I have successfully built everything without havi ...

Improving the structure of destructured props by including type annotations. TypeScript implementation in React with Redux. Error code TS

When working with the destructured props from the redux state in the mapStateToProps() function, I encountered a nested structure issue. How can I properly apply the HeaderStateMap types to address this? The compiler is generating the following error messa ...

Issue with Memory Deallocation in Rust WebAssembly Custom Elements

I encountered an issue while working on my first Rust-produced WASM, and I am unsure how to debug it. wasm-000650c2-23:340 Uncaught RuntimeError: memory access out of bounds at dlmalloc::dlmalloc::Dlmalloc::free::h36961b6fbcc40c05 (wasm-function[23]:6 ...

Using Angular 8, remember to not only create a model but also to properly set it

hello Here is a sample of the model I am working with: export interface SiteSetting { postSetting: PostSetting; } export interface PostSetting { showDataRecordAfterSomeDay: number; } I am trying to populate this model in a component and set it ...

The issue of HTTP parameters not being appended to the GET request was discovered

app.module.ts getHttpParams = () => { const httpParamsInstance = new HttpParams(); console.log(this.userForm.controls) Object.keys(this.userForm.controls).forEach(key => { console.log(this.userForm.get(key).value) const v ...

Disabling a specific tab in an array of tabs using Angular and Typescript

Displayed below are 5 tabs that can be clicked by the user. My goal is to disable tabs 2 and 3, meaning that the tab names will still be visible but users will not be able to click on them. I attempted to set the tabs to active: false in the TypeScript fi ...

Dependencies exclusively for NPM post-installUnique Rewrite: "N

I have been using git to distribute an internal TypeScript NPM package. To avoid cluttering my repository with build files, I have implemented a postinstall action to build the package upon installation: "postinstall": "tsc -p tsconfig.json& ...

Creating the data type for the input file's state: React with Typescript

Encountering an error when attempting to define the type of a file object within state: Argument of type 'null' is not assignable to parameter of type 'File | (()=> File)'.ts. Currently working on an upload component that allows for ...

A generic function in Typescript that can accept an object with the first argument as a specified key

I am looking to create a function that will take a string as its first argument and will only accept a second argument of type object if it contains the first argument as a key with a boolean value: const checkFlag = (str:string, obj) => obj[str] Alth ...

React Error: Attempting to access the 'style' property of an undefined object

Can anyone help with this issue related to React code? const sidebar = document.getElementsByClassName("pro-sidebar"); The problem occurs when trying to adjust the width using: function openNav() { sidebar.style.width = "250px";} Addi ...

Is there a way to establish a "transient" category within a category to maintain code efficiency?

I'm struggling to figure out how to search for this specific question on Stack Overflow. The structure of my generic type FetchOptions looks like this: type FetchOptions<T> = { explode?: string & keyof T | (string & keyof T)[]; } I&a ...

Encountering syntax errors with CommonJS Rollup plugin when attempting to import third-party libraries, particularly those involving the 'process' module

I have been developing a personalized rollup configuration that involves React projects and inlines the JS and CSS in index.html. When attempting to import third-party React libraries (such as material-ui-color), I encountered an issue with CommonJS repo ...

Insert items into an array at a specific index in typescript

Using the map function, I am adding elements to array arr1. Is there a way to specify the starting index position in typescript? For example: If I want to add elements from the 3rd index position of the array, with the first two indices holding a value of ...