Sharing cookies between subdomains

Published on: November 20, 2014

A while ago I wrote about sharing cookies on an old Tumblr blog of mine. I figured it contains some valuable information so I migrated the post here. The reason I wrote it was that I was working on a pitch that would take a user through a series of puzzles. Each puzzle would enable the user to see the next website(subdomain) and I decided I'd save the progress of the user in a cookie.

Normally you'd define a cookie for a domain like www.example.com. When the browser tries to read this cookie, the current domain has to be www.example.com. So sub.example.com wouldn't work and the cookie won't be read. There is, however, a way to get around this security limitation and it's quite easy.

If you only specify .example.com(note the period before example.com) as the host for your cookie, it will be accessible for every subdomain from this host. So both www.example.com and sub.example.com can use this cookie.

An example in code (using the jquery cookie plugin):

$.cookie('foo', 'bar', {path: '/', domain: '.example.com'});

Well, hope it's helpful to some of you out there.

Categories

Uncategorized

Subscribe to my newsletter