如何在nextjs页面中检查身份验证状态

时间:2020-10-14 23:34:55

标签: javascript firebase-authentication next.js

我不知道为什么在以下情况下调用auth.currentUser总是返回null。我还有另一个侦听auth状态并识别用户已登录(正确)的组件。

import { auth } from "../lib/firebase";

type Props = {
  hiProp: string;
};

const Index = ({ hiProp }: Props) => {
  useEffect(() => { 
    if (auth.currentUser) { // this never resolves to true
      const router = useRouter();
      router.push("/home");
    }
  }, []);

  return <div>{hiProp}</div>
}

export default Index;

export const getStaticProps = async () => {
  const hiProp = await getHiProp();

  return {
    props: { hiProp },
  };
};

1 个答案:

答案 0 :(得分:1)

当不确定是否有用户登录时,currentUser属性被记录为null。最初加载网页时,该属性最初始终为null-用户未预先填充对象,它以前已登录。您必须使用auth state observer来确定用户对象何时首次可用,就像您说其他代码正在做的那样。

确定登录用户需要花费不确定的时间。您可以在这篇描述why currentUser is unexpectedly null的博客文章中了解有关此内容的更多信息。