The Nuxt auth module fails to update the user's loggedin status within the store state

Currently, I am implementing Authentication functionality using the Nuxt Auth Module.

My frontend is built on Nuxt Js, while my backend is running Laravel 5.7

In nuxt.config.js, I have configured the auth settings as follows:


auth: {
    strategies: {
        local: {
            endpoints: {
                login: { url: 'login', method: 'post', propertyName: 'access_token' },
                logout: { url: 'logout', method: 'post' },
                user: { url: 'user', method: 'get', propertyName: 'user' },
            }
        },
        tokenRequired: true,
        tokenType: 'bearer',
    }
},

Within my index.vue file, I have a form with a login method:


<template>
    <div>
      <div>
        <b-container>
          <b-row no-gutters>
            <b-col col lg="12">

            </b-col>
          </b-row>
          <b-row no-gutters>
            <b-col col lg="12">
                <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm" label-position="top">
                  <el-form-item label="Email" prop="email">
                    <el-input v-model="ruleForm.email" ></el-input>
                  </el-form-item>
                  <el-form-item label="Password" prop="password">
                    <el-input type="password" v-model="ruleForm.password" autocomplete="off"></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="login">Login</el-button>
                  </el-form-item>
                </el-form>
            </b-col>
          </b-row>
        </b-container>
      </div>
    </div>
</template>

<script>
export default {
    layout: 'login',
    data() {
        var validatePass = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('Please enter a password'));
            } else {
                callback();
            }
        };
        return {
            ruleForm: {
                email: '',
                password: '',
            },
            rules: {
                password: [
                    { validator: validatePass, trigger: 'blur' }
                ],
                email: [
                    { required: true, message: 'Please enter an email', trigger: 'blur' },
                    { type: 'email', message: 'Please enter a valid email address', trigger: ['blur'] }
                ]
            }
        };
    },
    methods: {

        async login() {
            try {
                await this.$auth.loginWith('local', {
                    data: {
                        username: this.ruleForm.email,
                        password: this.ruleForm.password
                    }
                }).then(() => {
                        this.$router.push({ name: 'dashboard'})
                    })
            } catch (e) {
                console.log(e)
            }
        },
    }
}
</script>

Upon attempting to log in, the asynchronous function 'login' is triggered. The corresponding user based on the given username and password is returned. However, upon checking the Vuex state, `auth.loggedIn` remains false and `auth.user` is undefined.

I initially believed that Nuxt Auth would automatically update the state. Am I overlooking something?

Any assistance would be greatly appreciated! 😄

Answer â„–1

After much searching, I finally cracked the code. The key was to disable the property name in the user endpoint.

Outdated version

      endpoints: {
          login: { url: 'login', method: 'post', propertyName: 'access_token' },
          logout: { url: 'logout', method: 'post' },
          user: { url: 'user', method: 'get', propertyName: 'user' },
      }

Updated version

      endpoints: {
          login: { url: 'login', method: 'post', propertyName: 'access_token' },
          logout: { url: 'logout', method: 'post' },
          user: { url: 'user', method: 'get', propertyName: false },
      }

Now, the user information is successfully loaded into the state

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 way to extract the frameset from a frame window?

