Course contentsShow
← Web Development
Lesson 802 of 2,98214. Browser StorageFree lesson

Cookie Domain Attribute

Using the domain attribute to share cookies across subdomains and understanding default domain behavior.

Cookie Domain Attribute

You'll learn how to control which domains and subdomains can access your cookies.

What Is the Domain Attribute?

When you set a cookie, the browser needs to know which websites should be able to read it. By default, a cookie is only available to the exact domain that created it. The domain attribute lets you expand that scope to include subdomains, making cookies shareable across parts of your website.

Default Domain Behavior

If you don't specify a domain attribute, the cookie is tied to the exact hostname that set it:

document.cookie = "user=John; path=/";
// Set on www.example.com → only accessible on www.example.com
// NOT accessible on blog.example.com or example.com

Setting the Domain Attribute

To share a cookie across subdomains, specify the parent domain:

document.cookie = "user=John; path=/; domain=example.com";
// Now accessible on:
// - example.com
// - www.example.com
// - blog.example.com
// - shop.example.com

Important: You can only set the domain to the current domain or a parent domain. You cannot set cookies for completely different domains (security restriction).

Think of It Like Mail Forwarding

Imagine your cookie is a letter. Without a domain attribute, it only gets delivered to one specific apartment (www.example.com). With domain=example.com, it's like setting up mail forwarding for an entire apartment building—all units (subdomains) can receive it.

When to Use It

Use the domain attribute when you have multiple subdomains that need to share authentication status, user preferences, or shopping cart data. Just remember: broader scope means less isolation between different parts of your site.

Key Takeaway: The domain attribute shares cookies across subdomains; without it, cookies stick to the exact domain that created them—you can only set it to your current or parent domain for security.