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!
CodePudding user response:
I would recommend using Firebase Session Cookies if you need user's information before rendering the web page in SSR. You can then check for the cookie in your middleware, if it's present then you can verify it using verifySessionCookie
method (similar to verifyIdToken
) in Admin SDK.
If the cookie is valid then add user info to state and render the page else redirect to login or any other page.
I recently wrote an answer explaining how to get user data on server side in short here: