'how to get firebase use in nextJS getserversideprops

I want to get 'sample' document in Firestore using getServerSideProps if there is signed user. Code below doesn't work. It's result is 'can't read' What should I do? or is there the other way?

export const getServerSideProps = () => {
  let currentUser = []

  authService.onAuthStateChanged(async user => {
      if(user) {
        const docRef = dbService.collection('whole_users').doc('sample').get()
        await docRef.then((doc) => {
          if(doc.exists) {
            currentUser.push(doc.data())
          }
        })
      } else {
        console.log("can't read")
      }
    })

  return {
    props: {currentUser}
  }
}


Solution 1:[1]

The first: You call get() without an await. Chaneg your code to this:

export const getServerSideProps = () => {
  let currentUser = []

  authService.onAuthStateChanged(async user => {
      if(user) {
        const docRef = dbService.collection('whole_users').doc('sample')
        await docRef.get().then((doc) => {
          if(doc.exists) {
            currentUser.push(doc.data())
          }
        })
      } else {
        console.log("can't read")
      }
    })

  return {
    props: {currentUser}
  }
}

The second: onAuthStateChanged is only for the client side. To access the auth state on the server side you would need to put the auth state into a provider. Here is an example how to do it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1