How to Turn a 3rd Party Cookie into a 1st Party Cookie

in Website Tracking

Cookies are an important tool for tracking a users interactions with a web site over time. Unfortunately, due to bad press relating to their usage, they are often blocked by users leading to a reduction in the accuracy of the collected data. Because using the Internet has become hard to do without having first party cookies enabled, it’s now best practice to use these in a tracking application.

However, this is only possible when the data is being transmitted back to the same server from which the page being viewed originated. This is often a problem when creating a third party tracking service, or when using a global domain to collect data for a portfolio of sites. Luckily, there are techniques that can be used to overcome the problem.

Browser Cookies

A commonly cited solution is to set up a sub domain for each site that requires tracking, then point the domain at the tracking server; however, this requires some additional set-up to be done by the site owner, which makes the tracking solution harder to install, and sometimes isn’t feasible to do at all.

The technique that I use to solve this problem takes advantage of the fact that the JavaScript included in a page is executed in the first party security context, regardless of the actual domain from which it was loaded. This means that the script is able to set first party cookies on the user's machine even though it originated from a different source. The advantage of this approach is that it’s transparent to site owner who just needs to include the script in their page. I believe that it’s likely Google uses a similar approach to achieve this result in their Analytics solution.

To make this work, all that the tracking server needs to do is inject the data it wants stored into the JavaScript then the script can set the cookie while it’s executing on the client. When data needs to be transmitted back to the server, the JavaScript simply reads the cookie on the user's machine and sends it along with the rest of the data. Because no cookies are actually being sent to/from the user's machine there is no chance that they can be blocked: The server sends data embedded in a script, and the client sends it back using standard mechanisms, such as URL parameters.


I'm keen to get feedback on my posts, so if you have any questions or comments, then please send me a message and I'll be happy to help.


Brilliant solution! Could you please put up a sample of the script you're using?