How would I check for a cookie on every request in nextjs?

谁都会走 提交于 2021-01-29 11:11:10

问题


I have a nextjs app and I want to check every request to see if there is a JWT saved in their cookies. If not, I want to show them a login form. If they do have one, then proceed as normal.

I can't think of where or how I would do this.

Would I do this in pages/_app.js? Is there some kind of middleware... thing?

Hopefully I've explained what I want to accomplish, and someone can guide me to where or how I would do this.


回答1:


If every page needs the token you should do it in the _app.js. Otherwise you need to do it on every page which needs authorization.

you can use the next-cookies library to get the cookies serverside npm i next-cookies

Your get ServerSideProps function should look like this:

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: {} };
  }
};


来源:https://stackoverflow.com/questions/64420067/how-would-i-check-for-a-cookie-on-every-request-in-nextjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!