session and cookies. What are those?

abisekhsubedi profile image अभिषेक सुबेदी ・1 min read

Can anyone tell me the difference between session and cookies? Where are they needed? why are they used? How as a javascript beginner, that's me can use it?


Editor guide
alephnaught2tog profile image
M. Shemayev
  • Why we care: the Web is stateless. If I go into the console right now and do document.getElementById("page-content").style.backgroundColor = "orchid";, the background turns orchid! If you refresh the page, that disappears. Which I won't do, because if I do, I'll lose this content, too. Noticeably, most sites have log-ins or a means of "remembering" information: that data has to persist somewhere. For complex things like user logins, the site is (probably(3)) using a database to store that info somewhere; but not everything needs, or has access to, a database. Cookies and session variables and things like sessionStorage and localStorage allow you to persist data for a site--so that if I say I want the background here to ALWAYS be orchid, that's fine, but that data needs to get saved somewhere and then fetched for use.

Imagine playing a game: if every time you stopped playing the game and then came back later, it'd be no fun if you had to start over every single time, right? You'd have to go back to Level 1 every time you opened the game and you couldn't finish--unless the game was short or you played without interruption for a very long time.

Being able to persist data and information is massively awesome and a legit game-changer. (I feel like, along with IO, it's one of those tiers where when you learn how to do it in a given language a million new doors and rabbitholes open up because of how exponentially what you can do increases.)

sessionStorage and localStorage are really pretty friendly in Javascript. I havne't done huge amounts with them, but it's key-value pairs.

  • Session = until you close that tab(1). In Javascript(2), you can add items to sessionStorage by using the setItem method and a key-value pair:
// add an item to it
sessionStorage.setItem("firstSessionKey", "firstSessionValue");

// to retrieve that item
const bucketForValue = sessionStorage.getItem("firstSessionKey");
  • Cookies I admit I'm not familiar with from the Javascript end, but as I've learned in PHP (and I am assuming cookies are cookies in this case, even if implementation differs, someone please correct me!) cookies are a means of storing that info but on the user's computer. Hence the ability to clear cookies etc. in most (all? I hope?) browsers. You can find them on your computer itself. (Also why they are a security risk!) Cookie implementation in Javascript I will leave to W3: w3schools.com/js/js_cookies.asp

(1) Closing the tab and opening that page again in another tab ends the session; if you close the tab and reopen it, so say you close it then on FF you ctrl-shift-T and reopen it, the session is restored.

(2) Sessions in PHP, at least, are different if similar. In PHP, the data is stored on the server--there is a dichotomy-ish between cookies and sessions in that regard, storing client-side vs. server-side. Assuming no database is involved, my understanding of sessions in Javascript is that they are also client-side stored because, well, Javascript. (And assuming no AJAX, etc.)

(3) I hesitate to ever use absolutes :P

alephnaught2tog profile image
M. Shemayev

Quick sloppy demo (HTML etc included for demo purposes)

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Session Demo</title>
        When this page first loads, the first time you open it before clicking
        any buttons--the background is white.
        When you click red or green, then refresh the page, the color changes
        to that. If you close the tab entirely and open a new
        tab and open the url again--white again.
        If you hit the yellow button and refresh, it's yellow. If you close
        the tab like before, do a new one, open the page again--yellow!
    <p>If you do yellow then green or red, and refresh, green or red
       wins--until you close that tab and reopen it, even close the browser
       and reopen it, and then it will be yellow... because you picked
    <button onclick="pickRed()"
            style="background-color: red; color: white;">Red!
    <button onclick="pickGreen()"
            style="background-color: green; color: white;">Green!
    <button onclick="setLocalStorageToYellow()"
            style="background-color: yellow;">Set localstorage to yellow
        if (sessionStorage.getItem("chosenBackgroundColor") !== null)
            document.body.style.backgroundColor =
        else if (localStorage.getItem("localBackgroundColor") !== null)
            document.body.style.backgroundColor =

        // functions!
        function pickRed()
            sessionStorage.setItem("chosenBackgroundColor", "red");

        function pickGreen()
            sessionStorage.setItem("chosenBackgroundColor", "green");

        function setLocalStorageToYellow()
            localStorage.setItem("localBackgroundColor", "yellow");
abisekhsubedi profile image
अभिषेक सुबेदी Author

😻 thanks, M. Shemayev for your wonderful explanation.

tom profile image

I'm guessing that rather than asking about session storage , you're asking about associating data with a particular visitor to a website.

If so, a session could be loosely defined as a temporary interaction between two (or more) devices. They are often stateful, and will almost certainly be stateful in the case of a visitor to a website.

Examples include login (eg. authentication tokens), shopping cart data, or partially-complete form state.

In particular, you might say a logged-in user has a session with the site they are logged-in-to.

Cookies are one possible way to build this kind of stateful session.

For example, the session library for express uses a cookie to store a "session ID" that associates a user with data saved on the server-side.

Cookies are (small) amounts of information, saved in a user's browser, associated with a particular origin.

A web browser transfers cookies with any HTTP requests made to an origin server in the Cookie request header.

Cookies are set either:

  • by the server, using the Set-Cookie response header
  • by JavaScript, using document.cookie API

JavaScript can also read cookies using the same API.

That means you can build sessions using cookies.

So to answer your questions directly:

Can anyone tell me the difference between session and cookies?

Answered above, hopefully!

Where are they needed? why are they used?

Amongst other things, they are useful anytime you want your (otherwise stateless) servers to "remember" something about a visitor between requests.

Largely, cookies live in HTTP headers.

How as a javascript beginner, that's me, can use it?

Choose any site and pop open your developer console and try document.cookie. See what's in there!

abisekhsubedi profile image
अभिषेक सुबेदी Author

Tom. Thank you, you're such an explainer.thanks again for clearing my confusion on session & cookies ❤

ethanarrowood profile image
Ethan Arrowood

So for session storage you have two options, localStorage and sessionStorage:

"sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends" - MDN

More info can be found here

Both of these are client side only.

Cookies on the other hand are predominantly used for server-side data recording. StackOverflow

The biggest difference is that cookies are sent via the HTTP protocol where localStorage just writes to the Window Storage API implemented by several browsers such as Chrome and Firefox.