May 29, 2009

Cookies across subdomains

I recently was on a project where we built an online contest/auction site for a company which ran from June through September.

The first thing the user did was register - using an already existing registration area in a different subdomain on the same site. Once they registered, a cookie was created, storing a login token. They were then redirected to our domain where we needed to access that same cookie and act accordingly. We also used cookies as a nicety to the user so they wouldn't have to login every time they came back to the site.

When we deployed, we found that we were unable to access the registration token cookie created in the other subdomain, because when the cookie was created, the domain was not specified, so the default domain was "registration.domain.com". Our application at "contest.domain.com" was unable to access this cookie. So we ended up resolving the issue by making sure to specify no subdomain, just using "domain.com". We were then able to reference each others' cookies across the entire domain:

document.cookie = name + '=' + value + "; expires=" + exp + "; domain=mydomain.com";

Share |