问题
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