paint-brush
Using $auth Module’s Redirect in Tandem With $router.push in Nuxt.jsby@abrar
3,838 reads
3,838 reads

Using $auth Module’s Redirect in Tandem With $router.push in Nuxt.js

by abrarMarch 15th, 2020
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Using $router.push in Nuxt.js and invoking a.router.push in subsequent line of code in the same method is redundant. The conundrum began when the lines after the.auth.loginWith method did not execute as intended since the page was redirected to the redirect. URL. The only thing left to do is disabling the redirect case in the. auth option: false will do the job! The.auth object in nuxt.config.js would look like this now:

Company Mentioned

Mention Thumbnail
featured image - Using $auth Module’s Redirect in Tandem With $router.push in Nuxt.js
abrar HackerNoon profile picture

Recently I came across the issue of using the auth module in Nuxt.js and invoking a $router.push in subsequent line of code in the same method. The conundrum began when the lines after the auth.loginWith method did not execute as intended since the page was redirected to the redirect URI.

It has been only a week in the Vue.js land, so I suppose this issue is something faced by many newbies.

So, here goes where it all started:

I have a authenticate() function, whose body looks like:

try {
 await this.$auth.loginWith('local', { data: this.user })
 // some other line of code that shows loading msgs
 // ...
 this.$router.push(this.localePath({ path: 'dashboard' }))
} catch (e) {
  // handling error
}

Now, notice that once the line: 2 gets invoked, the execution is handed over to the auth middleware of nuxt.js. Thus, using a $router.push in line:5 is redundant.

Before we proceed any further, let’s take a look where the auth’s configs are defined:

Go to: 

nuxt.config.js

Find the key 

auth

  auth: {
    redirect: {
      login: '/login',
      logout: '/',
      callback: '/login',
      home: 
    },

Notice, the 

home
 key.

Bingo!

This is exactly where we want to tweak.

Before we do any tweaking, let’s make it clear what we are trying to do and why:

  • We want to use all the good things offered by the auth module, other than the redirect thing.
  • The lines after the $auth.loginWith are necessary to be executed before the view can be updated. In this case it is a loading and success notification that needs to be shown before the user is redirected to the dashboard upon successful login.

Now, the only thing left to do is disabling the redirect case in auth option

  • home: false
     will do the job!

The auth object in nuxt.config.js would look like this now:

 auth: {
    redirect: {
      login: '/login',
      logout: '/',
      callback: '/login',
      home: false
    },

Bam! We are done.

Previously published at https://medium.com/consol/using-auth-modules-redirect-in-tandem-with-router-push-in-nuxt-js-d6d703e0a85a