Unable to start store from localStorage during App initialization

Having trouble setting up my Vuex store with the logged-in user's account details from localStorage.

I've looked at numerous Auth examples in Nuxt, but none explain how to retrieve an authToken from localStorage on the client side for subsequent API requests when the page is refreshed or the user navigates to the app.

Disclaimer: Not using Nuxt in SSR (this may impact your response).

What's frustrating is that I can fetch and initialize my state from localStorage, but then it gets overwritten. See this code snippet:

buildInitialState () {
   if (!process.server) {
      // Retrieve accessToken, refreshToken, and account details from localStorage
      return {accessToken: <valid-string>, refreshToken: <valid-string>, account: <valid-json-blob>}
   } else {
      // Return "INVALID" placeholders for demonstration
     return {accessToken: "INVALID", refreshToken: "INVALID", account: "INVALID"}
  }
}

export const state = () => buildInitialState()

Although initially all looks good as I correctly set the state values from localStorage, once I use Axios for requests and add an interceptor to include the accessToken, things go awry.

In the interceptor plugin:

export default ({ app, store }) => {
  axios.interceptors.request.use((config) => {
    const accessToken = _.get(store.state, ['account', 'accessToken'])
    if (accessToken) {
      config.headers.common['x-auth-token'] = accessToken
    }
    return config
  }, (error) => Promise.reject(error))
}

It seems that despite initializing the state correctly, the accessToken reverts back to "INVALID" when a request is made. This behavior contradicts the initial setup from localStorage.

If anyone familiar with Nuxt could shed light on this issue, it would be greatly appreciated. The goal is to maintain the user session intact even after page refresh without requiring a new login each time.

Thanks and regards, Jason.

Answer №1

After some trial and error, as well as gathering insights from various online discussions about SSR and SPA concepts, I was able to resolve the issue.

A helpful thread on https://github.com/nuxt/nuxt.js/issues/1500 provided valuable information, with a key takeaway from @jsonberry redirecting my focus away from using fetch and asyncData.

This led me to gain a better understanding of how NUXT.js handles the separation of SSR and SPA functionalities.

Following @robyedlin's advice, I implemented localStorage initialization within the created() method of my main layout/default.vue page.

Although there was progress with this approach, it became evident that the created() method also operates during SSR, preventing me from accessing the necessary credentials for store initialization.

Ultimately, moving the initialization process to the mounted() method proved to be the solution!

To summarize:

  • I refrained from initializing my account store upon creation, recognizing that it would be overwritten during the SSR process.
  • In mounted() within layout/default.vue, I utilized localStorage to initialize the account store, enabling successful API requests with the correct accessToken.

Implementing these adjustments successfully resolved the issue at hand.

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

Using NextJS to pass a string from an input field to getStaticProps via context

I am a beginner in NextJS and React, so please forgive my lack of knowledge. I am trying to figure out how to pass the text input by users from an input field (inside Header) to the getStaticProps function of a specific page using the React context API. I ...

Handling exceptions in AngularJS router-ui resolve functionality

