The Startup
Published in

The Startup

Working With Cookies and Creating Cookies in JavaScript

Cookies

Cookies are small data strings, stored directly in the browser. They are included in the HTTP protocol.

As a rule, the web-server sets cookies with the help of a response Set-Cookie HTTP header. After that, the browser adds them to each request to the same domain, using the Cookie HTTP header.
Cookies are used in many cases to store information and sensitive-data, the most common being authentication
During the sign-in, the server applies the Set-Cookie HTTP header in the response for setting a cookie with a specific “session identifier”.

  1. The next time if the request is set to the same domain, the cookie is sent over the net by the browser, with the help of the Cookie HTTP header.
  2. In that way, the servers know who the request was made by.

Also, you can use the document.cookie property for accessing cookies from the browser.

The 2 domains mydomain.com and subdomain.mydomain.com can only share cookies if the domain is explicitly named in the Set-Cookie header. Otherwise, the scope of the cookie is restricted to the request host. (This is referred to as a "host-only cookie".

Host-Only Cookie

If Domain is not specified, the cookie can only be read by the exact domain that has set the cookie. This can be loosened by setting the Domain attribute when setting a cookie.

For example, if the cookie is set by www.example.com and the Domain attribute is not specified, the cookie will be set with domain www.example.com and the cookie will be a host-only cookie.

Another example: If the cookie is set by www.example.com and the Domain attribute is specified as example.com (so the cookie will be sent to foo.example.com too), the cookie will be set with domain example.com (or possibly .example.com by some browsers that use the dot from the previous RFC 2109 to denote not host-only) and the cookie will not be a host-only cookie.

In simple words, Host-Only cookie means that the cookie should be handled by the browser to the server only to the same host/server that firstly sent it to the browser.
You don’t want to send this host only cookie for ad campaigns, as it might contain sensitive information.

For instance, if you sent the following header from subdomain.mydomain.com, then the cookie won't be sent for requests to mydomain.com:

Set-Cookie: name=value

However, if you use the following, it will be usable on both domains:

Set-Cookie: name=value; domain=mydomain.com

This cookie will be sent for any subdomain of mydomain.com, including nested subdomains like subsub.subdomain.mydomain.com.

In RFC 2109, a domain without a leading dot meant that it could not be used on subdomains, and only a leading dot (.mydomain.com) would allow it to be used across multiple subdomains (but not the top-level domain, so what you ask was not possible in the older spec).
However, all modern browsers respect the newer specification RFC 6265 and will ignore any leading dot, meaning you can use the cookie on subdomains as well as the top-level domain.

In summary, if you set a cookie like the second example above from mydomain.com, it would be accessible by subdomain.mydomain.com, and vice versa. This can also be used to allow sub1.mydomain.com and sub2.mydomain.com to share cookies.

See also:

Web sites often have a www. sub-domain that points to the same content as the main domain. With session cookies our visitor has either accessed our site with the www. or they have accessed it without and so the fact that a cookie created for www.example.com is not accessible from example.com isn’t going to matter. With first-party cookies, a visitor may very easily access our site the first time as www.example.com and the second time as example.com and so we want to create a cookie that will be accessible from both.

Creating a Domain Level Cookie in Javascript

To make a cookie accessible from the entire domain including any sub-domains we just add a domain parameter when setting the cookie as demonstrated in this JavaScript example. You should, of course, substitute your own domain name for example.com (as example.com is a domain name specifically reserved for use in examples where it represents whatever domain name you are really using.)

writeCookie = function(cname, cvalue, days) {
var dt, expires;
dt = new Date();
dt.setTime(dt.getTime()+(days*24*60*60*1000));
expires = "; expires="+dt.toGMTString();
document.cookie = cname+"="+cvalue+expires+'; domain=example.com'

It involves setting the domain attribute of the cookie string like:

document.cookie = "myValue=5;path=/;domain=example.com";

This cookie should now be accessible to all sub-domains of example.com like login.example.com

Cookies need to have both path and domain appended to them to be removed. Try this:

cookies.remove("abc", {path: "/", domain: ".example.com"}) 

Working with Cookies in ReactJS

While working in a Javascript, you can have some simpler ways to work with cookies via npm package universal-cookie

npm install universal-cookie --save

Creating and Reading Cookie Example in Browser

import Cookies from 'universal-cookie';const cookies = new Cookies();cookies.set('myName', 'Aman', { path: '/' });console.log(cookies.get('myName')) // Aman

Reading Cookie Example in Server

import Cookies from 'universal-cookie';const cookies = new Cookies(req.headers.cookie);console.log(cookies.get('myName')); // Aman or undefined if not set yet

For detailed function included in the package,
Check NPM Package:- Universal-Cookie

Hope this helps :)

--

--

--

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +756K followers.

Recommended from Medium

Developer diary: Day 1 — Bazel build system with monorepo and typescript

[Action required] Your RSS.app Trial has Expired — Mon Jun 07 2021

Air BnB’s Digital Canvas

[Action required] Your RSS.app Trial has Expired — Thu May 27 2021

How to create the LWC Multi Select Combobox that Salesforce is still missing

Who would rather use a Lightning Dual Listbox instead of a Multi-Select Combobox?

How To Resolve CORS Error On Localhost And Netlify In A React App

MVI on Android

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
Aman Kumar

Aman Kumar

Building influencerbit.com, 📍Bengaluru

More from Medium

What is Execution Context, Lexical Environment And Hoisting?

Simple Cipher Solution

Making WebSocket connection using fastify:

How to Check if a Box Fits in a Box