express js clear cookie

If you are working with cookies in your Express.js application, you may need to clear a cookie at some point. Here's how you can do it:

Method 1: Using the response object

The simplest way to clear a cookie is to set its value to an empty string and set the expiration date to a past date. You can do this using the response object's clearCookie method:


  res.clearCookie('cookieName');
  

This will clear the cookie named "cookieName".

If you are using the cookie-parser middleware in your Express.js application, you can also clear a cookie using the clearCookie method on the request object:


  req.clearCookie('cookieName');
  

This will also clear the cookie named "cookieName".

Method 3: Using the response object with options

You can also clear a cookie by setting its value to an empty string and setting the expiration date to a past date, like in Method 1, but you can also pass in options as a third argument:


  res.cookie('cookieName', '', {expires: new Date(0)});
  

This will set the cookie named "cookieName" to an empty string and set the expiration date to a past date. The options object can also include other properties like the domain, path, and secure flag.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe