Securing page access for unlogged users using VueJS: A guide

As I continue to hone my skills in VueJs, I am experimenting with creating sample applications. Currently, I am working on a straightforward app that features a login page where users input their credentials to access their profile. However, I am struggling to find a method to prevent unauthorized users from viewing the profile section by manually changing the URL to /profile.

This application is quite basic, utilizing only JavaScript and Bootstrap.

Is there a way to automatically redirect users back to the login page if they are not logged in and attempt to access the profile page?

Answer №1

If you want to verify if a user is logged in before navigating, you can utilize the navigation guards in Vue Router. This way, you can ensure that certain routes are only accessible to authenticated users.

Here's how you can set up your routes:

...
{
    path:'/dashboard',
    meta:{requiresAuth:true},
    component:DashboardComponent
},
...

For instance, you can implement the following logic:

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

    if (to.meta.requiresAuth && !AuthService.isAuthenticated()) {
        // User is not logged in, redirect to login page
        return next({path:'/login'}); 
    }

    return next();
});

Answer №2

If there are only a few routes that need to be protected, you can also utilize the beforeEnter parameter.

routes.js
import {ifAuthenticated} from "../middleware/authentication";
{
    path: '/test',
    name: 'Test',
    component: Test,
    beforeEnter: ifAuthenticated
},

authentication.js
import store from '../../store'

export const ifAuthenticated = (to, from, next) => {
  store.dispatch('User/getUser')
      .then(() => {
        next()
      })
      .catch(() => {
        next({ name: 'Login', query: { redirect_to: to.fullPath } })
      })
}

Here is an example utilizing Vuex for authentication.

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

What is the best way to retrieve a string from a lambda expression?

I am trying to call the function myFunction() and retrieve the source._id value, but I'm encountering issues with the current code. Even though source._id is correctly filled, I am unsure of how to successfully return it in its entirety. Ideally, some ...

Ways to implement a backup plan when making multiple requests using Axios?

Within my application, a comment has the ability to serve as a parent and have various child comments associated with it. When I initiate the deletion of a parent comment, I verify the existence of any child comments. If children are present, I proceed to ...

The issue with v-model on dynamically created inputs in Vue.js

I've spent the entire day searching, but I still haven't found a solution to this issue. I'm working on an app where I need to use v-model for reactive input that displays its value in another div element. What I really want is to be able t ...

Refreshing the package using Bower

I'm facing an issue while trying to upgrade angular from version 1.0.5 to 1.0.6 using Yeoman. Despite clearing the cache and checking the Github repository, it still installs version 1.0.5. Is there a workaround to force the update to version 1.0.6? ...

Testing mouse click events in Vue.js

As I work with a particular template, I encountered the following code snippet: <button type="button" id="alogin" class="btn btn-primary btn-raised btn-block btn-lg" @click="login()">Sign In</button> The login function within this ...

Troubleshooting Problem with JQuery Datepicker Input Field Value

There are two text boxes on my page named fromDate and toDate for date search. By default, the current day is displayed in both of them. Here is the working code: Jquery (document).ready(function () { $('.dateClass').datetimepicker({timepi ...

Node.js readline: SyntaxError: Unexpected token =>

Currently, I am diving into node.js and have found myself in need of utilizing the readline module for a new project. Below is the code snippet that I extracted directly from the official readline module example. const readline = require('readline&ap ...

Converting a three.js scene into SVG or alternative vector format for export

Can an SVG- or other vector-formatted image be exported from a scene rendered using three.js's WebGLRenderer? What about from a scene derived from CanvasRenderer? If not, how can one set up SVGRenderer with three.js? Creating a new THREE.SVGRenderer( ...

Are There Data Racing Issues in JavaScript?

Imagine executing the following code snippet. let score = 0; for (let i = 0; i < some_length; i++) { asyncFunction(i, function() { score++; }); // incrementing callback function } The code above may potentially lead to a data race issue where two ...

Loop through each current value in an ng-repeat directive and use it in an

I'm facing a simple issue that doesn't seem to have an easy fix. I have a ng-repeat set up like this <p ng-repeat="title in Menu.data[Menu.selected]"> {{ title }} </p> Now, I want to add an onclick event so I adjusted i ...

Encountering unexpected fetch requests to JSON files when using getStaticProps/getStaticPaths

My webpage seems to be functioning correctly, however I have noticed that in the console there are 5, 404 errors appearing on fetch requests. It's puzzling where these errors are originating from. Interestingly, these 404 errors only occur in the pro ...

Using JavaScript/jQuery to send JSON data via POST request and download a file

I am currently developing a single-page web application using jQuery. It communicates with a RESTful web service through AJAX calls. My main goal is to achieve the following tasks: Send a POST request containing JSON data to a RESTful URL. If the reques ...

Issue encountered with my AJAX request in JavaScript on Internet Explorer 8

Check out the range of products available on this website using jQuery When using Firefox or Safari, clicking on view will show you more product details on the right side. This could include a gallery with multiple images, downloadable spec sheets if av ...

What is the process for initiating an application dynamically using second.html in Vue3?

I'm currently working on a Vue3 project. In the main.js file: import { createApp } from "vue"; import App from "./App.vue"; const app = createApp(App); import store from "./store"; app.use(store); import router from &quo ...

Implementing functionality for changing methods based on Vue.js checkboxes

My web page features a dropdown menu that triggers a specific method to retrieve data based on the selected dropdown option. I am looking to implement a condition that dynamically changes the @change method depending on whether a checkbox is selected. The ...

Tips for troubleshooting in Chrome when working with the webpack, ReactJS, and Babel combination

I've configured webpack-dev-server to act as my development server, bundling all of my source code into a single JavaScript file. While it's working well, I'm having trouble debugging my code in Chrome. I can view my JS source code in the Ch ...

Launching an Electron application in fullscreen mode upon startup

I need assistance with setting my Vue and Node application in Electron to start in full screen mode. Currently, I launch the application using the command yarn run electron:serve. How can I modify it so that when the application is built and the .exe fil ...

Challenge encountered when trying to store AngularJS response in a global variable

When making an HTTP call to the controller using angular.js, I am trying to save the response in a global variable like so: app.controller('dashBoardController', ['$scope', '$http', '$location', function ($scope ...

What is the method for retrieving a computed state variable?

In Vue Class Component, accessing the value of a computed variable can be a bit tricky. If you try to access it using this.bar, you may encounter an error like this: Property 'bar' does not exist on type 'Vue'. <script lang="ts& ...

Can someone explain to me the utilization of async await in conjunction with map in mongoose?

const fetchOwnerInfo = async _ => { console.log('Initiating search for book owners...') const ownerPromises = books.map(async (book) => { const ownerDetails = await User.find({_id: book.Owner}) ...