Encountered the error message "Router.js file throwing a TypeError: next is not a function" while implementing navigation guards in my Vue 3 project

I'm puzzled as to why 'i' doesn't recognize the next function, even though I followed a similar video that implemented it without any errors.

import Dashboard from "./Pages/Dashboard.vue";
import Customers from "./Pages/Customers.vue";
EditProfile from "./Pages/EditProfile.vue";
Insurance from "./Pages/Insurance.vue";
Activations from "./Pages/Activations.vue";
Login from "./Pages/Login.vue"
ForgotPassword from "./Pages/ForgotPassword.vue"

MyDashboard from "./Pages_cus/MyDashboard.vue";
MyActivations from "./Pages_cus/MyActivations.vue";
MyEditProfile from "./Pages_cus/MyEditProfile.vue";
NotFound from ./Pages/NotFound.vue';
NetworkError from './Pages/NetworkError.vue'

import { createRouter, createWebHistory } from "vue-router";

const routes = [
    {
        name: "MyDashboard",
        component: MyDashboard,
        path: "/my-dashboard",
        meta: {
            requiresAuth: true,
        }
    },
    {
        name: "MyActivations",
        component: MyActivations,
        path: "/my-activations",
    },
    {
        name: "MyEditProfile",
        component: MyEditProfile,
        path: "/my-edit-profile",
    },
    {
        name: "Dashboard",
        component: Dashboard,
        path: "/dashboard",
        meta: {
            requiresAuth: true,
        }
    },
    {
        name: "Customers",
        component: Customers,
        path: "/customers",
    },
    {
        name: "EditProfile",
        component: EditProfile,
        path: "/edit-profile",
    },
    {
        name: "Insurance",
        component: Insurance,
        path: "/insurance",
    },
    {
        name: "Activations",
        component: Activations,
        path: "/activations",
    },
    {
        name: "Login",
        component: Login,
        path: "/",
        meta: {
            requiresAuth: true,
        }
    },
    {
        name: "ForgotPassword",
        component: ForgotPassword,
        path: "/forgot-password",
    },
    {
        name: "404Resource",
        component: NotFound,
        path: '/404/:resource',
        props:true
    },
    {
        name: "NetworkError",
        component: NetworkError,
        path: '/network-error'
    },
    {
        name: "NotFound",
        component: NotFound,
        path: '/:catchAll(.*)'
    },
    
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

router.beforeEach((to, next) => {
    if (to.matched.some(record => record.meta.requiresAuth)) {
        if (localStorage.getItem('token') == null) {
            console.log('Hello JS')
          next({
            path: '/',
            params: { nextUrl: to.fullPath }
          }) // The error occurs here where 'next' is not recognized as a function
        }
        else{
            next();
        }
    } 
    else {
          next()
    }
})

export default router;

Answer №1

The next parameter is the third argument to be used in the beforeEach function, so it should look like this:

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

Although you are currently using the next function correctly by ensuring it's called once, please note that it has been deprecated: https://github.com/vuejs/rfcs/blob/master/active-rfcs/0037-router-return-guards.md#motivation

It is now recommended to utilize 1 or 2 arguments and return a boolean value to indicate whether to proceed or redirect to a specific route:

router.beforeEach((to)=>{
    if (to.matched.some(record => record.meta.requiresAuth) 
        && localStorage.getItem('token') == null) {
          //redirect
          return {
            name: '/',
            query: { nextUrl: to.fullPath }
          } 
    } 

    return true; //proceed (equivalent of 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

Steps to resolve the error message "The port 9876 has no listening server when karma is running"

I have a situation where I am executing the following code: PS D:\app> karma run However, an error is being displayed: [2013-11-29 17:39:54.297] [DEBUG] config - Loading config D:\app\karma.conf.js There is no server listening on port ...

What is an alternative method to retrieve POST fields in Express without relying on the bodyParser middleware?

Recent updates to Express have suggested to stop using the bodyParser middleware, as indicated by a debug message. Upon further research, it appears that bodyParser is simply a wrapper to the json and urlencoded middlewares. In its place, the latest versio ...

Obtain the value of a range using JQuery

I made an attempt to retrieve the value of JQuery's range slider when it changes. Here is how I tried: On the HTML/PHP page: <div class="total"> <label for="">Total</label> <p><span class="monthrc"></span ...

Clicking on Only One Card in Material UI React

I've encountered an issue with my code: const useStyles = makeStyles({ card: { maxWidth: 345, }, media: { height: 140, }, }); export default function AlbumCard(props) { const classes = useStyles(); let ...

Discover how ReactJS can dynamically display or hide div elements based on specific conditions being met within JSON data

How do I show or hide a div based on a condition in React, using data from a JSON array? I have implemented the code below, but changing the value of isPassed={resultPass.pass} to isPassed={resultPass.failed} still displays the result as pass. I came acro ...

NodeJS experiencing a hitch in the image upload process

I am currently working on a Node code snippet that is used for uploading images. The images I am dealing with have sizes ranging from 10 to 200K, so they are relatively small in size. However, the issue I am facing is that Node seems to get stuck process ...

"Troubleshooting: Issues with the ng-hide directive in AngularJS

I am facing an issue with hiding a column in my table using ng-hide. The goal is to hide the column before the user logs in and then show it after they have logged in. However, I found that after applying the ng-hide property, the entire table gets hidden ...

Retain the chosen values even after submitting the form

Consider the following form: <form method="get" action=""> <select name="name"> <option value="a">a</option> <option value="b">b</option> </select> <select name="location"> <opt ...

Creating broken lines with Three.js using BufferGeometry

I find myself in a situation where I need to create a Line with holes, essentially a discontinuous line. This entails my Line being composed of multiple segments that are visually separate but conceptually connected. These segments contain more than just t ...

Utilize HTML5 to enable fullscreen functionality for embedded SWF files

I have implemented a function that handles the click event of a button to toggle a DOM element into fullscreen mode. The function works well, but I am facing an issue when there is another div containing a swf inside the main div. var elem = document.getE ...

Displaying an interactive 2D floorplan in a web browser with the use of html5 and javascript

In the process of updating my old Flash viewer, I am looking to display interactive 2D floorplans exported from AutoCAD. Currently, I convert the AutoCAD files into XML files containing the X and Y coordinates of the various elements on the floorplan such ...

Step-by-step guide to adding products to your Supabase shopping cart

I have managed to insert a row into the "order" table with user information. Now, I want to individually add item details to a separate table named "order_storeItems" to create a relationship between the order and storeItems tables. I attempted using Pro ...

Error: Unable to access the 'nom_gr' property of null - encountered in Chrome

<ion-col col-9 class="sildes"> <ion-slides slidesPerView="{{nbPerPage}}" spaceBetween="5"> <ion-slide *ngFor="let slide of lesClassrooms; let i = index" (click)="saveCurrentSlide(i)"> ...

What is the best way to restrict the maximum number of items stored in local storage?

I'm creating a GitHub search app using the GitHub API in Angular. I want to restrict the number of items that can be stored in local storage. If the number of stored elements exceeds 5, the "Add to Favorite" button should either stop working or disapp ...

Steps to dynamically populate a datatable with JSON data by triggering a click event in jQuery

I am facing an issue with feeding JSON data into datatables when the search button is clicked. The JSON data structure is as follows: [ { "port_code":"BOM", "cont_details_id":"9", "price":"44.000", "cont_price":"500", "c ...

"Integrating Associated Models with Sequelize: A Step-by-Step Guide

I am attempting to retrieve all transactions along with their associated stripePayments, but I keep encountering the error include.model.getTableName is not a function. In my database schema, there is a table for transactions that has a one-to-many relati ...

The error message states: "An attempt was made to destructure a non-iterable object. In order for non-array objects to be iterable, they must have a [Symbol.iterator

I need to call a RTK query endpoint from a function const [getCityCode, { isLoading, error, data, isSuccess, isError }] = useLocationQuery(); const getLocationDetails = async () => { const queryItems = { latitude: lat, longitude: long }; await getC ...

vee-validate remains consistent in its language settings

Having trouble changing the error message in vee-validate, any suggestions on how to fix this? import VeeValidate from "vee-validate"; import hebrew from "vee-validate/dist/locale/he"; Vue.use(VeeValidate, { locale: "he", dictionary: { he: { me ...

Isolating a type as a constant in Typescript within a .js file?

Within my .js configuration files, I have a tsconfig containing the property checkJs: true. A library called Terser includes the following type options: ecma: 5 | 2015 | 2016 | 2017 | 2018 | 2019 | 2020 Despite setting ecma: 2017 in my configuration file ...

Refreshing CommonJS modules by reloading or reinitializing them

It is well known that CommonJS modules are designed to load only once. Imagine we have a Single Page application with hash-based navigation; when we go back to a page that has already been loaded, the code does not run again because it has already been loa ...