Necessary page redirection following login using nuxt/auth

Scenario

Currently, I am working on integrating a login feature using nuxt/auth. My goal is to include a guest login option. However, upon selecting the guest login button, instead of being directed to /search, the page goes back to user/login. This behavior is not desired as I want to avoid redirecting to the login page after choosing the guest login option. Although the specified page briefly appears, it quickly switches back to display user/login.

Objective

The aim is to successfully redirect to a specific page after clicking the guest login button.

Implementation

Pages containing the guest login button:

<script>
import * as url from '@/store/constants/url'
export default {
  data ({ $config: { APP_NAME } }) {
    return {
      APP_NAME,
    }
  },

  methods: {
    guest () {
・
・
    .then((response) => {
・
・
      this.$auth.loginWith('local', {data: {
        email: response.email,
        password: "xxxxxx"
      }})
    })
      this.$router.replace('/search') // Issue with redirection to /search after clicking guest login button
    }
  }
}
</script>

nuxt.config.js

auth: {
    token: {
      global: true
    },
    redirect: {
      login: '/user/login',
      logout: '/user/login',
      callback: false,
      home: '/'
    },
    strategies: {
      local: {
        endpoints: {
          login: { url: '/api/v1/auth/sign_in', method: 'post', propertyName: 'token' },
          logout: { url: '/api/v1/auth/sign_out', method: 'delete' },
          user: false
        }
      }
    }
  },

Answer №1

As stated in a previous post here, and also in various answers related to nuxt/auth, it is recommended to implement something similar to the following code snippet.

<script>
export default {
  methods: {
    async logMeIn() {
      const response = await this.$auth.loginWith('local', {
        data: {
          email: 'example@email.com',
          password: 'securepassword',
        },
      })
      if (response) {
        await this.$auth.setUser({
          email: 'example@email.com',
          password: 'securepassword',
        })
      }
    },
  },
}
</script>

This approach will allow seamless login using the auth module, automatically redirecting you to the specified home page defined in the redirects object without requiring explicit router.push method.

nuxt.config.js

auth: {
  redirect: {
    home: '/search'
  },
},

Answer №2

Possibly due to the asynchronous nature of this.$auth.loginWith, causing this.$router.replace('/search') to be triggered before the authentication process is completed.

A potential solution could be:

.then((response) => {
  return this.$auth.loginWith('local', {data: {
    email: response.email,
    password: "xxxxxx"
  }})
})
.then() => { this.$router.replace('/search') }

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 most secure approach for defining the file path of an HTML file within an express.js application?

In my directory setup, I have the index.js file located at: path/to/home-page/src/routes This is also where you can find the __dirname. The html file resides at: path/to/home-page/public/bootstrap/Homepage/page.html To serve the html document by relati ...

When using a callback function in the Array Map method with only one argument, the function argument is returned as the index instead of the item

I'm experiencing an unexpected issue where the callback function of the map method in an array is receiving the index number as the first argument instead of the item itself. Interestingly, when I provide two arguments, the function behaves correctly ...

Please enter the date placeholder with today's date

I need help changing the placeholder to display the current date <input type="date" v-model="selectedDate" class="dateclass" placeholder="[function to retrieve current date]"> ...

The way jQuery and CSS are rendered in the same browser window can vary depending on whether they are loaded via Django or statically

Experiencing a perplexing dilemma. While viewing a web page created using html, jquery, and css on the same browser but in two separate tabs, I am encountering varying renderings of the page. Scenario 1: Directly loading the html file from the file system ...

Sanitizing computed properties in VueJS

