Kenny
Kenny

Reputation: 4572

Can't delete cookie in express

Pretty simple. I set a cookie like so in my /user/login route:

if (rememberMe) {
    console.log('Login will remembered.');
    res.cookie('user', userObj, { signed: true, httpOnly: true, path: '/' });
}
else {
    console.log('Login will NOT be remembered.');
}

I've already set my secret for cookie-parser:

app.use(cookieParser('shhh!'));

Pretty basic stuff. Everything is working great insofar as I'm able to retrieve whatever I stored in the cookie:

app.use(function (req, res, next) {
    if (req.signedCookies.user) {
        console.log('Cookie exists!');
        req.session.user = req.signedCookies.user;
    }
    else {
        console.log('No cookie found.');
    }

    next();
});

This middleware is called before anything else, so for the sake of the argument "Cookie exists!" is always logged in my console if the cookie is valid.

The problem is when I try to delete the cookie. I've tried res.clearCookie('user'), res.cookie('user', '', { expires: new Date() }), and I've tried passing in the same flags (that I pass to res.cookie() in /user/login). I've attempted to use combinations of these methods, but nothing has worked.

Currently, the only way I am able to clear the cookie (and not receive the "Cookie exists!" log message) is by clearing my browser history. Here is what my logout route looks like:

route.get('/user/logout', function (req, res, next) {
    res.clearCookie('user');
    req.session.destroy();
    util.response.ok(res, 'Successfully logged out.');
});

It seems as though I can't even modify the cookie value; I put

res.cookie('user', {}, { signed: true, httpOnly: true, path: '/' })

in my logout route, but the cookie value remains unchanged.

Upvotes: 26

Views: 30147

Answers (10)

Hithesh Jay
Hithesh Jay

Reputation: 31

If you omit the empty object {} and only send

axios.post('http://localhost:4000/logout', {withCredentials:true})

the {withCredentials:true} part will be treated as the data to be sent in the body of the POST request, not as the configuration object.

So remember to send as this,

axios.post('http://localhost:4000/logout', {}, {withCredentials:true})

This worked for me.

Upvotes: 0

Abdullah Mehboob
Abdullah Mehboob

Reputation: 1

In my case I was using a variable as reusable variable which looked like this

const refreshTokenOptions = {
  httpOnly: true,
  secure: true,
  maxAge: 604800000, // (1 week)
};

// in api endpoint
res.cookie('refreshToken', refreshToken, refreshTokenOptions);

in logout endpoint. I was passing the same variable like this. And this wasn't working.

  res.clearCookie('refreshToken', refreshTokenOptions);

After setting it like this, it Worked.

  res.clearCookie('refreshToken', { httpOnly: true, secure: true });

I think it's related to maxAge. While clearing cookie we have to remove maxAge.

Upvotes: 0

P.R. D
P.R. D

Reputation: 1

I am new to this but adding a return (return res.sendStatus(204);)to Backend function is what deleted the cookie for me, hope it helps. without return it does not delete the cookie but only logs "session over"

 app.post("/logout", (req, res) => {
  if (req.session.user && req.cookies.user_sid) {
    res.clearCookie("user_sid");
    console.log("session over");
    return res.sendStatus(204);
  } else {
    console.log("error");
  }
});

Upvotes: 0

user1503606
user1503606

Reputation: 4290

Had a nightmare getting this to work as well this works for me hopefully helps someone.

Express router

router.post('/logout', (req, res) => {
    res.clearCookie('github-token', {
        domain: 'www.example.com',
        path: '/'
    });
    return res.status(200).json({
        status: 'success',
        message: 'Logged out...'
    });
});

React frontend handle logout.

const handleLogout = async () => {
    const logout = await fetch('/logout', {
        method: 'POST',
        credentials: 'include',
    });
    if (logout.status === 200) {
        localStorage.clear();
        alert('Logged out');
    } else {
        alert('Error logging out');
    }
};

I am setting the cookie in my auth call like this.

res.cookie('github-token', token, {
    httpOnly: true,
    domain: 'www.example.com',
    secure: true
});

Important you need to add the path and domain in the clearCookie method.

Upvotes: 2

Bersan
Bersan

Reputation: 3461

Nov 2022 (Chrome) - What worked for me

Frontend:

const logOut = async () =>{
  await axios.post(LOGOUT_URL, {}, {withCredentials: true}) // <-- POST METHOD, WITH CREDENTIALS IN BODY
}

Backend:

res.clearCookie('jwt') // <- NO EXTRA OPTIONS NEEDED, EVEN THOUGH HTTPONLY WAS SET
return res.sendStatus(204)

Upvotes: 1

Milan Velebit
Milan Velebit

Reputation: 2027

Judging by (an extensive) search and a random thought that popped into my head, the answer is to use

res.clearCookie('<token_name>',{path:'/',domain:'<your domain name which is set in the cookie>'});

i.e.

    res.clearCookie('_random_cookie_name',{path:'/',domain:'.awesomedomain.co'}); 

Note the . which is specified in the cookie, because we use it for subdomains (you can use it for subdomains without the dot too, but it's simply safer to use one).

TLDR; You have to provide a route and domain: in the backend, so that the request is made to the same endpoint in the frontend.

Upvotes: 6

kenodek
kenodek

Reputation: 372

Path needs to be correct. In my case it was a typo in path

Upvotes: 0

Noob
Noob

Reputation: 2807

Even though it's not gonna help the author of this question, i hope this might help someone. I run into the same problem that i could not delete cookies in my React app that was using Express api. I used axios, and after a couple of hours i was finally able to fix it.

await axios.post('http://localhost:4000/api/logout', { } , { withCredentials: true })

{ withCredentials: true } is what made it work for me.

This is my Express code:

 const logOutUser = (req, res) => {
  res.clearCookie('username')
  res.clearCookie('logedIn')
  res.status(200).json('User Logged out')
}

Upvotes: 20

joshuakcockrell
joshuakcockrell

Reputation: 6113

Make sure you are sending your credentials to be cleared

Even though it's only a /logout endpoint, you still need to send credentials.

// FRONT END
let logOut = () => {

  fetch('logout', {
    method: 'get',
    credentials: 'include', // <--- YOU NEED THIS LINE
    redirect: "follow"
  }).then(res => {
    console.log(res);
  }).catch(err => {
    console.log(err);
  });

}


// BACK END
app.get('/logout', (req, res) => {
  res.clearCookie('token');
  return res.status(200).redirect('/login');
});

Upvotes: 4

Kevin
Kevin

Reputation: 575

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('mlcl');
  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. I wish I had found this earlier...

Upvotes: 23

Related Questions