Home > Software engineering >  res.clearCookie is not clearing cookies despite matching options
res.clearCookie is not clearing cookies despite matching options

Time:11-21

I apologize if there are errors in my code or anything like that, I have been searching for a solution, and have not found anything.

I am trying to use a /logout route to clear a cookie with res.clearCookie(). My understanding is that in order for the cookie to be cleared, all the options passed to res.clearCookie must match the options passed to res.cookie, when the cookie was originally created. I have tried including the domain (5.161.134.120) as well, but nothing seems to work, the cookie still persists.

Cookies work fine throughout the rest of the site for accessing specific pages, it appears to be just deleting them that is causing the issue. Deleting cookies worked fine locally, it's only after deploying to a server.

Initializing the cookie:

router.get("/callback", async function (req, res, next) {

    try {
        let tokenData = await SpotifyClientService.getSpotifyToken(req.query.code);
        let sessionId = await SpotifyClientService.validateUserAndGetSessionId(tokenData);
        res.cookie("sessionId", sessionId, {
            path: '/',
            httpOnly: true
                });

        res.redirect(HOME_REDIRECT);

    } catch (err) {
        console.log(err);
        return next(err);
    }
})

Logout route

router.post("/logout", async function (req, res, next) {

    try {
    
        res.clearCookie('sessionId', {
            path: '/',
            httpOnly: true
});
    res.end();
    }

    catch (err) {
        return next(err);
    }
})

My backend's app.js, with cors:

const express = require("express");
const morgan = require("morgan");
const cors = require("cors");
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
const reviewsRoutes = require("./routes/reviews");
const userRoutes = require("./routes/users");
const albumRoutes = require("./routes/albums");
const authRoutes = require("./routes/auth.js")
const app = express();
app.use(cookieParser());
app.use(bodyParser.json())

app.use(morgan("tiny"));
app.use(express.json());
app.use(cors({origin:"http://5.161.134.120:3000", credentials:true}));
app.use("/reviews", reviewsRoutes);
app.use("/users", userRoutes);
app.use("/albums", albumRoutes);
app.use("/auth", authRoutes.router);


// 404 Not Found handler * //

app.use(function (req, res, next) {
    const err = new Error("Not Found");
    err.status = 404;
    next(err);
});

// Generic error handler. *//

app.use(function (err, req, res, next) {

    res.status(err.status || 500).json({
        message: err.message
    });

});

module.exports = app;

Lastly, the function from the React component that is calling the logout route:

 async function doLogout() {

    let result = await axios.post(`${BASE_URL}/auth/logout`,{ withCredentials: true});
    dispatch({
      type: "LOGOUT-CURR-USER"
    })
    navigate("/");
  }

I did search pretty extensively and I apologize if I missed this issue being fixed. Thank you for reading.

Attempted to use the res.clearCookie function with options identical to res.Cookie, to clear a cookie.

CodePudding user response:

I had the similar problem where i realized after a long and annoying time that my front end was not sending the cookie to the end point were I was trying to clear the cookie...

On the server:

function logout(req, res) {
  res.clearCookie('cooky');
  return res.sendStatus(200);
}

And on the front end,

fetch('/logout', { method: 'POST', credentials: 'same-origin' })

adding the "credentials: 'same-origin'" is what made the clearCookie work for me. If the cookie is not being sent, it has nothing to clear.

I hope this helps.

CodePudding user response:

Update - Ali Iqbal pointed me in the right direction that this was an issue of cookies not being sent properly in the front end. Despite withCredentials being set to true, the cookies indeed were not being sent. This line fixed the issue, allowing the cookies to be sent to the backend and deleted to complete the logout:

axios.defaults.withCredentials = true;

  • Related