In my app, I have the parent route listed below: .state('app',{ url: '/app', templateUrl: 'views/app.html', resolve: loadSequence('modernizr','moment'), ...

What could be the reason for the lack of definition of the `pieceOfText

My latest project involves a fun guessing game centered around decrypting text, but I've hit a snag with a variable in my JavaScript code. This variable, known as pieceOfText, should be assigned a random piece of text from an array containing 3 encode ...

Master the Art of Scrollbar Control in Angular!

I am currently developing a chat web application that functions similar to gchat. One of the key features I'm trying to implement is an alert notification when the scrollbar is in the middle of the div, indicating a new message. If the scrollbar is at ...

Is it possible to update labels on an AngularJS slider using a timeout function?

I recently started implementing an AngularJS slider to navigate through various date and time points. Specifically, I am utilizing the draggable range feature demonstrated in this example - https://jsfiddle.net/ValentinH/954eve2L/ The backend provides the ...

Unable to view images that have been uploaded through express.js

In my current project with a REST Api, I have been facing an issue while uploading images. The folder structure of the project can be seen here: Under the public folder, there is a subfolder named images where all the image uploads are stored. However, w ...

Utilizing React JS to neatly display Firebase data in a table

Before I post, I always make sure to do my due diligence by searching on Google, YouTube, forums, or trying to figure it out on my own. I even check questions similar to mine asked by other people, but unfortunately, I'm stuck. Currently, I am using ...

AngularJS Assessing an Attribute directive following an Element directive

Currently, I am utilizing an angular plugin that can be found at the following link: https://github.com/angular-slider/angularjs-slider The objective is to customize the "legends" produced by the directive. In order to achieve this customization, the dire ...

What is the best way to manage the "checked" state of an input checkbox using React?

I'm currently developing an application that features a form with radio buttons. One of the radio button options can be toggled on/off using a checkbox, but I want to ensure that the checkbox is disabled if the corresponding radio button is not selec ...

Is it appropriate for HTML5 Web Workers to utilize CORS for cross-origin requests?

As I was creating a hosted API that relies on web workers, I encountered an intriguing issue. I am looking for feedback from the community to help me with this. Even though my server has the necessary CORS headers in place to serve the worker JS files and ...

Is there a JavaScript function available to remove comments from previously commented HTML code?

<div id="div1">bar</div> JQuery function addComment(element){ element.wrap(function() { return '<!--' + this.outerHTML + '"-->'; }); } addComment($('#div1')); Looking for assistance in unc ...

Angulating Service Testing

I am encountering an issue that I'm not sure how to resolve because I am inexperienced when it comes to testing. Currently, I am testing a service that includes the following code: import { Injectable } from '@angular/core'; import { Endpo ...

Is it possible to utilize a controller within a different controller?

As I work on developing an application, I am faced with the challenge of using controller functions within another controller function. Is it possible to achieve this or not? Use-case: My goal is to verify in the User collection (using mongoDB) if a user ...

Displaying entries of input data

I have an application that includes a modal window with filters, but I am looking to add another type of filter. However, I am struggling with implementing it in React and would appreciate any help with the code or recommended links. Essentially, I want t ...

What are some ways to personalize column design when a Kendo grid column is automatically created?

I am populating the Kendo grid with data using JavaScript: var dataSource = new kendo.data.DataSource({ transport: { read: { url: "@Url.Action("GetProductList", "Home")", type: "POST&qu ...

JQuery If Statement always outputs a consistent number regardless of the input provided

I'm facing an issue with my HTML form and JQuery code that is supposed to calculate a figure. The problem I am encountering is that the if statement always returns the same number, regardless of the input: $(document).ready(function() { ...

Creating a dynamic drop-down box with editable text input using HTML5

I am looking to enhance text editing functionality by incorporating a drop down box and a custom scrollbar. This will allow the end user to input data directly or select from the dropdown options. The final value provided by the user should be saved. I w ...

What is the best way to display an image right in the middle of the header?

My project consists of three main files - an HTML, a CSS, and a JS file. I have developed the HTML using the Bootstrap 5.1.3 framework. The issue I am facing pertains to the alignment of the clothing brand logo within the header section. Despite multiple ...

Tips for executing parallax designs, similar to the techniques used on the

Currently, I am in the process of creating a website that utilizes parallax scrolling. Here is a brief overview of what I have accomplished thus far. I decided to use the skrollr plugin to achieve the desired parallax effect. Through this plugin, I was abl ...

Can you explain the significance of the error message stating "XMLHttpRequest.timeout cannot be set for synchronous http(s) requests made from the window context"?

I'm experiencing some timeouts with a synchronous XML HTTP request in Safari on my Mac. In an attempt to fix this issue, I added a timeout setting like this: req.open(this.method, fullURL, this.isAsync); req.setRequestHeader('Content-Typ ...