javascriptvue.jsauthenticationnuxt.jsnuxt-auth

Forced page transition after login with nuxt/auth


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
        }
      }
    }
  },

Solution

  • 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'
      },
    },