1.

How to delete cookies in Express.js?

Answer»

There are many situations in which we WANT to delete COOKIES from the CLIENT browser. There can be situations, where we are told to delete cookies once the user logs out from the applications. We will look into an example to understand the same.

First create a project directory and go to it. After that initialize a node project by giving the command NPM init -y from the terminal.  We also need to install express and cookie parser in the project.

Now, create a file server.js and add the below content in it. Here, we have a root route which stores the user information in a cookie named login info. Now, we have a /logout route and when the user navigates to it, the cookie login info is cleared, through the res.clear cookie function. We are passing the name of the cookie to be cleared, which is login info.  

Now, we will go to http://localhost:3000/ and we will see the message Cookie Saved Successfully. Now in the developer tools open Storage and then expand Cookies and we will see the cookie being saved.

Next, go to the route http://localhost:3000/logout and you will see the message Cookie loginInfo cleared and also in the Storage TAB, there is no cookie information.  



Discussion

No Comment Found