【问题标题】:How would I check for a cookie on every request in nextjs?如何在 nextjs 中检查每个请求的 cookie?
【发布时间】:2021-02-01 19:12:30
【问题描述】:

我有一个 nextjs 应用程序,我想检查每个请求以查看其 cookie 中是否保存了 JWT。如果没有,我想向他们展示一个登录表单。如果他们确实有,则照常进行。

我想不出我会在哪里或如何做到这一点。

我会在pages/_app.js 中这样做吗?有没有某种中间件……的东西?

希望我已经解释了我想要完成的工作,并且有人可以指导我在哪里或如何做到这一点。

【问题讨论】:

    标签: next.js


    【解决方案1】:

    如果每个页面都需要令牌,您应该在 _app.js 中进行。 否则,您需要在需要授权的每个页面上执行此操作。

    您可以使用 next-cookies 库来获取服务器端的 cookie npm i next-cookies

    您的获取 ServerSideProps 函数应如下所示:

    export const getServerSideProps = async (ctx) => {
      try {
        const cookies = cookies(ctx);
        const { token } = cookies;
    
        // fetch data here with the token...
    
    
        return {
          props: { token },
        };
    } catch (err) {
        // either the `token` cookie didn't exist
        // either way: redirect to the login page
        console.log(err);
        ctx.res.writeHead(302, { Location: "/login" });
        ctx.res.end();
    
        return { props: {} };
      }
    };
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    相关资源
    最近更新 更多