I've got an app that uses middleware to try and redirect a user to another page if he is not logged in.
The page that uses it is set up like so:
pages/upload.vue:
export default {
name: 'Upload',
middleware: 'redirect',
...etc...
The middleware/redirect.js file looks like so:
export default function ({ redirect, store }) {
const isLoggedIn = store.getters.isLoggedIn
console.log(isLoggedIn)
// if (!isLoggedIn) {
// redirect({ name: 'login' })
// }
}
Navigating TO the upload page works fine and the console is logged with true from the middleware, however, doing a manual page refresh or typing the page upload URL in the browser causes the console.log(isLoggedIn) to output false.
So, here is my store/getters.js file logic:
export default {
isLoggedIn: (state) => {
try {
return state.userProfile.uid !== null
} catch {
return false
}
}
}
store/state.js is like so:
export default () => ({
authUser: null,
userProfile: null
})
It looks like the user state is null on initial SSR load. I am using a custom plugin called auth like so:
plugins/auth.js:
and loaded it in nuxt.config.js like so:
plugins: [
{ src: '~/plugins/auth.js' }
]
import { onAuthStateChanged, getAuth } from 'firebase/auth'
import { doc, getDoc } from 'firebase/firestore'
import { db } from '~/plugins/firebase'
export default (context, inject) => {
const auth = getAuth()
inject(
'authObserver',
onAuthStateChanged(auth, async (user) => {
console.log('user state:', user)
if (user) {
...etc...
}
So, all together, the above code outputs the following console log (note the null user state on SSR!):
OK, so obviously we should not care about SSR for client logic like this as it's not needed for crawlers, so how should I write the logic for the middleware to check whether a user is logged in or not? That way I can redirect him to login page to login before proceeding to upload page.
Thanks!