Would it be considered safe to add a URL in Vue through a computed property when the link is sourced from an external API service? For instance: <img :src="imgURL"> VueJS computed: { imgURL(){ return `https://exampleur.com${poster.4by4 ...

What causes the "500: Unknown web method" error when JavaScript tries to call a Page WebMethod?

I am encountering an issue with a method in CreateTicket.aspx.cs: [WebMethod()] public static string Categories() { var business = new CategoryBusiness(); var categories = business.ListRootCategories(); return categories.Json(); } Additiona ...

An effective method for injecting a mixin into a component on the fly

A situation has arisen where one of my components needs a mixin based on the props it is given. const timerMixin = { created() { console.log("Timer mixin injected") } } export default { name: 'Component A', props: [&apos ...

Utilize parameters in Ajax's success function to analyze data retrieved from Django's backend

I'm currently working on a Django project where I am trying to handle a form using ajax. I have set up an ajax request to a Django view and receiving the response in JSON format. However, when I attempt to apply if-else conditions on the data, it alwa ...

Update DataTable 1.9 while preserving existing rows

I'm currently using dataTables js version 1.9 Periodically, an ajax call is made to the server to retrieve information that should be displayed in a table every 60 seconds or so. Although I can easily clear and repopulate the table like this: $(id) ...

Creating dynamic HTML elements can be achieved by using JavaScript to dynamically generate and

I have an array var elements = ["What?", "How", "Who", ......]; My goal is to generate the following components: <html .. whatever> <div id="q1"> What? </div> <input type="text" id="a1"></input> <div id="q2"> How ...

What is the best way to integrate varying number formats based on user locale in UI5?

In my SAPUI5 app, I need to display numerical data based on the user's settings in the SU01 backend transaction in SAP Logon. For instance, users can specify decimal separators as: 22,000.000 (twenty two thousand) → US format 22.000,000 (twenty tw ...

Having trouble with the mouse trail code on codepen.io

I am currently attempting to integrate this specific CodePen sample into a Hugo template called Somrat Theme. I'm facing challenges in deciding where to place the HTML file; only the 'no cursor' section should go into style.css, and I need ...

Bug Alert: Incompatibility between Angular $resource and PHP causing issues with Update and Delete functionalities

As a newcomer to both AngularJS and PHP, I have been struggling to find comprehensive documentation on using $resource to update records in a database. While I did come across a helpful tutorial here that covers most aspects of $resource usage, I am having ...

Updating variable value in a Javascript function

I'm currently working on a signup page and I need to verify if an email address already exists in the database. var emailnum = getEmailCount(`select * from contactinfo where email='${email}'`); console.log(emailnum); // Output shows ...

The combination of Inline CSS and Bootstrap classes does not seem to be functioning properly

I'm new to web design and currently working on a website project. My concept involves hiding the #login-box when the user clicks on the login button, and displaying another element (.dashboard) in its place. Initially, I set the .dashboard class to ha ...

Using VueJS to incorporate fixed HTML and Javascript elements

Transitioning from a mustache project to VueJS has been challenging for me. I found it very simple in the past to include common pieces of HTML, such as footers and Google tracking codes. However, with VueJS, some of the methods I've come across seem ...

Is there a way in PHP to establish a database connection only once and reuse it multiple times via Ajax calls in JavaScript?

My current setup involves using Ajax to request a remote PHP file for accessing the database. However, every time I make a request, the connection is re-created. Is there a way for me to create the connection just once and reuse it multiple times? The PHP ...

Adjusting columns dynamically in Vuetify's v-col component

I am currently working on creating a row and column layout based on array values. Here is the code snippet from my component: <template> <v-col cols="columnnum">{{value}}</v-col> </template> At the moment, both value and column ...

Struggling with white space problems? JavaScript can come to the rescue with its regular expression feature for replacing

I am looking to utilize regular expressions in wrapping HTML tags around specific words within a text, Below is an example using JavaScript: In the given scenario, the first "We" is not being replaced. Why is this happening and how can it be modified? va ...

Bootstrap: Retrieve an image from a modal

I am working on a modal that contains a variety of selectable images. When an image is clicked, I want to change the text of the button in the modal to display the name of the selected image. Additionally, I would like to grab the selected image and displa ...