Here is a code snippet to consider: function conceal(frameElem) { var frameSet = frameElem.frameSet; //<-- this doesn't seem to be working $(frameSet).attr('cols', '0,*'); } //conceal the parent frame conceal(window.pa ...

A malfunction report stemming from an HTTP error code while using react.js/javascript

In my react.js application, I have a Component that displays an error code. It currently looks like this: https://i.stack.imgur.com/2usiy.png Now, in addition to displaying just the code, I also want to show the reason for the error. Similar to how this ...

Using Angular's ngBlur directive on multiple input fields

My current task involves capturing and saving all content on a webpage after it has been edited. For example, when a user clicks into an input field, enters data, and then clicks elsewhere, I would like to trigger a function to collect all the model data a ...

Creating a task management application using AXIOS and VUE for easy data manipulation

I am currently working on a small app to enhance my skills in VUE and Axios. However, I am facing a roadblock when it comes to the update functionality. I am struggling to pass the ID to the form for updating and despite watching numerous tutorial videos ...

Within the materia-ui table, I am facing an issue where clicking the button to expand a row results in all rows expanding. I am seeking a solution to ensure only the selected row expands

When a row is clicked, all rows in the data table expand to show inner data for each row. The issue is that clicking the expand button expands all rows rather than just the selected row. Each time I try to expand one specific row, it ends up expanding mul ...

The function _vm.$refs.menu.open is not defined

Utilizing vue-context to customize the default context menu, I encounter an error when trying to interact with it from a component. Below is my code snippet: <!-- Main --> <p @contextmenu.prevent="$refs.menu.open">test</p> <C ...

Can you provide guidance on effectively utilizing a Pinia store with Vue3, Pinia, and Typescript?

I'm currently facing challenges while using the Pinia store with TypeScript and implementing the store within a basic app.vue Vuejs3 option api. Here is my app.js file: import {createApp} from 'vue' import {createPinia} from "pinia&quo ...

Using JSON.parse in Node.js to manipulate arrays with Javascript

While taking an online course, I came across a confusing code snippet: notes = JSON.parse(notesString). The confusion arises from the fact that this code is supposed to result in an object, but it's being treated as an array. Isn't JSON.parse sup ...

Exploring the proper method for closing connections in Node JS and the pg module

I'm experiencing frustration with the node pg module as I keep encountering a 'too many clients already' error. For instance, in my app.js file, I handle various routes where I query data from postgres. Here's a snippet of how app.js i ...

Troubleshooting a Laravel 5.2 modal popup issue for password recovery, experiencing a 500 internal server error with the Ajax function execution

Is there a way to check if an email exists in order to send a reset password link using an AJAX function? I keep encountering a 500 internal server error before the AJAX runs. I understand that a 500 error is usually due to a token mismatch, but do I actua ...

Remove all stored data from localStorage and update the view in Backbone framework

Hi, currently I am using backbone localstorage and facing an issue where I need to clear the localstorage every time a user hits the search button. This will allow me to add new data to the localStorage without any conflicts. Additionally, I am attempting ...

The input form in my Node.js project is not adapting to different screen sizes. I am currently utilizing ejs as the template

I have integrated ejs as a template in my Node.js project, but I am encountering an issue with the input form in the following code snippet. The form is unresponsive, preventing me from entering text or clicking on any buttons. What could be causing this ...

Achieving sequential actions in Javascript without the need for state updates

One aspect of jQuery that I find impressive is its ability to chain methods like .animate() and .css(). This is made possible by utilizing the special variable "this" in the backend code. I am interested in implementing a similar method chaining mechanism ...

Is there a way to switch an element across various pages within Ionic 3?

Is it possible to exchange information between two pages using logic? I have successfully implemented a checklist, but I am unsure how to add a success/error icon next to the Room name on the 'verifyplace.html' page after invoking the goToNextPa ...

Is the variable leaping to a superior scope?

A few days back, I encountered a strange bug in my code that has left me puzzled. It appears that a variable declared within a narrower scope is somehow leaking into a broader one. Any insights into what might be going wrong here? Here's a simplified ...

Receive fresh properties in React and subsequently reset state

I need some guidance on this issue: My scenario involves a parent React component and its child. The parent component contains a table, while the child has its own controls. What I am trying to achieve is the ability to click on a cell within the parent&a ...

Property-based Angular Material row grouping in a mat-table is a powerful feature that enhances

Is there a way to organize the data in one row with the same ID? Currently, my data looks like this: Data Set: { "id": "700", "desc": "Tempo", "richiesta": "20220087", "dataElab": &quo ...

In Reactjs, the specified property title is not found within the string type

Currently, I am working with Reactjs and using the nextjs framework. I have encountered an issue while fetching data where I am receiving an error message stating "Property 'title' does not exist on type 'string'". How can I r ...

Tips for determining if an item in one array is present in a different array

Looking for a way to disable a button using React code? Take a look at the snippet below: todos.filter(todo => todo.completed === true) .map(todo => todo.id) .includes(this.state.checkedIds) But there's a catch - it always seems to return ...

Problems arise with identification of asynchronous functions

My async functions have been used successfully in various projects, but when incorporating them into a new project, they suddenly stopped working. One of the functions causing trouble is: const ddbGet = async (params) => { try { const data ...