[英]Remove Cookies and Sign out server-side in Next.js
I need to check if there's a token and if the token expired in getInitialProps, and then if the token is expired clear the Cookies from the browser and sign out the user.我需要检查是否有令牌以及令牌是否在 getInitialProps 中过期,然后如果令牌过期,请从浏览器中清除 Cookies 并注销用户。
Here's what I'm doing so far...这是我到目前为止正在做的事情......
const isTokenExpired = (token) => {
const currentTime = new Date().getTime() / 1000;
const decodedToken: MetadataObj = jwt_decode(token);
if (decodedToken.exp < currentTime) {
return true;
} else {
return false;
}
};
import nextCookie from "next-cookies";
import Cookies from "js-cookie";
MyApp.getInitialProps = async ({ctx}: any) => {
const { WebsiteToken } = nextCookie(ctx);
if (WebsiteToken ) {
if (isTokenExpired(WebsiteToken )) {
console.log("Token Expired");
Cookies.remove("WebsiteToken ");
}
}
}
The console log works, but the Cookie is not removed from the browser, I know that this is because it didn't hit the client-side, but how can I do that from the server?控制台日志有效,但 Cookie 没有从浏览器中删除,我知道这是因为它没有命中客户端,但我怎样才能从服务器上做到这一点?
You can erase cookies by setting the header:您可以通过设置 header 来擦除 cookies:
ctx.res.setHeader(
"Set-Cookie", [
`WebsiteToken=deleted; Max-Age=0`,
`AnotherCookieName=deleted; Max-Age=0`]
);
It will set the cookie value to be "deleted" but that is not important because Max-Age=0
means that cookie will expire immediately and browser will delete it.它会将 cookie 值设置为“已删除”,但这并不重要,因为
Max-Age=0
意味着 cookie 将立即过期,浏览器将删除它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.