【发布时间】:2020-11-30 11:57:03
【问题描述】:
我正在尝试创建一个 Next JS 应用程序来处理 getInitialProps 中的身份验证和初始路由。我发现这个方法既可以在服务器上执行,也可以在客户端上执行。 到目前为止,我的方法是基于检测我是否在服务器中执行来检查 ctx 内部是否存在 req 属性,从而拥有 2 个不同的处理程序。 这可以解决问题,但感觉不是正确的做法。有人可以请告诉我是否有更清洁的方法。 所有身份验证都在单独的子域中处理,因此如果没有 cookie 或身份验证请求因其他原因失败,我只需要重定向到身份验证子域。
import "../../styles/globals.css";
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
MyApp.getInitialProps = async (appContext) => {
let cookie, user;
let ctx = appContext.ctx;
//Check if I am in the server.
if (ctx.req) {
cookie = ctx.req.headers.cookie
//Do auth request.
//Redirect base on user properties
// handle redirects using res object
ctx.res.writeHead(302, { Location: "/crear-cuenta"});
} else {
cookie = window.document.cookie;
//Do auth request.
//Redirect base on user properties
//Do redirects using client side methods (useRouter hook, location.replace)???
}
//Return pageProps to the page with the authenticted user information.
return { pageProps: { user: user } };
};
export default MyApp;
【问题讨论】:
标签: reactjs authentication cookies next.js