Securing client side routes in Vue.js: Best practices

Currently, I am in the process of developing a spa using Vue.js as the front end framework. It interacts with a back-end system that utilizes pure JSON and jsonwebtokens for security. While I am more experienced with the React ecosystem, my new role requires me to work with Vue.js.

In React, protecting client-side routes involves checking for a jsonwebtoken in localstorage before mounting the app, and setting the redux state accordingly. Route protection is typically implemented using higher order components by checking the logged in state in the componentWillMount lifecycle method.

Unfortunately, it seems that achieving similar behavior with higher order components in Vue is not as straightforward or well-documented. As I navigate this challenge, I would appreciate insights from others on how they would approach this issue.

Answer №1

In the official documentation, it is clearly mentioned that you have the ability to utilize meta fields for authentication validation on specific routes.

An illustration from the documentation is as follows:

router.beforeEach((to, from, next) => { 
    if (to.matched.some(record => record.meta.requiresAuth)) { 
        // Check if user is logged in before accessing this route
        if (!auth.loggedIn()) { 
            next({ 
                path: '/login', 
                query: { redirect: to.fullPath } 
            }) 
        } else { 
            next() 
        } 
    } else { 
        next() // Call next() at all times!
    } 
}) 

Alternatively, when it comes to component navigation guards, you should refer to the additional resource provided by wostex.

Answer №2

It appears that I overlooked the documentation on routes meta fields. Despite my initial confusion, my approach seems to be effective. Haha.

router.beforeEach((to, from, next) => {
    let web = ["home", "login", "verifyAccount", "resetPassword","forgotPassword","register"];
    if(web.includes(to.name)){
        next();
    }else{
        axios.post('/api/auth/verify-token',{
            token: localStorage.token
        }).then(response=>{
            if(response.data.verification === true){
                next();
            }else{
                router.push({
                    name:'home',
                    params:{
                        serverError:true,
                        serverMsg: 'Please login to continue.'
                    }
                });
            }
        }).catch(response=> {
            console.log(response);
        });
    }
});

Answer №3

Check out this great demonstration of how Vue.js handles authentication: link

For more detailed information, here is a manual on navigation guards in Vue.js: link

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

Tips for activating multiple CSS animations when scrolling

I am currently working on a project that involves multiple CSS animations. However, I am facing an issue where these animations only occur once when the page initially loads. I would like them to trigger every time the user scrolls past them, regardless of ...

Tips for utilizing Vue router query parameters while in hash mode:

Is there a more efficient way to access URL parameters in Vue methodology, without having to rely on window.location.href and parsing the URL? router/index.js const router = new Router({ mode: 'hash', routes: [] }); router.beforeEach((to, f ...

Is it feasible to pre-load external websites using JavaScript?

While searching on various platforms, including Stack Overflow, I couldn't find a solution to this specific query. I'm not necessarily seeking an implementation already in place, but rather ... Imagine having an intranet application that loads q ...

The secure exchange of HTTP-only cookies between a REST API developed with Spring Boot and a frontend application

Currently, I am in the process of integrating a Spring Boot API with VueJS. Initially, everything was functioning smoothly when I stored the JWT in localstorage. However, numerous online resources suggest that it is advisable to refrain from storing the J ...

The renderToString function in Material UI's sx property doesn't seem to have

Every time I apply sx to a component that is rendered as a string and then displayed using dangerouslySetInnerHtml, the styles within the sx prop do not work. Here is an example showcasing the issue: Codesandbox: https://codesandbox.io/p/sandbox/wonderfu ...

An uncaught exception has occurred: An error was encountered indicating that the specified path is not valid for either posix or windows systems, and it appears that there is no 'join' method defined in the

I am currently working with nextjs version 13.5.6 using the app router and app directory. This issue arises during the compilation of the route app/(home)/page.js. The folder and file structure within the app folder is as follows: app/ -(home)/page.js -ser ...

Several attributes in the JSON object being sent to the MVC controller are missing or have a null

I am facing an issue while passing a JSON object to my MVC controller action via POST. Although the controller action is being called, some elements of the object are showing up as NULL. Specifically, the 'ArticleKey' element is present but the & ...

Calculate the number of days required for the value in an item to multiply by two

I'm currently working on a JavaScript project to create a table displaying the latest number of coronavirus cases. I've reached a point where I want to add a column showing how many days it took for the confirmedCases numbers to double. Here&apos ...

Start numerous nodejs servers with just a single command

I currently have multiple Nodejs servers, each stored in its own separate folder within a root directory. Whenever I need to run these servers, I find it cumbersome to navigate through each folder and manually type nodemon *name*. The number of servers i ...

Vue paginated select with dynamic data loading

My API has a endpoint that provides a list of countries. The endpoint accepts the following query parameters: searchQuery // optional search string startFrom // index to start from count // number of options to return For example, a request with searchQu ...

The error message "[Insecure URL]" was triggered at line 85 of angular.min.js in the AngularJS framework

Looking for some assistance with Angular as I have limited knowledge. It was working fine on localhost, but after upgrading from PHP5 to PHP7, I encountered this error: angular.min.js:85 Error: [$sce:insecurl] http://errors.angularjs.org/1.2.13/$sce/inse ...

Error 405 (Unauthorized) encountered with the stack of technologies including Vue.js, Nginx, Axios, SQLite, and Express

I successfully developed an application that handles user login and registration to a SQLite database on `localhost`, but I am encountering issues when trying to deploy it. The deployment results in an error message saying `405 (Not Allowed)` with the acco ...

Is it possible to switch from kilometers to miles on the distance matrix service in Google Maps?

let distanceService = new google.maps.DistanceMatrixService(); distanceService.getDistanceMatrix({ origins: [sourceLocation], destinations: [destinationLocation], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.IMPERI ...

Guide on sending a message to a specific channel using Discord.js version 13 with TypeScript

After recently diving into TypeScript and seeing that Discord.js has made the move to v13, I have encountered an issue with sending messages to a specific channel using a Channel ID. Below is the code snippet I am currently using: // Define Channel ID cons ...

Optimizing the particle rendering speed for HTML5 <canvas> elements

Currently conducting an experiment to enhance the maximum particle count before frame-rates begin to decrease in HTML5 Canvas. Utilizing requestAnimationFrame and employing drawImage from a canvas as it appears to be the most efficient method for image re ...

How can I remove the back button that the Ionic framework adds when using $state.go('app.home') to navigate to a page?

I have an app with a sidebar menu. Currently, I am on the second page and I am calling a controller function that redirects me to the first page using: $state.go('app.home'); The issue I am facing is that on this page, a back button is displayed ...

How can we eliminate the modal-open class in Angular when transitioning to a different URL?

Currently, I am facing an issue with a bootstrap modal. There is a button inside the modal which upon clicking should navigate the current component to another component named 'questions'. The problem arises when the new component is loaded, as t ...

Utilize ng-bootstrap in an Angular CLI project by integrating it with npm commands

I've been attempting to set up a project using Angular CLI with ng-bootstrap, but I'm having trouble getting the style to work properly. Here are the exact steps I followed (as outlined in the get-started page): Create a new project using `ng n ...

Pressing the enter key within Material UI Autocomplete will allow you to quickly create new

Wouldn't it be great if Autocomplete in material ui could do this: wertarbyte Imagine being able to insert text (string) without the need for a list of elements to select from. This means that the noOptions message shouldn't appear, and instead ...

Leverage information extracted from the Node.js function

As I dive into the world of NodeJS, a particular issue arose while working with the getCurrentWeather() function. It's asynchronous nature means that it loads instantly upon app start and writes data to variables. However, when attempting to use these ...