Vue application failing to utilize local storage post user authentication (vue router)

After successfully logging in, I store the user key in localstorage and redirect the user to the dashboard. However, my application does not utilize the stored key until after a manual refresh.

Below is the code snippet responsible for setting the key:

    axios.post(url, creds)
      .then((response) => {
        if (response.data.code === 401) {
          context.error = response.data.data
        } else {
          Vue.ls.set('id_token', response.data.data.key, 60 * 60 * 1000)
          this.user.authenticated = true
        }
      }).catch((err) => {
        context.error = err.data
      })

Interestingly, there is a route guard function in place that correctly accesses the value right after login without needing a refresh:

router.beforeEach((to, from, next) => {
  const r = axios.create({
    baseURL: env.api_url,
    timeout: 25000,
    headers: {
      'Authorization': 'Bearer ' + Vue.ls.get('id_token'),
      'X-Requested-With': 'XMLHttpRequest'
    }
  })

  if (to.name === 'Login') {
    r.get('user').then(() => {
      next({name: 'Dashboard'})
    }).catch(() => {
      next({name: 'Login'})
    })
  }

  if (to.name !== 'Login') {
    r.get('user').then(() => {
      next()
    }).catch(error => {
      console.log(error)
      next({name: 'Login'})
    })
  } else next()
})

Why is this issue occurring?

Answer №1

Big shoutout to the insightful comment from JacobGoh that led me straight to the solution. It dawned on me that the axios instance was being created in my main.js file, where I set the Authorization headers. However, this setup wasn't dynamically updating when a user logged in.

So, here's what I ended up doing instead:

router.beforeEach((to, from, next) => {
  if (Vue.ls.get('id_token') === null && to.name !== 'Login' && to.name !== 'Register') {
    router.push('/login')
  } else {
    next()
  }
})

Vue.$http.interceptors.request.use(
  config => {
    config.headers.Authorization = 'Bearer ' + Vue.ls.get('id_token')
    return config
  },
  error => Promise.reject(error)
)

And just like that, problem solved!

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 approach to add additional functionality to an already existing object method?

Let's say we have an obj, var obj = { l:function(){ alert(1); } } In what way can additional functionality be incorporated into obj.l without directly modifying the object? ...

Navigating through images within my application

When setting images, I encounter an issue where the second image overlaps the first one instead of appearing separately. How can I ensure that each image is displayed in its own box? I have attempted to use a blob directly by returning imgUrl in the showI ...

Gathering Servlet details from non-form elements

I am currently in the process of developing an application that is capable of parsing JSON strings. At this stage, I am able to input a JSON string using Java, write it to an HTML document, and then have a JavaScript program read and parse it before ultima ...

A beginner's guide to integrating ChartJS with React

Trying to incorporate ChartJS into a React component but unsure of how to proceed. First step is to create a canvas element following the instructions found at https://www.chartjs.org/docs/latest/getting-started/usage.html#creating-a-chart. Next, need to ...

Verify that the text entered in the form is accurate, and if it meets the required criteria, proceed to the next

Is it possible to achieve this without using JavaScript? If not, I'd like to find the simplest solution. I have a form that functions similar to a password entry field, and I would like to redirect users to a certain page if they type in a specific p ...

Using jQuery to retrieve the unique identifier of an element and checking if it matches a certain value before including the link

I'm currently using this code to retrieve values from a database and then add them to a form. The initial part appends the name of the Firewall and includes the unique ID in the element's id. if (value.type == 'Firewall') { $(' ...

Issue with the loop function

When I try to loop through my code, I keep getting the same "y" value (5) and it doesn't change. What I actually want is to make the ajax call repeat X times [all], passing both the response and the current call number through an anonymous function. A ...

Tips for stopping PHP echo from cutting off a JS string?

I encountered an issue with my code: <!DOCTYPE html> <html> <head> <title>Sign up page</title> <meta charset="UTF-8"/> </head> <body> <h1>Sign up page</h ...

Tips for implementing dynamic image paths in Next.js

As a newcomer to ReactJS and working with Next.js, I am currently fetching images from a database using an API. The issue I am facing is that I am receiving the image name with the full path (url.com/imagename), but I want to be able to use a dynamic pat ...

How is it possible that the SetTimeout code continues to run even after calling clearTimeout

I have this code snippet within my react component: //some code var timeout = null; //global variable //some more code useEffect(() => { if(...some condition) { console.log('test1'); timeout = setTimeout(() => { ...

Swap out an element in a list that does not correspond to any element in a separate list with a designated value

I am fairly new to Javascript and currently struggling with looping through an array and replacing items. I hope my explanation is clear. Here is the initial array: [ '1:1', 'blah', '1:2', undefined, '1:3' ...

Performing matrix manipulations using Mirror.js (Three.js)

I am currently working on creating water effects in three.js and I haven't come across any examples in three.js that incorporate both reflection and refraction. If you know of any examples, please feel free to share the links with me. Currently, I am ...

Upon initial server-side rendering load in Nuxt 3, Vercel fails to transmit the client's IP address to the Laravel backend

I'm encountering an issue with my setup where the actual client's IP address is not being forwarded correctly during the initial Server-Side Rendering (SSR) load of a page. Backend: Running Laravel on a VPS Frontend: Utilizing Nuxt 3 deployed on ...

Using Next.js API routes instead of relying on Axios for making API calls is a great

While following a tutorial, I encountered an issue with axios endpoints not working properly (resulting in a server error). Therefore, I am interested in learning how to utilize Next.js API routes in my project instead of axios. Any guidance on this matt ...

What is the best way to apply an SVG as the background-image for this text?

After examining the fiddle, it is clear that there is code to set the background of two spans to an image created with svg. The goal now is to achieve this dynamically using javascript (either jquery or raw) on the span with the "help" class, but unfortuna ...

Preloading web page with Flash animation for seamless transitions and stylish fade in/out effects

My customer is requesting a loading animation or movie (already created in Flash CS5) to be displayed on the initial page of the website (root, '/' - the first thing visitors see when they go to domain.tld). After the animation finishes, it sho ...

Transmit a JavaScript object using the $.ajax method

My goal is to pass a complex JavaScript object like the one below through a $.ajax request : var o = { a: 1, b: 'dummy string', c: ['a', 1, {}], d: {dd: 1}, e: new Date(), f: function() { console.log(&ap ...

Steps to implement a body {} style on a particular vue component

To prevent interference with other components, I have been utilizing scoped styles in most of my components. However, there are certain views or components that require the use of body { overflow: hidden; }, while others do not. The issue is that I am unab ...

Retrieve the past week's data based on names using JavaScript

Is there a way to dynamically fetch the past seven day names, starting from today, in JavaScript? I am looking to format the result as follows: (Wednesday, Tuesday, Monday, Sunday, Saturday, Friday, Thursday, Wednesday). ...

Invoking a function that is declared in a fetch request from an external source beyond the confines of the fetch itself

I am currently struggling with calling a function that is defined inside an API Fetch response function. My code sends an API fetch request to the GitHub API to retrieve a repository tree in JSON format. The problem arises when I try to call a function def ...