Steps to automatically redirect to the login page when a user is not authenticated in a Vue 3 frontend with Laravel as the backend

RoxanneSkywalker OP Posted 32 minutes ago Achievement Unlocked: Ten Thousand Strong Badge How can I implement a redirect to the login page when a user is not authenticated in Vue 3 with Laravel as the backend? Hey there,

I am seeking guidance on how to redirect a user to the login page if they are not authenticated while using Vue 3 as the front end and Laravel as the back end. My frontend is developed using Vue 3 separately, whereas my backend utilizes Laravel.

Below is an excerpt from my router/index.js file:

import {createRouter, createWebHistory} from "vue-router";
import Dashboard from "../views/admin/Dashboard.vue";
import Home from "../views/Home.vue";
import Login from "../views/Login.vue";
import Register from "../views/Register.vue";
import Unauthorized from "../views/Unauthorized.vue";
import Users from "../views/admin/manage-user/Users.vue";
import Roles from "../views/admin/manage-user/Roles.vue";
import Permissions from "../views/admin/manage-user/Permissions.vue";

// More code here

In addition, here's an overview of my store/auth.js file:

import {defineStore} from "pinia";
import axios from "axios";

// More code here

Lastly, let me share a snippet from my Dashbaord.vue component:

<script setup>
 import {onMounted} from "vue";
 import {useAuthStore} from "../../stores/auth.js";
import DashboardLayout from "../../layouts/DashboardLayout.vue";
const authStore = useAuthStore();

// More code here

</script>

<template>
<DashboardLayout>

// More code here

</template>

Please note that my application integrates Vue with Pinia, and it operates as two separate entities with Vue managing the front end and Laravel handling the backend processes.

Answer №1

It is recommended to utilize Navigation Guards to verify authentication status prior to each redirection.

Learn more about Navigation Guards here

// router/index.js
import { useAuthStore } from 'store/auth.js'

router.beforeEach(async (to, from) => {
  const authStore = useAuthStore();

  if (
    // Check if the user is authenticated
    !authStore.authUser &&
    // ❗️ Prevent infinite redirect loop
    to.name !== 'Login'
  ) {
    // Redirect user to login page
    return { name: 'Login' }
  }
})

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 use a jQuery each loop to retrieve the margin of an element

I currently have 7 different elements, each with unique margin-left and margin-top properties set in the CSS file. I am looking to loop through these elements and gather information about their margins. This is what my jQuery code looks like so far: var ...

Maintaining aspect ratio of canvas while ensuring responsiveness

Currently, I am working on a drawing app and have come across an issue that has been challenging for me to resolve. The dilemma lies in resizing the canvas of sketches from the original resolution of 1280 x 720 to the maximum size possible upon opening the ...

"Is there a way to assign a default value to a select element while also using ng-model and ng-change in AngularJS

My reason for this question is that I have encountered a situation where ng-model is overriding the default value in the select tag. Therefore, I am looking to establish <option value="-translation.published_at" selected>{{ 'Newest first' | ...

When jQuery inserts JavaScript into the DOM, it does not automatically execute the code

UPDATE: I initially used filter(), which was incorrect. I have since switched to find(), but unfortunately the issue persists. This snippet of code functions properly for me: $('#content') .replaceWith($( '<div> <d ...

What is the best method for retrieving the complete error message from my client-side Node and Express server?

When I send a request to my express route and it returns a 400 status along with an error message, I am facing an issue on the client-side. The alert message only displays "Object object" instead of the actual error message that I see on the server side. U ...

Mobile device experiences shader malfunction

On my laptop, this shader works perfectly fine. However, I'm facing issues on mobile devices and suspect that it might be related to precision settings. Here is the error message I'm encountering: THREE.WebGLProgram: shader error - 0 35715 fals ...

The disabled functionality of AddCircleIcon in Material UI seems to be malfunctioning

The AddCircleIcon button's disabled functionality is not working, even though the onClick function is functioning properly. Even when directly passing true to the disabled property, it still doesn't work. I am in need of assistance to resolve thi ...

What is the process for exporting data from MongoDB?

Recently, I created a web application for fun using Handlebars, Express, and Mongoose/MongoDB. This app allows users to sign up, post advertisements for others to view and respond to. All the ads are displayed on the index page, making it a shared experie ...

How can I calculate the width of a character in an HTML5 canvas?

When using the .fillText function with a fixed-width font, I can easily adjust the height by setting the .font property. However, is there a way to accurately determine the width of an individual character? ...

Leveraging the node CLI tool as a library for trimming MP3 files (trimp3

I recently came across a fantastic library that I am interested in using for my nodejs project: https://github.com/kyr0/trimp3 The only issue is that it functions as a cli tool, and I would like to integrate it seamlessly into my codebase as a library. D ...

What is the recommended sequence for using decorators in NestJS: @Body(), @Params(), @Req(), @Res()?

How can I properly access the res object to send httpOnly cookies and validate the body with DTO? I keep running into issues every time I attempt it. What is the correct order for these parameters? ...

Implement a horizontal scrollbar for your table in HTML

I need to implement a horizontal scroll bar for my table. Here is the HTML code: Even though I have utilized Bootstrap, the horizontal scroll bar is not working for this particular module. It works fine in other modules. The tbody data is added after an ...

Exploring the integration of Passport SAML authentication for a seamless experience across both the backend Node (Express) and client Vue

I have a unique situation where I have developed an application with a Node (Express) backend, and a Vue client. Recently, I decided to implement SAML Single Sign-On (SSO) using passport for authentication. While everything works perfectly within the Expre ...

Exploring ways to cycle through a select dropdown in React by utilizing properties sent from the Parent Component

I'm having trouble displaying the props from a parent component in a modal, specifically in a select dropdown. How can I make it so that the dropdown dynamically shows the values from the props instead of the hardcoded 'Agent' value? What am ...

Show a visual representation when Blob is retrieved from an API call

Currently, I am working on a Vue app that integrates with the Microsoft Graph API and SDK for authentication at the front end, along with using various features of the API like displaying emails, OneDrive files, etc. One specific challenge I am facing is ...

Prevent a specific item from being included in an Electron list using JavaScript

When extracting filenames from a directory, this code is currently being used: getFilenameList = () => { let select = document.getElementById("filenameSelect"); let options = []; fs.readdirSync(folderUrl).forEach(file => { options.pus ...

Decipher and handle the ampersand symbol in a GET query with Django and Vue

We have been using axios to send GET requests to our Django server, which then splits the request into search terms and executes the search. Everything was working smoothly until we encountered a particular scenario. To prevent any issues with empty spaces ...

Best practices for correctly parsing a date in UTC format using the date-fns library

My log file contains timestamps in a non-ISO format: 2020-12-03 08:30:00 2020-12-03 08:40:00 ... The timestamps are in UTC, as per the log provider's documentation. I am attempting to parse them using date-fns: const toParse = "2020-12-03 08:40 ...

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 & ...

Place the Drawer element at the bottom of the menu

Is there a way to position the menu point at the bottom of the screen? It would be great if we could easily customize the style of the navigation options for each element. Check out my App Navigator below: const AppNavigator = createDrawerNavigator( ...