How to create domain-based cookies using JavaScript?

To create a domain-based cookie, set the domain and path attribute on your cookie. Domain-based cookies are accessible across all subdomains of the specified domain.

Syntax

document.cookie = "cookieName=value; domain=.example.com; path=/";

Domain Cookie Format

domain=.example.com

The dot prefix (.) makes the cookie available to all subdomains like www.example.com, api.example.com, etc.

Example: Setting Domain-Based Cookie

<html>
<head>
    <script>
        function WriteCookie() {
            if( document.myform.customer.value == "" ){
                alert("Enter some value!");
                return;
            }
            cookievalue = escape(document.myform.customer.value) + ";";
            document.cookie = "name=" + cookievalue + 
                "domain=.example.com;path=/";
            document.write("Setting Cookies : " + "name=" + cookievalue);
        }
    </script>
</head>
<body>
    <form name="myform" action="">
        Enter name: <input type="text" name="customer"/>
        <input type="button" value="Set Cookie" onclick="WriteCookie();"/>
    </form>
</body>
</html>

Modern Approach Using JavaScript

function setDomainCookie(name, value, domain) {
    const expires = new Date();
    expires.setTime(expires.getTime() + (7 * 24 * 60 * 60 * 1000)); // 7 days
    
    document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; domain=${domain}; path=/`;
    console.log(`Cookie set: ${name}=${value} for domain ${domain}`);
}

// Usage
setDomainCookie("username", "john_doe", ".example.com");
setDomainCookie("preferences", "dark_mode", ".mysite.com");
Cookie set: username=john_doe for domain .example.com
Cookie set: preferences=dark_mode for domain .mysite.com

Key Points

  • Domain prefix: Use .example.com (with dot) for all subdomains
  • Without dot: example.com works only for the exact domain
  • Path: Set path=/ to make cookie available site-wide
  • Security: Add Secure and SameSite attributes for production

Reading Domain Cookies

function getCookie(name) {
    const cookies = document.cookie.split(';');
    for(let cookie of cookies) {
        const [cookieName, cookieValue] = cookie.trim().split('=');
        if(cookieName === name) {
            return cookieValue;
        }
    }
    return null;
}

// Read the domain cookie
const username = getCookie("username");
console.log("Username from cookie:", username);
Username from cookie: john_doe

Conclusion

Domain-based cookies use the domain attribute to share data across subdomains. Always include the dot prefix and set appropriate path and security attributes for production use.

Updated on: 2026-03-15T23:18:59+05:30

412 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements