简体   繁体   中英

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.

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?

You can erase cookies by setting the header:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM