SRR
SRR

Reputation: 1748

Get user on initial page load - Nuxt middleware

I'm using Firebase Auth in my Nuxt app and having some trouble with protected routes. I have the nuxt middleware enabled that handles redirection based on whether or not a user a logged in on page navigation.

My issue is, if you visit a protected route from the address bar and you were previously logged out, you'll be given access to the route. However if you try to visit another protected route from that route you'll be redirected. I am using Vuex to handle the user logged in state.

How can I get the middleware to kick in on a 'cold start' for a protected route.

Middleware: router-auth.js

export default function({ store, redirect, route }) {
    const user = JSON.parse(store.state.Authentication.user)
    console.log(user);
    user !== null && route.name === '/' ? redirect('/dashboard') : ''
    //user === null && route.name !== '/' ? redirect('/dashboard') : ''
  }

Plugin: auth.js

import firebase from "firebase/app";
import "firebase/auth";

export default function ({store, router}) {
  firebase.auth().onAuthStateChanged((user) => {
      if(user){
        store.dispatch('Authentication/SET_USER',JSON.stringify(user))
      }else{
        store.dispatch('Authentication/SET_USER', null)
      }
  })
}

Vuex: Authentication.js

export const state = () => ({
    user: ''
});

export const getters = {
    user: state => {
      return state.user;
    },
  
  }

export const mutations = {
    SET_USER: (state, payload) => {
        state.user = payload;
    },
}

export const actions = {
    SET_USER({ commit }, payload) {
        commit('SET_USER', payload)
    },
}

Upvotes: 1

Views: 2295

Answers (1)

Sergey Mitrichev
Sergey Mitrichev

Reputation: 116

You can return an error func call in middleware:

export default function({ store, redirect, route, error }) {
  const accessDenied = true // ... your access route logic goes here
  if (accessDenied) {
    return error({
      message: 'access denied',
      statusCode: 403
    })
  }
}

Upvotes: 2

Related Questions