1.

How to make the cookie more secure for the client through Express JS?

Answer»

It is very important to make the cookie secure or else it can be misused for cross-scripting attacks. For example, you can access the cookie which is stored in the browser by using the document.cookie command from the console.

There are several attributes available, while setting the cookie which generally make it more secure. Let's take a look at them with an example.  

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.  

After that we will install express and cookie-parser in the project.  

Now, create a server.js file in the same directory and add the below code in it. We are using res.cookie() here to send the cookie information to the client. But notice that we are also sending a third parameter which contains some parameters. Now, these means the following: 

  • maxAge - It is the number of SECONDS after which the cookie will expire. 
  • Expires - Similar to maxAge, but we can give the Date on which the cookie will expire. 
  • secure - It means the browser will not accept cookies until it comes through a https connection. 
  • httpOnly - The most important parameter, which ensures that the cookie cannot be accessed through JavaScript. It is the main THING which prevents cross-origin attack. 
  • sameSite - It improves the security by stopping third PARTIES from tracking users across sites. This is done, if it is set to lax. 

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




Discussion

No Comment Found