Cookie Path and Scope
You'll learn how to use the path attribute to control which pages on your site can access a specific cookie.
What Is Cookie Path?
By default, a cookie set on your domain is available to every page on that domain. But what if you only want certain pages or sections of your site to access a particular cookie? That's where the path attribute comes in.
The path attribute restricts cookie availability to specific URL paths. When you set a cookie with a path, the browser only sends that cookie to the server when the requested URL matches or falls under that path.
How Path Works
When setting a cookie, add path=/some-path to limit its scope:
document.cookie = "user=John; path=/account";
This cookie is only available to pages under /account (like /account/profile, /account/settings). It won't be sent to /home or /products.
Common Path Values
path=/— Available site-wide (the default behavior)path=/dashboard— Only for/dashboardand its subpagespath=/checkout— Isolated to checkout-related pages
Why Use Path?
Think of your website as an apartment building. Without the path attribute, a cookie is like a key that opens every door. With path=/apartment-3, the key only works for apartment 3 and its rooms—other apartments can't use it.
This is useful for:
- Isolating features (shopping cart only in
/shop) - Security (admin cookies only in
/admin) - Avoiding naming conflicts between sections
Key Takeaway: The path attribute limits which URL paths can access a cookie, helping you organize data and improve security by restricting cookie scope to specific site sections.