我要保护的路线:/account
如果用户未通过身份验证,则重定向到/signIn
NextJS文档上提供的示例目前无法正常工作: with-firebase-auth
所以我提交了一个问题: with-firebase-auth-example-not-working
此外,我是NextJ的新手,而且不幸的是,我从未使用过JWT :(或任何种类的后端保护路由cookie / JWT / sessions实现...。直到我想要/需要它。
我尝试过什么样的解决方法,就像这样:
import Account from "./Account.js";
import Loading from "./Loading.js";
import { useRequireAuth } from "./use-require-auth.js";
function Account(props) {
const auth = useRequireAuth();
// If auth is null (still fetching data)
// or false (logged out, above hook will redirect)
// then show loading indicator.
if (!auth) {
return <Loading />;
}
return (
<Account auth={auth} />
);
}
// Hook (use-require-auth.js)
import { useEffect } from "react";
import { useAuth } from "./use-auth.js";
import { useRouter } from "./use-router.js";
function useRequireAuth(redirectUrl = '/sigIn'){
const auth = useAuth();
const router = useRouter();
// If auth.user is false that means we're not
// logged in and should redirect.
useEffect(() => {
if (auth.user === false){
router.push(redirectUrl);
}
}, [auth, router]);
return auth;
}
但这都是在客户端发生的。...服务器没有检查任何内容。