Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookies handling using javascript or Express.js or node.js?

I just want to know which one is the best way to handle the cookies? Using Express.js? Node.js or client side javascript jquery?

I am little confuse with security perspective.

Thanks for all your help/information.

like image 467
Ali Hassan Avatar asked Mar 24 '26 09:03

Ali Hassan


2 Answers

Cookies are HTTP concepts which is irrespective of the language / platform. So, Node.js is a server side platform while Express.js is a server side web application framework for Node.js and jQuery is a client side library.

From security perspective, you should not store cookie information in plain text. Also, "you shouldn't allow client side scripts to set or read the cookie value". If you are already using Express.js, then I would recommend setting & reading of cookies to be taken care by your application using Express.js and ensure you encrypt the cookie values.

like image 190
Ramesh Avatar answered Mar 26 '26 21:03

Ramesh


You should keep some session id in cookie, not actual data (it's true for most cases, especially for any user-related sensitive data).

The correct approach for using cookies would be:

  1. Make user input his login/password and check "keep logged in" checkbox.
  2. On server side, based on inputed login and password, decide if user credentials are valid.
  3. Assuming valid credentials, create some random id and store information on server side, that this given random id is related to some data (some user id, settings etc.).
  4. On server side, based on value of "keep me logged in" checkbox you would then do following: if checkbox was checked, create cookie that should expire in some time in very distant future (like, say, 100 years). If checkbox wasn't checked, you set cookie to expire once browser session is over or for example in 1 hour. Keep in mind, that user can tampre with expiration date of cookies once you send them, but that's a whole different story.
  5. User (client) is receiving your cookie which has that generated id in it. That cookie is sent to you by browser on every request.
  6. On server side, once you get your cookie from client, check if you know that id and if it is valid. If so - retreive user data from your databse or whatver and operate on those.
like image 24
WTK Avatar answered Mar 26 '26 22:03

WTK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!