Search code examples
node.jsmongodbexpresscookiescors

Third-party cookie will be blocked - warning, not able to logout


I want to remove the warning and be able to logout

https://link-bee-roan.vercel.app/ this is the link

I am setting cookies here

 res.cookie('token', token, {
        secure: true, 
        sameSite: 'none', 
    });

My cors

app.use(cors({
    origin: "https://link-bee-roan.vercel.app",
    credentials: true
}));

In the frontEnd

axios.defaults.withCredentials = true;
.
.
.
let response = await axios.post("https://linkbee-2.onrender.com/login", {
      // let response = await axios.post("http://localhost:3000/login", {
        userID, password
   },{ 
   withCredentials: true,
});

I am getting the third party cookie error in the console,

However I am able to see the cookie, but when I click the logout button, the cookie is not getting deleted,

This is the logout backend code,

router.post('/logout', (req, res) => {
    console.log("this is the cookie :: " ,  req.cookies.token);
    res.clearCookie('token').send(req.cookies.token);
});

This is the related function in the front end

const handleLogout = async (e) => {
        try {
            let response = await axios.post(`${backendLink}/user/logout`);
            console.log("this is the respose :: " , response);
            // window.location.href = "/";
        }
        catch (error) {
            console.log("error :: ", error);
        }
    }

Getting the cookie, but the cookie is not getting deleted even after the logout code above;

enter image description here


Solution

  • From the documentation:

    Web browsers and other compliant clients will only clear the cookie if the given options is identical to those given to res.cookie(), excluding expires and maxAge.

    Having

     res.cookie('token', token, {
            secure: true, 
            sameSite: 'none', 
        });
    

    to set cookies, you should have

      res.clearCookie('token', {
            secure: true, 
            sameSite: 'none', 
        }).send();
    

    to mirror the options.

    Saying that, cookies are stored on the client, and in your particular case (no serverside logic in router.post('/logout' handler, the cookie is not "http only", no other cookies) you can delete it (and effectively logout) straight in the browser, saving on the HTTP request:

    document.cookie = 'token; Max-Age=0 path=/; domain=...etc'