我正在使用 next-iron-session
在我的 NextJS 应用程序中实现身份验证,目前使用 getServerSideProps
方法,它工作正常,但我必须在我想对用户进行身份验证的每个页面中实现这一点。我只想以 HOC 格式或包装器格式实现它,所以我不必在每个文件中重写它。我为此使用以下代码
import { withIronSession } from "next-iron-session";
const user_home = (props) => {
if (!user.isAuth) {
router.push("/");
}
// ...some other layout stuff
};
export const getServerSideProps = withIronSession(
async ({ req, res }) => {
const user = req.session.get("user");
if (!user) {
return {
props: { isAuth: false },
};
}
return {
props: { isAuth: true, user: user },
};
},
{
cookieName: "NEXT_EXAMPLE",
cookieOptions: {
secure: true,
},
password: process.env.APPLICATION_SECRET,
}
);
export default user_home;
答案 0 :(得分:0)
我认为您可以从服务器重定向。
import { withIronSession } from "next-iron-session";
const user_home = (props) => {
// ...some other layout stuff
};
export const getServerSideProps = withIronSession(
async ({ req, res }) => {
const user = req.session.get("user");
if (!user) {
redirect: {
permanent: false,
destination: "/login",
},
}
return {
props: { user: user },
};
},
{
cookieName: "NEXT_EXAMPLE",
cookieOptions: {
secure: true,
},
password: process.env.APPLICATION_SECRET,
}
);
export default user_home;