How To Set Same Cookie On Different Domains

Read {count} times since 2020

You might have seen sites like Google setting the login status cookie on the various domains of theirs (YouTube, Blogger). As you may know, cookie can’t be set in a different domain from another domain directly.

If you’re having multiple sites in where you need to set a cookie from a parent site, you can use basic **HTML **and JS to set the cookies. Google is using this same way.


For this tutorial, we will refer to three domains :

We will set cookies on and from

Other Domains

You should make a dynamic page named “setCookie.php” on your server where you’re going to create the cookie. If it’s PHP, then add the following code to set the cookie :

setcookie("MyCookie", "", time()+3600);

In the above case we’re not mentioning the path or domain because PHP automatically sets it.

Main Domain

On the main domain ( where you’re going to ask the other two domains to set the cookie, create an HTML page with the following content :

<!DOCTYPE html>
   function loadComplete(){
    alert("Completed Setting Cookies");
 <body onload="loadComplete()">
  Please Wait...
  <img src="" style="display:none;" />
  <img src="" style="display:none;" />

When the client visits the above page, a page is requested from the domain as image source, but the page is not an image. This page that is on the other domain will set the cookie on that domain.

We also add an event listener on the document, so that we will know when the cookies are set completely. This is equal to document loaded listener because when the images are loaded, cookies are set.

Other Things

You can also send data to the other domains as GET parameters so that cookies based on that data can be created. But, when you send passwords or other secure content, be sure to encrypt the string.

The images should be hidden because, since it’s not valid images, the ugly image icon will appear in the browser.

You can change the content of the event listener callback loadComplete() to do something else according to your choice, like redirecting back to the main domain.

How Google Do It

If you have account on Blogger & YouTube which are on external domains, when you log in via you are redirected to a page that says “Please Wait…”, right ? If you look at the source code of the page, you can see the tags of and domain. Yes, Google is using the same way to set login information cookie on YouTube and Blogger.

Microsoft does in this same way to set cookies on their services like etc.. So many domains, right ?

Show Comments