What could be causing my Vuex store state to consistently come up empty in middleware when accessing it through SSR (Server-Side Rendering) with NuxtJS?

Question: I am facing an issue with my middleware files. More specifically, I have a file named authenticated.js. In this file, I have a function that checks for authentication.

Here is the code snippet:

export default function (context) {
    //console.log('context.store.state :>> ', context.store.state);

    if(process.server === true) { //Server Side

        //why is my store state here is always empty when access in SSR
        console.log(context.store.state.authen.UserToken);

    } else { //Client Side

        if(!context.store.state.authen.UserToken) {
            context.redirect('/error');
        } else {
            //Refresh Token
            context.$axios.get("authen/refresh")
                .then((res) => {
                    const payload = {
                        UserToken: res.data.DataReturn.Token,
                        UserId: res.data.DataReturn.UserId,
                        UserEmail: res.data.DataReturn.UserEmail,
                        UserFullname: res.data.DataReturn.UserFullname
                    };
                    context.store.dispatch("authen/SetLogin", payload);
                })
                .catch(function (error) {
                    context.redirect('/error');
                });
        }

    }
}

The problem I am facing is that the state is always empty when accessing in SSR. Why is this happening? I can access the store if the call is from the client side. Any suggestions or solutions are appreciated.

Answer №1

The response you seek is anticipated from the server, however, the process is taking place on the client side. In response to your query, nuxtServerInit is the solution. Since SSR operates on the server side, you must populate the store by invoking nuxtServerInit as shown below.

actions: {
  nuxtServerInit ({ commit }, { req }) {
    if (req.session.user) {
      commit('user', req.session.user)
    }
  }
}
     

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

Ways to refresh my $scope once new data is inserted into the SQL database

As I implement the angularjs/SQL technique to fetch data from a database, the code snippet below demonstrates how it is done: $http.get("retrieveData.php").then(function(response){ $scope.tasks = response.data.tasks; }) In addition, there is a functi ...

CSS: elements that are only visible when positioned above specific elements

Can we create an element that is only visible above specific other elements? For instance, in the following code snippet, I want the .reflection element to be visible only above the .reflective elements (located at the top and bottom) and not visible on t ...

The i18n feature in node.js seems to be malfunctioning as the setLocale function is not working properly. Regardless

Something seems off with my usage of the i18n library, but I believe I'm following the correct steps. I've been attempting to switch the locale. Here's my current code. Despite calling setLocale on the global i81n variable, it continues to ...

Ways to display distinct text boxes based on selected radio button?

Currently, I am working with JSP and have implemented an HTML form that includes a "Process" button at the top. When this button is clicked, it displays a form with two radio buttons - TestClient and TestServer. The form also contains a Submit button. If ...

Understanding why we use the `&&` operator in reference to a Google instance

Currently, I am utilizing the vue2-google-maps module and stumbled upon this syntax while trying to access the google instance from within a component prop. scaledSize: google && new google.maps.Size(50, 50) This syntax is used like so: <Gmap ...

Enter a socket.IO chat room upon accessing an Express route

Encountering difficulty when attempting to connect to a socket.IO room while accessing a specific route in my Express application. The current setup is as follows: app.js var express = require('express'); var app = express(); var http = requir ...

What is the method for defining functions that accept two different object types in Typescript?

After encountering the same issue multiple times, I've decided it's time to address it: How can functions that accept two different object types be defined in Typescript? I've referred to https://www.typescriptlang.org/docs/handbook/unions ...

Exploring Vue.js: Navigating through child components from parent component

I currently have 3 components in my project: Form, Card, and Button. Let's start with the Button.vue component: <template> <div> <slot v-bind="{ text }"> <button>{{ text }}</button> </slot> ...

Unable to make anchor tag inside button effectively collapse another div

My Nuxt 2 SSR + Bootstrap 5 application includes the following code snippet: <button v-for="file of orderProduct.files" class="collapsed son-collapse" type="button" data-bs-toggle=&quo ...

What is my strategy for testing a middleware that accepts arguments?

Here is the middleware I am working with: function verifyKeys(expectedKeys: string[], req: Request): boolean{ if (expectedKeys.length !== Object.keys(req.body).length) return false; for (const key of expectedKeys) { if (!(key in req.body)) return ...

Updating AngularJS to have the same page TITLE tag as the page's H1 tag

Is there a way to dynamically update the title tag of my page based on the H1 tag in AngularJS? In jQuery, I could achieve this by: var title = $('#content').find('h1').first().text(); if (title.length >= 1) { document.title = ...

Is there a way to access the original query string without it being automatically altered by the browser?

I'm currently encountering an issue with query strings. When I send an activation link via email, the link contains a query string including a user activation token. Here's an example of the link: http://localhost:3000/#/activation?activation_cod ...

Unable to resize images in Firefox

Why is it that resizing doesn't seem to work in Firefox but functions fine in Internet Explorer? I'm struggling to find a way to make it consistent across all browsers. My goal is to resize the width to 800 and height to 475, disable maximizing t ...

Activate the HTML drop-down option upon selecting the radio button, or the other way around

I'm attempting to accomplish a task. Below is the code snippet I am working with: <form> <input type='radio' name='radio_flavour' checked/>Unique flavour<br/><input class='double-flavoured' type=&apo ...

Is requestAnimationFrame necessary for rendering in three.js?

I am currently working on the example provided in Chapter 2 of the WebGL Up and Running book. My goal is to display a static texture-mapped cube. The initial code snippet is not functioning as expected: var camera = null, renderer = null, scene = null ...

What are the steps to implement Lazy loading in Node.js?

const posts = await Post.find().populate("receiver").populate("author") try { res.json({ status: true, message: 'All posts fetched', data: posts.reverse() ...

Tips for sharing the scope using module.exports

Within handler.js, I have exported 2 functions: one for initialize() and the other for handle(). The initialize function is used to dynamically load the handler based on the application settings. I have a shared variable called var handler outside the modu ...

Returning a 404 Error stating "Invalid request to /api/users/register."

Encountering an issue with proxy connection - unable to determine the root cause despite verifying all routes. Not able to successfully register the user and store data in MongoDB. Seeking suggestions for resolution. Thank you. Attempting to send user reg ...

The JQuery pagination feature fails to function properly once an AJAX load is initiated

I am using jspages.js to implement pagination with jQuery. Everything works fine when the page is initially loaded. However, I encounter an error when the content for pagination is loaded after an ajax call. The plugin does not seem to work as expected. ...

What is the best way to incorporate autoplay video within the viewport?

My objective is for the video to automatically start playing when it enters the viewport, even if the play button is not clicked. It should also pause automatically when it leaves the viewport, without the need to click the pause button. <script src=& ...