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

Exploring additional parameters within express.js

I'm currently working on creating an email sender that includes all necessary components such as 'from', 'to', 'subject', 'textBody', etc. However, I am facing a challenge in setting optional parameters in expre ...

The element is implicitly classified as an 'any' type due to the index expression not being of type 'number'

Encountering a specific error, I am aware of what the code signifies but unsure about the correct interface format: An error is occurring due to an 'any' type being implicitly assigned as the index expression is not of type 'number'. ...

Is it possible to keep my JavaScript scripts running continuously within my HTML code?

I recently set up a JavaScript file that continuously queries an API for updates. It's currently linked to my index.html, but I'm looking for a way to keep it live and running 24/7 without requiring the browser to be open. Any suggestions on how ...

The clearing of sessions is not supported by Node.js / Express.js

At the start, the application loads some users using Angularjs / $http.get(). As you scroll down, more users are loaded dynamically (infinite scroll). In addition to this, there are location filters on the page. Users can select a different Country and Ci ...

Is the availability of XMLHttpRequest constant?

When using XMLHttpRequest to retrieve data from the server with Javascript, is it necessary to include conditional checks for the specific browser being used? Is the code snippet below considered standard practice when working with XMLHttpRequest? if (w ...

Dividing an array of characters within an ng-repeat and assigning each character to its individual input tag

Hello, I'm currently learning Angular and I have a unique challenge. I want to take the names in a table and break each name into individual <input> tags, so that when a user clicks on a letter, only that letter is selected in the input tag. For ...

Error: The current component does not have a template or render function specified. Check the <App>

I am a beginner in Vue js and I am facing an issue while running my application. It is showing an empty page with the error message: Component is missing template or render function. at <App>. Additionally, there is also a warning from Vue Router sa ...

Uploading files using Ajax in the Laravel framework

I am attempting to utilize ajax to upload a file in Laravel. $("#stepbutton2").click(function(){ var uploadFile = document.getElementById("largeImage"); if( ""==uploadFile.value){ } else{ v ...

Ways to successfully pass multiple parameters in Nuxt

Within Nuxt.js, when working with the code in pages/posts/_id.vue, it looks like this: <template> ...

`Count the number of rows needed to accommodate text line breaks within a div element`

Is there a method to determine the number of lines that text breaks into using the CSS property word-break: break-all? For example, if I have a div like this: <div>Sample text to check how many lines the text is broken into</div> And the corr ...

Updating a JSON data structure after removing an item using AngularJS

As a newcomer to AngularJS, I have created a Service using Java and integrated it into Angular to handle the deletion of Contact objects. On my homepage in AngularJS, this is the code I have: <!--RESULTS--> <form> <table class="table table ...

Transmitting data as an array using JQuery

$('[data-toggle="mftapproveCheck"]').click(function () { var selected = $("#checkboxes input:checked").map(function (i, el) { return el.value; }).get(); //alert("selected = [" + selected + "]\nas int = \"" + selected.join(";") ...

What are some ways to lazily load directives in AngularJS?

Currently, I am exploring the capabilities of angularjs and aiming to dynamically load directives only when they are required instead of loading all of them initially on the page. My focus is on creating custom directives for the plugins that I use frequen ...

Challenge with Angular *ngFor: Struggling to Access Previous Elements

In my angular and node application, I am using socket.io. When a user joins the room, they can see their username in the user list. If another user joins, the first user can see both usernames but the new user can only see their own. This pattern continues ...

When executing an $http get request in Angular, a promise is

After implementing this code in my service and noticing that it works, I have a question. Since $http.get() returns a promise which executes asynchronously, I am confused about why I need to use deffered.resolve(res.data) to return data in my service. Yo ...

Issue with VueJS: Method not displaying returned data

I am successfully able to retrieve data in the console. However, I am encountering an issue when trying to display this data on the webpage using double curly braces. The rest of the template displays fine without any issues. Template: <template> ...

Obtain JSON data using jQuery

Hey there! I am currently working on understanding how to retrieve data using json/JQuery with the code below. After storing a php variable in a json variable (var ar), I confirmed its contents through console.log, although when I used document.write it d ...

What is the best way to implement onChange for multiple form fields in Reactjs?

Can anyone help me troubleshoot my form? I'm having issues with typing into the fields and nothing happens when I try. Initially, whatever text I input would show up in all the fields simultaneously, but after making some changes, it stopped working ...

Discovering a way to retrieve objects from an array of objects with matching IDs

Here is a code snippet I put together to illustrate my objective. arr = [ { id:1 , name:'a', title: 'qmummbw' }, { id:2 , name:'b', title: 'sdmus' }, { id:2 , name:'', title: 'dvfv' }, ...

Sped up object outpacing the mouse pointer

I'm currently developing a drag and drop minigame, but I've encountered an issue with the touch functionality. The draggable function (using only cursor) works flawlessly, however, when I tried to implement touch support for mobile and tablet use ...