Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nuxt Firebase Authentication Middleware

I'm using Nuxt(vue) as frontend and Firestore and Authentication as Backend. I got the authentication to work to a certain amount, but my problem is refreshing the browser resets the state so my Middleware returns a false result.

Here some code snippets:

Middleware:

export default function ({store, redirect, route}) {

    const userIsLoggedIn = !!store.state.currentUser; 

    if(!userIsLoggedIn) {
        return redirect ('/')
    } 
}

Plugin:

import { auth } from '@/services/firebaseInit.js'

export default (context) => {
    const { store } = context

    return new Promise((resolve, reject) => {
        auth.onAuthStateChanged(user => {
            store.commit('setCurrentUser', user)
            resolve()
        })
    })
}

Now this works in running App but when someone refreshes a page where you need auth it doesnt work and redirect to /, now i dont know how to solve that, would appreciate help and if you need more code then i provide it.

EDIT 1:

   async nuxtServerInit ({ commit }, { req }) {
            let user = await firebase.auth().currentUser

            commit('setCurrentUser', user)
        }
like image 767
Badgy Avatar asked Sep 23 '18 13:09

Badgy


1 Answers

You need to init your user in nuxtServerInit method, otherwise your middleware will be executed on server with empty user and hence redirect will happen.

You need to grab user data from req object. See this repo for reference implementation https://github.com/davidroyer/nuxt-ssr-firebase-auth.v2

like image 56
Aldarund Avatar answered Nov 20 '22 05:11

Aldarund