How to set Cookies to share across all subdomains using JavaScript

Browser Cookies, is a very handy feature that enables us as a web developer to do so many interactive programming. Recently since HTML5 raised up, its Web Storage is replacing this feature. But there is one area where Web Storage fails to achieve the result – subdomain access. There we have to again jump back for old school document.cookie method.

In this very quick tutorial, lets discuss how we can setup browser cookies that can be accessed from all subdomains and root domain. But proceeding further requires basic knowledge of cookies, and if you need to learn, Tutorial Point has good article on JavaScript Cookies.

Steps:

  1. Prepare the cookie name/value
  2. Get the top level domain and assign as .domain.com
  3. Set the path to root path=/
  4. Set Expires (optional)

Lets set up a example cookie. Example take as ‘Last time report generated’ to showup across subdomains.


//variables
var LastReportGenerated="Jul 11 2013",
baseDomain = '.expiredqueues.com',
expireAfter = new Date();

//setting up  cookie expire date after a week
expireAfter.setDate(expireAfter.getDate() + 7);

//now setup cookie
document.cookie="Report={'ReportName':'MainReport', 'lastGenerated':" + LastReportGenerated + "}; domain=" + baseDomain + "; expires=" + expireAfter + "; path=/";

Major thing to take care here is:

Your domain must be in format of “.domain.com” – dot and root domain and your path=/ always. If you don’t setup your path=/, auto path will be saved as from where the cookies is being saved hence it wont be accessible across any subdomain.

You can try copy paste code above in the Console, and see the result in Resource Panel. If you happen to successfully run the script above, you will get a preview:

JavaScript Cookie

Now that ‘Report’ cookie should be available across all subdomains like = main.cssjunction.com, tuts.cssjunction.com etc.

You might be interested in: