Forced page transition after login with nuxt/auth

1.5k Views Asked by At

Assumption

I am implementing a login function in nuxt/auth. I want to implement a guest login function, but when I press the button to log in as a guest, it doesn't go to /search, it goes back to user/login. I would like it not to go to the login page. The specified page is displayed for a moment, but user/login is displayed immediately.

What we want to achieve

I want to be redirected to a specified page after pressing the guest login button.

Code

Pages with a 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') // I get back to the login page without going to /search.
    }
  }
}
</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
        }
      }
    }
  },
2

There are 2 best solutions below

0
On BEST ANSWER

As explained here and in a lot of my previous answers regarding nuxt/auth, you should have something like this rather.

<script>
export default {
  methods: {
    async logMeIn() {
      const positiveResponseFromBackend = await this.$auth.loginWith('local', {
        data: {
          email: 'fancy email',
          password: 'cool password',
        },
      })
      if (positiveResponseFromBackend) {
        await this.$auth.setUser({
          email: 'fancy email', // can of course be dynamic or fetched from your backend as a response
          password: 'cool password', // same here
        })
      }
    },
  },
}
</script>

This will successfully login you via the auth module, hence you will be redirected automatically to your home value as in the redirects object (no need for a router.push).

nuxt.config.js

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

It could be because this.$auth.loginWith is asynchronous, which means that this.$router.replace('/search') would be executed beforee the auth login function has returned.

You could try this instead:

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