Understanding how Cookie and Session works in JavaScript ( Node.js )

With actual Code Examples to help demonstrate their use

GP Lee
GP Lee
Mar 18, 2020 · 7 min read
Photo by Alvan Nee on Unsplash

ROADMAP

Photo by Jaromír Kavan on Unsplash

Why does the web application have to have a login functionality ?

THE 2nd QUESTION

What the heck is Cookie ?

THE 3rd QUESTION

How does Cookie tell “who made a request” ?

THE 4th QUESTION

What is the difference between Cookie and Session authentication ?

THE 5th QUESTION

What is Session ?

Photo by Ben White on Unsplash

The need for LogIn , LogOut functionality for web application

  • Login, Logout Authentication is one of the most difficult features to implement for web developers
  • But, they are also the very necessary features to have for making a reliable web application
  • It does not know who made the request
  • Of course, we have IP address and browser information
  • But, it’s possible that many computers share the same IP address or a computer is used by different users
  • Thus, we need to implement Login Functionality to tell the server who made a request and Cookie & Session authentication is one of the ways to tell the server “who made a request”

The need for Cookie

  • If the website does not log you out for refreshing the page, the website implements cookie and session
  • Every websites you visit has cookie and session implemented
  • The client is able to sending information about you and your authenticated status etc… to the server by using cookie
  • Cookie is a simple key-value pair
name=gplee
  • Web browser saves the cookie internally and sends to the server whenever the client wants to request to the server
  • In other words, cookie keeps tracking of you and your information
  • That’s why you are recommended to erase the cookie periodically to prevent the personal information leakage
  • Cookie is delivered in the request and response header

Let’s implement a code to make a cookie and send to the browser

Code available from https://github.com/gpDA/cookieSession

Let’s run the code
Open VS Code and run typing `node server3` in terminal
You will see `listening on port 8082`

ParseCookies function

  • we made a parseCookies function, which converts string to object
  • Cookie is as string type such as name=gplee;year=1993 and we need to convert this to object type such as { name : 'gplee', year: '1993'}

createServer method

  • In the first createServer method callback, we are analyzing the cookie
  • Cookie is located inside of req.headers.cookie
  • We use res.writeHead method to send cookie to response header
  • In res.writeHead, the first parameter is 200 status code, which means the success and the second parameter is header information (i.e., Set-Cookie asks the browser to save the cookie)
  • Then, the browser saves mycookie=test

Let’s see the cookie in the browser

  • If you run it, you will see such informations in the terminal

In the terminal, you have following items

csrftoken

  • Cross-site request forgery (CSRF) token is a random , hard-to-guess string which tells the browser that it’s user’s intention to send the request
  • User Intention???? More information about CSRF token available in the following Link ==> https://cloudunder.io/blog/csrf-token

favion.ico

  • Browser asks information about favicon, if it does not get the information from HTML

mycookie

  • The server asks (orders) browser to send cookie called mycookie=test
  • General is the common header
  • Request Headers is the header from the requester
  • Response Headers is the header from response
  • They are many Headers, but we only need to focus on Set-Cookie from Response Headers & Cookie from Request Headers
  • Set-Cookie from Response Header asks (orders) the browser to save the cookie
  • After the browser setting Cookie in Request Headers, the browser is able send Cookie in the request next time
  • We also can see the string Hello Cookie which we sent from res.end (in the code above)
  • Last but not least, we can see only Cookies in NetworkCookies tab
  • Cookies tab is very useful for debugging purpose

HTTP Header and HTTP Body (Briefly)

  • Request and Response is comprised of HTTP Header and HTTP Body
  • HTTP Header has an information about request or response
  • HTTP Response has a real data that needs to be exchanged between the server and the client
  • Cookie is an extra information; thus, cookie is saved in HTTP Header

Cookie as a requester identifier

In the previous example, we sent the cookie but the cookie does not identify who send the cookie. But this time, we will send a user information (user name) as a cookie

Code available from https://github.com/gpDA/cookieSession

server4.html
server4.js

Code Analysis Line by line

There are two cases 1) URL comes from /login 2) URL comes from /

If the URL starts with /login ( req.url.startsWith('/login') ) ,

(line 19–20) we analyze url and query-string qs.parse(query)

(line 22) Then, we set cookie that expires in 1 minute

(You can see that it actually expires after a minute by refreshing the page after a minute. The page will be redirected to the login HTML page)

(line 23–28) We write head writeHead with 302 response code , redirect Location and setting cookie in the header

If the URL starts with / ( else if , else CASE)

  • We first check whether there’s a cookie or not → cookies.name
  • If there is no cookie, redirect to login html
  • If cookie exists, we show → Welcome {name}

Cookie Options

In the code above, we set Expires , HttpOnly, Path options

  • Cookies are able to have some options as long as separated by semicolon ;

Options Example

  • cookiename=cookievalue : basic cookie name and value
  • Expires=date : Expiration Date for cookie ; Default expiration date is until expiration of client (web browser)
  • Max-age=seconds : Similar to Expires but in seconds ; Have a priority over Expires
  • Domain=DomainName : We can specify domain which the cookie is sent ; Default is the current domain
  • Path=URL : We can specify URL ; Default URL is '/' and can send to every URL by default
  • Secure : available to send cookie only for HTTPS
  • HttpOnly : block access from JavaScript to cookie ; It prevents cookie manipulation

Let’s see the example from the browser

  • It works as expected
  • But, using cookie is vulnerable to security threats because cookie is exposed in Browser’s Application tab
  • Thus, it is not proper to save sensitive personal information to cookie

Use of Session instead of Cookie

Let server manages the user information

Code available from https://github.com/gpDA/cookieSession

server5.js

The slight differences from the previous example (server4.js)

  • Instead of sending user name (user information) along with cookie, we send randomInt (random number) and we set name and expired time in session object const session = {}
  • If cookie.session does not exceed the expiration date, we get the user information from session variable

What is Session

  • In Session based Authentication, user information is saved on the server and the client and the server communicates only via session id
  • There are many different ways to implement session id but many web sites use cookie for its simplicity for implementation
  • For the deployment server, we do not set the session as a variable const session = {} because memory can be cleared if the server stops or restarts. So session is often saved in the database

Conclusion

  • In real life, we do not maintain the session as a variable nor make session from the scratch
  • We often use a third party modules such as express-session and cookie-parser
  • It’s much safer to use the third party modules which are proved and edited by many developers
  • This article focuses on understanding cookie-based & session-based authentication with codes from the scratch.
  • Next time, I will dive deep into session-based authentication vs. Token based authentication (TL DR; token-based authentication saves the user’s state on the client whereas session-based authentication store user’s state on the server)

Thank you

Photo by Anthony DELANOIX on Unsplash

Web Developers Tomorrow

Programming Advices, Development Tips, Web Development

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store