Synchronize your store by utilizing cookies in the nuxtServerInit function of NuxtJS

I am currently working with NuxtJS's auth module and attempting to retrieve the Bearer token along with a custom cookie that holds a sessionType during nuxtServerInit in order to update the store through a mutation. However, I am facing an issue where this only works when I refresh the page.

When I close the browser and navigate directly to my app URL, I consistently receive 'undefined' for auth._token.local because the nuxtServerInit function runs before the cookies are fully loaded.

The code snippet in my store/index.js file appears as follows:

export const actions = {
  async nuxtServerInit({ commit, dispatch }, { req }) {
    // Parse cookies using cookie-universal-nuxt
    const token = this.$cookies.get('token')
    const sessionType = this.$cookies.get('sessionType')

   // Check if Cookie user and token exists to set them in 'auth'
    if (token && user) {
      commit('auth/SET_TOKEN', token)
      commit('auth/SET_SESSION_TYPE', sessionType)
    }
  }
}

I am utilizing the nuxt-universal-cookies library.

Is there a method to delay the execution of the action until after the cookies have been successfully loaded in the browser?

Answer №1

It's interesting how hitting F5 triggers the desired behavior but hitting Enter does not. This inconsistency suggests that the functionality may work intermittently, as both F5 and Enter should typically produce the same result in Nuxt (with some exceptions for cache headers).

The use of an async function in your code is a bit suspicious, especially since the function does not return or await any promises.

You can either await for an action:

export const actions = {
  async nuxtServerInit({ commit, dispatch }, { req }) {
    // Parsing cookies using cookie-universal-nuxt
    const token = this.$cookies.get('token')
    const sessionType = this.$cookies.get('sessionType')

   // Checking if there is a Cookie user and token to set them in 'auth'
    if (token && user) {
      await dispatch('SET_SESSION', {token, user})
    }
  }
}

Alternatively, you could remove the async keyword from the declaration:

export const actions = {
  nuxtServerInit({ commit, dispatch }, { req }) {
    // Parsing cookies using cookie-universal-nuxt
    const token = this.$cookies.get('token')
    const sessionType = this.$cookies.get('sessionType')

   // Checking if there is a Cookie user and token to set them in 'auth'
    if (token && user) {
      commit('auth/SET_TOKEN', token)
      commit('auth/SET_SESSION_TYPE', user)
    }
  }
}

Answer №2

After experiencing a similar problem myself, I discovered that nuxtServerInit actually gets activated prior to the cookie being established through an express middleware.

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 steps do I need to take to retrieve my paginated data from FaunaDB in a React frontend application?

I am facing a challenge when trying to access the data object that contains the keys (letter and extra) in my response from the faunadb database to the frontend react. Although I have used the map function in my frontend code, I have not been successful ...

Prevent regex special characters in JavaScript while preserving the original string for keyword matching

As I develop my web page, I encountered an issue while trying to highlight text based on user input in the search box. My search algorithm matches each space-separated keyword, but ran into problems when including brackets in the search term. This caused a ...

The component in React does not refresh after updating the state

I have a React page where I am displaying a list of quizzes fetched from an external API. There's also a "New Quiz" button that opens a dialog with a form for users to create a new quiz. My issue is with making the table re-render once the POST reque ...

Is there a way to highlight today's working hours with a different color using Vue.js?

Here is the script I have created to display the working hours: const workHour = "Monday :9:00AM to 5:00PM,Thursday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM ...

Avoiding the capturing of events on $( document ).mousemove

Each time the browser detects a $( document ).mousemove event, my function is invoked. The performance is smooth with an empty page, but once I introduce a div element and hover over it, the function gets executed twice: first on the document and then agai ...

Utilizing the swiper's onSlide change event to access various methods of my component

I am attempting to update another component in my application whenever the user changes the slide on the swiper. I have succeeded in console logging the swipe and identifying the slide number, but when I try to call the other method to render the other com ...

Leveraging jquery's $.ajax method to send GET values to a PHP endpoint

Is it possible to use an AJAX call to pass a value to a PHP script? For example, if I have the URL example.com/test.php?command=apple, how can I make sure that the code is executed properly on the server side? This is how my code looks like: PHP: <?p ...

Adjust Vue FilePond dimensions

I am currently working with a Vue Filepond and trying to ensure that it fills the height of its container. My Vue Filepond setup also involves Vuetify. Whenever I attempt to set values in the CSS, they are constantly overridden by 76px. Although fill-hei ...

What issues are hindering the successful export of my Vue component packaged with npm?

I created a small local npm package called fomantic-ui-vue with the following main js file: import Vue from 'vue' // Import vue component import button from './elements/button/button.vue' import buttonGroup from './elements/butt ...

Transition smoothly between two images with CSS or jQuery

I am working on a project where I need to implement a hover effect that fades in a second image above the initial image. The challenge is to ensure that the second image remains hidden initially and smoothly fades in without causing the initial image to fa ...

Show the user's name in an Express partial once they have logged in

I've been trying to find a solution for my issue without success. Here's the scenario: I have a homepage ('/'), a profile page ('/profile'), and a login/register page. I'm using passport with local, twitter, and google fo ...

In the process of developing a custom Vue component library with the help of Rollup and VueJS 3

My goal is to develop a custom Vue component library using rollup and Vue.js. The process went smoothly with Vue2, but I encountered issues parsing CSS files with Vue3. To address this, I updated the dependencies in the package.json file. package.json { ...

Sharing stickers with Discord.js version 13

I have encountered an issue while trying to forward messages sent to my bot via DM. Everything is functioning smoothly, except for sending stickers. Whenever I attempt to send a message with a sticker, an Error DiscordAPIError: Cannot use this sticker is ...

Display HTML content repeatedly depending on the number selected in a dropdown menu using AngularJS

I need your assistance with a dropdown selection feature on my website. The idea is that based on the number chosen from the dropdown, I want to dynamically repeat sections in HTML. For example, if I select 3 from the dropdown menu, the page should display ...

Is there a way to execute a script during every npm install process?

Is it possible to set up pre-push hooks for Git with each npm install action? Are there any alternative solutions that do not involve installing tools like Gulp, and instead rely solely on npm? ...

Ways to resolve Error: Project needs yarn, but it is not currently installed

Just finished setting up my new project using the following commands: npm install --global yarn vue create elecprog yarn serve (-> encountered an error) Running everything through VS Code terminal. PS D:\elcp\elecprog> yarn serve yarn run ...

Identify the row containing a value of null using jQuery (functionality not performing as anticipated)

Whenever the user clicks on the GetData button, I retrieve JSON data and display it in an HTML table similar to the demo below. Demo: https://plnkr.co/edit/I4XYY6CZohf7IS6wP8dR?p=preview There are instances where the value can be null, such as the loanNu ...

Does adding .catch resolve a promise?

Being new to typescript / javascript, I have limited knowledge about promises. My current scenario involves creating three distinct promises within a cloud-function and subsequently returning them using Promise.all([promise1, promise2, promise3]). Each of ...

Securing API endpoints in a React/Redux application using proxy techniques

Ensuring the security of my react/redux application is a top priority for me. I've noticed that my api url is exposed to the public inside the bundled app.js file, which raises some concerns. After doing some research, I discovered that some developer ...

Create a dropdown menu with selectable options using a b-form-select

I am working with a b-form-select element that displays options based on user input. I am trying to figure out how to trigger a function when the user selects one of the dynamically generated <b-form-option> elements, but I am struggling to capture b ...