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)
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With