【问题标题】:Next JS - Handling getInitialProps on _app.js in SSR vs CSRNext JS - 在 SSR 与 CSR 中处理 _app.js 上的 getInitialProps
【发布时间】: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


    【解决方案1】:

    我认为您的代码足够干净。当然你仍然可以维护它。

    我的建议如下:

    MyApp.getInitialProps = async (appContext) => {
    

    在这一行中,您可以使用对象解构技术来直接获得上下文:

    MyApp.getInitialProps = async ({ ctx }) => {
    

    那么您将不再需要此行:let ctx = appContext.ctx;

    顺便说一句,可以清理的代码中最重要的部分是您在 if/else 条件下两次编写身份验证请求的区域。我建议您像这样实现该部分:

    const cookie = ctx.req ? ctx.req.headers.cookie : window.document.cookie;
    

    虽然我会尝试将所有内容都保留在服务器端的 getInitialProps 中,但在这种情况下,我会进行一些小改动以获取 cookie 并仅在服务器端进行处理。

    const cookie = cookie.parse(ctx.req ? ctx.req.headers.cookie || "" : undefined);
    

    请注意:我使用的是 cookie 解析器,您也可以自己安装包。 (npm install cookie)

    如果您需要在客户端对 cookie 进行额外检查,我将在 componentdidmount 中进行检查,或者如果您在 useEffect 中使用反应挂钩。不过没必要。

    现在您可以实现一次//Do auth request,这将使代码更简洁,当然也可以减少不必要的重复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 2021-09-13
      • 2019-11-14
      • 2023-02-09
      • 2020-08-01
      • 1970-01-01
      • 2021-02-04
      相关资源
      最近更新 更多