1
votes

I am creating an app with Nuxt using nuxt and nuxt-auth to handle the authentication.

I am wanting to have two middlewares for auth - auth and guest. An auth user should not be able to access the login page ('/') and will get redirected to the dashboard, but can access everywhere else. A guest user shouldn't be able to access any page except the login page and will redirected to the login page on any attempts.

Currently everything is working fine with regards to the authentication and logging in. However when an authenticated user clicks a link to '/' OR refreshes the page they get sent to the login page and have 'guest' privilages again even though they are still set to 'loggedIn' in the vuex store. It looks like when the SSR kicks in the auth store isn't available on the server so it redirects the user to the login page and then thats when everything gets messed up, however that is a guess.

Below is some code:

// layout/default <- used for the login page

export default {
  middleware: 'guest'
}

// layout/dashboard <- used for all authenticated user only pages

export default {
  middleware: 'auth'
}

// middleware/guest.js

export default function (ctx) {
  if (ctx.app.$auth.$state.loggedIn) {
    return ctx.app.$auth.redirect('home')
  }
}

The other auth middleware is created with 'nuxt-auth' the nuxt.config.js file has the following settings:

  auth: {
    localStorage: false,
    cookie: {
      options: {
        secure: true
      }
    },
    redirect: {
      login: '/',
      logout: '/',
      callback: '/api/auth/callback',
      home: '/dashboard'
    }
  },
1

1 Answers

1
votes

I think I have it solved. The issue did seem to be with the server side rendering the page as it didn't have access to auth cookie so I've made another middleware which gets applied to the whole site to check auth which does the following:

// Check auth

export default function (context) {
  context.store.dispatch('auth/initAuth', context.req)
}

Then in the Vuex store we check if we are process.server and retrieve the JWT from the cookie header. Then we set the auth store with the user before the auth and guest middlewares are being ran.

I just need to ping the API to check the JWT is valid and then that should be it.