How can I set up a redirect in vue.js after a user has been authenticated?

After receiving the token and storing it in both Vue state and local storage, how can I set up a redirect upon authentication?

Currently, the provided code includes a redirect feature, however the redirect does not occur after obtaining the token and there is no token check.

I am looking for assistance on how to validate the token and then redirect to the fullPath. Can anyone help with this?

var Auth = {
  loggedIn: false,
  login: function () { this.loggedIn = true },
  logout: function () { this.loggedIn = false }
}
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth) && !Auth.loggedIn) {
    next({
      path: '/login',
      query: {redirect: '/'}
    })
  } else {
    next()
  }
})

Answer №1

Typically, the process should proceed as follows:

  • User inputs login credentials
  • Vuex action userLogin is triggered
  • userLogin action sends data to the server and receives a token in return
  • userLogin action stores the token in the browser's localStorage
  • userLogin triggers mutation USER_LOGIN with the token and user details

To enable automatic login with the saved token (even after closing the browser):

  • Upon starting the app, you need to execute the userLoginLocal vuex action
  • userLoginLocal retrieves the token from the localStorage
  • userLoginLocal validates the token or sends it to the server for validation
  • If the token is valid, userLoginLocal commits mutation USER_LOGIN with the token and user details

NOTES: The USER_LOGIN mutation sets isLoggedIn = true

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 most effective way to condense these if statements?

I've been working on a project that includes some if statements in the code. I was advised to make it more concise and efficient by doing it all in one line. While my current method is functional, I need to refactor it for approval. Can you assist me ...

Display Images in React Component with Dynamic Loading

I've been troubleshooting for a few hours now, attempting to make a react component display an image of a playing card based on the prop passed in. I've scoured online resources, but the solutions I've come across are leaving me perplexed. ...

Submitting late leads to several consecutive submissions

I am working on a jQuery code that aims to introduce a short time delay to allow for the proper execution of an AJAX request: $('#form_id').submit(function(e) { e.preventDefault(); $submit_url = $(this).data('submitUrl'); ...

The concept of transparency in Internet Explorer 8 stands out in

Has anyone been able to achieve transparency in IE8 for the foreground color, not just the background color? I've tried various solutions but they all seem to focus on the background color. I need the transparency effect for user-generated colors, so ...

Problem with AngularJS Service

Can two different services be called in a specific order? I am working with two services, here are the details: dataservice.getCPUUtilization(model.dbName).then(function (data) { model.cpuUtilizationChart = data; model.cpuPercentage = model.cpuUtil ...

What is the best way to add a blur effect to the bottom layer as it

I'm looking to create a fixed top bar in my app. However, when the main page scrolls, the top bar ends up covering it. Is there a way to achieve a blurring effect on the main page when the top bar is overlaid on top of it? I've noticed that twit ...

Update the value of a td element when a select option is changed in another td element within the same table row

I have a table set up as follows: Header1 | Header2 | Header3 | Header 4 | Header 5 Row 1 |<span>Some Text</span> | <select></select> Row 2 Row 3 . . . . Rows generated dynamically. My objecti ...

Failure to update the DOM after clicking a button and making an AJAX request

After experimenting with different iterations of this code, the outcomes have been mediocre and inconsistent. The concept is rather simple: A user inputs a search query into a text box, clicks a button, and the query is assigned to a var search. This varia ...

Encountering difficulty in retrieving the outcome of the initial HTTP request while utilizing the switchMap function in RxJS

My goal is to make 2 HTTP requests where the first call creates a record and then based on its result, I want to decide whether or not to execute the second call that updates another data. However, despite being able to handle errors in the catchError bl ...

In React Native, you can pass native component properties as props, while also defining custom ones using a TypeScript interface

I am working on a component called AppText where I need to utilize a Props interface and also be able to accept additional props that can be spread using the spread operator. However, I encountered this error: Type '{ children: string; accessible: tru ...

The banner refuses to show up at the top and the CSS styling is not taking effect

In my Django project, I have the following HTML code: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, ...

What steps are involved in linking Java with JavaScript?

After attempting to connect html and javascript using applet, unfortunately it was unsuccessful. I am curious if there is an alternative method besides applet to establish this connection. ...

scrolling through a list using .slice choosing an excessive amount of items

Is it possible to create a dynamic pager that can be customized using parameters from the URL? I have noticed that when I hardcode the perTime variable, everything works fine. However, as soon as I try to use a parameter from the URL, the page starts behav ...

Access the style of the first script tag using document.getElementsByTagName('script')[0].style or simply refer to the style of the document body with document.body.style

Many individuals opt for: document.getElementsByTagName('script')[0].style While others prefer: document.body.style. Are there any notable differences between the two methods? EDIT: Here's an example using the first option: ...

forming an instance from JSON information

In a .json file, I have data that includes information on countries such as their currency, major language, and land area in square kilometers or square miles. { "countries": { "sweden": { "currency": "Swedish krona", " ...

Warning: The recursion limit has been exceeded in VUEjs 3, please review your

Recently, I've encountered a warning from Vue that says: "Maximum recursive updates exceeded. This means you have a reactive effect that is mutating its own dependencies and thus recursively triggering itself. Possible sources include component templa ...

How can I insert a variable into the URL for fetching data in React?

Here's a fetch request I have: fetch(`https://example/e1/e11/${variable1}?param=A1&include=metadata`, { "method": "GET"... Is there an issue with declaring the variable1 in this manner? It seems to work fine when written lik ...

What are some creative ways to animate Angular ng-switch for both entering and leaving transitions?

I have created an angular directive named 'cardViewer' that is designed to display images with animation. The directive enables the user to slide the image to the left when pressing the "prev" button and to the right when pressing the "next" butt ...

Tips for preventing the use of website URLs as variables in jQuery ajax() calls:

Having some trouble. For example: $(document).ready(function () { $("#btnSend").click(function () { var noti_p = { url: "Pusher_Controller.ashx", data: "&appname=" + $("#selt1").val() + "&title=" + $("#title"). ...

Issues encountered when trying to modify the Content-Type of POST requests using ngResource versions 1.0.6 and 1.1.4

Despite numerous attempts and trying various solutions found online, I am still unable to solve this issue. Similar questions have been asked in the following places: How to specify headers parameter for custom Angular $resource action How can I post da ...