DEV Community

[Comment from a deleted post]
Collapse
 
tom profile image
tom • Edited

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!

Collapse
 
johndoesup profile image
abhishek

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