4

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?

Ruby
  • 2,207
  • 12
  • 42
  • 71

2 Answers2

10

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.

Luka
  • 156
  • 1
  • 5
0

For my case, for NextJS 12.3.1 I did the following way

import type { NextResponse } from 'next/server'

export async function deleteCookie(res: NextResponse) {
    res.cookies.set('cookie_name', '', {
    httpOnly: true,
    maxAge: 0, // 0 second hours in seconds
  })
  return res
}