我将如何检查 nextjs 中每个请求的 cookie? [英] How would I check for a cookie on every request in nextjs?
问题描述
我有一个 nextjs 应用程序,我想检查每个请求,看看他们的 cookie 中是否保存了 JWT.如果没有,我想向他们展示一个登录表单.如果他们确实有,那么照常进行.
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.
我会在 pages/_app.js
中执行此操作吗?有没有某种中间件......东西?
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.
推荐答案
如果每个页面都需要令牌,您应该在 _app.js 中进行.否则你需要在每个需要授权的页面上进行.
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.
您可以使用 next-cookies 库来获取服务器端的 cookie npm i next-cookies
you can use the next-cookies library to get the cookies serverside npm i next-cookies
您的 get ServerSideProps 函数应如下所示:
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: {} };
}
};
这篇关于我将如何检查 nextjs 中每个请求的 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!