简体   繁体   English

删除 Cookies 并在 Next.js 中注销服务器端

[英]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.

相关问题 服务器端渲染不适用于生产 Next.js - Server-side rendering not working on production Next.js 是否可以在 Next.js 中设置服务器端 cookie - Is it possible to set a server-side cookie in Next.js Next.JS:如何在服务器端发出所有请求 - Next.JS: How to make ALL requests server-side 是否可以在 Next.js 中使用国际化重定向服务器端? - Is it possible to redirect server-side with internationalization in Next.js? Next.js 中的动态路由是呈现在服务器端还是客户端? - Are dynamic routes in Next.js rendered server-side or client-side? Next.js:服务端渲染页面请求高时无响应(动态路由) - Next.js : no response when request goes high in server-side rendering page(dynamic routing) 在服务器端设置初始道具时,Next.js挂起 - Next.js hangs while setting initial props on server-side 在 Next.js 和/或其他形式的 React 服务器端渲染中延迟加载图像 - Lazy Loading Images in Next.js and/or in other forms of React server-side rendering 无法在服务器端 Next.js 上导入 React 组件 - Can't import React component on server-side Next.js Next.js 10 + 子路由,如何在服务器端的自定义应用程序中访问语言环境 - Next.js 10 + sub-routing, how to access locale in custom app on server-side
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM