JavaScript Cookies — Path Attribute

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Cookie scope

What You’ll Learn

The path attribute controls which pages on your site can send and read a cookie. This tutorial explains prefix matching, why path=/ is the usual default for app cookies, and how wrong paths cause “missing cookie” bugs.

01

Prefix match

URL starts with path

02

path=/

Whole site

03

/shop scope

Section only

04

Default trap

Current directory

05

Duplicates

Path mismatch

06

DevTools

Path not in script

Introduction

Cookies store name–value data, but attributes decide where that data applies. The path attribute is one of the most important—and most overlooked. Set it wrong and a cookie works on one page but vanishes on the homepage.

You set path when you write a cookie. You cannot read the path back from document.cookie, but it still governs every read and HTTP request.

What Are JavaScript Cookies?

Cookies are small strings the browser stores and attaches to HTTP requests for the same origin. JavaScript sets them through document.cookie, optionally adding attributes like max-age, Secure, SameSite, and path.

The path attribute defines a URL path prefix. The browser includes the cookie on requests whose path starts with that prefix (per cookie matching rules). It does not mean “only this exact page.”

💡
Beginner Tip

For most site-wide preferences, always add path=/. Narrow paths like /shop are for section-specific data you deliberately want to isolate.

Understanding the path Attribute

When you omit path, the browser uses the directory of the current document URL as the default. A cookie set on /js/cookies/path without an explicit path is scoped to that folder—not to / or /js automatically.

Explicit paths give you control:

  • path=/ — every page on the origin (home, blog, checkout).
  • path=/shop/shop, /shop/cart, etc.
  • path=/app/settings — only URLs under that settings section.

📝 Syntax

Set a cookie limited to a URL prefix:

JavaScript
document.cookie = "userToken=abc123; path=/shop; max-age=86400";

Set a cookie for the entire site:

JavaScript
document.cookie = "sessionId=abc123; path=/; max-age=3600; SameSite=Lax";

Matching rule (simplified)

  • Request path must be under the cookie’s path prefix to send the cookie.
  • / matches all paths on the host.
  • Narrower paths hide the cookie from unrelated sections (blog vs shop).

⚡ Quick Reference

path valueVisible on (examples)
//, /about, /shop/cart
/shop/shop, /shop/item/5
/shopNot on /blog or /account
(omitted on /js/foo)Default ~ /js/ scope, not whole site
Same name, different pathTwo separate cookies in the jar

📋 Common Path Scopes

Pick the narrowest path that still covers every page needing the cookie. When in doubt, use path=/.

Site-wide
path=/

Theme, lang, session

Section
path=/shop

Cart in store only

Default
(omitted)

Current URL directory

Bug pattern
path=/app

Missing on homepage

How the Cookie Path Affects Availability

The browser decides cookie visibility separately for JavaScript reads and HTTP requests, but both follow the same path rules. If the current page URL is not under the cookie path, document.cookie will not include that cookie.

  • path=/ — sent on all same-origin requests.
  • path=/shop — sent on /shop and deeper paths only.
  • path=/app/settings — limited to that subtree.

When updating cookies, reuse the original path or you create a duplicate—see Update cookies.

Examples Gallery

Use DevTools → Application → Cookies to inspect path values. Try-it labs run on this page’s URL—compare scoped vs path=/ cookies.

📚 Getting Started

Site-wide cookies with the root path.

Example 1 — Site-Wide Cookie with path=/

Make a session cookie available on every page of your domain.

JavaScript
document.cookie = "sessionId=abc123; path=/; max-age=3600; SameSite=Lax";

// Readable on /, /about, /shop/cart, and this tutorial page
Try It Yourself

How It Works

path=/ is the path prefix that matches every URL on the host. Pair it with max-age or expires for persistence.

📈 Practical Patterns

Section scope, defaults, duplicates, and helpers.

Example 2 — Restrict Cookie to /shop

Keep a cart token only in the store section.

JavaScript
document.cookie = "cartId=xyz789; path=/shop; max-age=604800";

// Sent on /shop and /shop/checkout
// NOT sent on /blog or /account
Try It Yourself

How It Works

Prefix matching limits exposure. Useful when shop data should not leak to unrelated areas, but remember users on non-/shop pages cannot read it from script either.

Example 3 — Default Path Trap (Omitted path)

See what happens when you forget path=/ on a deep URL.

JavaScript
// On https://example.com/js/cookies/path — no path attribute
document.cookie = "prefs=compact; max-age=604800";

// Default path ≈ /js/cookies/
// Cookie missing on https://example.com/ and /js/
Try It Yourself

How It Works

This is the #1 production cookie bug: set on one route without path=/, then missing everywhere else. Fix by always passing path=/ unless you intentionally want a narrow scope.

Example 4 — Path Mismatch Creates Duplicate Cookies

Updating with a different path does not replace the original.

JavaScript
document.cookie = "username=John; path=/; max-age=604800";

// Attempted "update" with wrong path
document.cookie = "username=Jane; path=/account; max-age=604800";

// DevTools may show TWO username cookies
// document.cookie on / lists both when paths match current URL
Try It Yourself

How It Works

Name alone does not identify a cookie—path (and domain) complete the key. Match paths when updating or delete the old cookie first.

Example 5 — setCookieWithPath Helper

Centralize path defaults so writes and updates stay consistent.

JavaScript
function setCookieWithPath(name, value, cookiePath, maxAgeSeconds) {
  const encoded = encodeURIComponent(value);
  const path = cookiePath || "/";
  let cookie = name + "=" + encoded + "; path=" + path + "; SameSite=Lax";
  if (typeof maxAgeSeconds === "number") {
    cookie += "; max-age=" + maxAgeSeconds;
  }
  document.cookie = cookie;
}

setCookieWithPath("theme", "dark", "/", 604800);
setCookieWithPath("cartId", "item-42", "/shop", 86400);
Try It Yourself

How It Works

Defaulting to / prevents accidental directory scoping. Pass an explicit second path only for section-specific cookies.

🚀 Common Use Cases

  • Global preferencespath=/ for theme and language.
  • Store cartpath=/shop isolates commerce data.
  • Admin panelspath=/admin limits admin flags to staff URLs.
  • Multi-app hosts — separate paths per mounted app on one domain.
  • Staging vs prod — keep path conventions identical across environments.
  • Debugging — compare path column in DevTools when cookies “vanish.”

🧠 How Path Matching Works

1

Cookie stored

Browser saves name, value, path prefix, and other flags.

Write
2

Page loads

Current URL path is compared against each cookie’s path.

Match
3

Include or skip

Matching cookies appear in document.cookie and HTTP Cookie headers.

Expose
4

Scoped access

Non-matching paths behave as if the cookie does not exist for that page.

📝 Notes & Common Pitfalls

  • Forgetting path=/ — cookies stuck in one directory; classic “works on this page only” bug.
  • Too narrow/app/settings excludes /app/dashboard.
  • Path change on update — creates duplicates instead of overwrites.
  • Script cannot read path — use DevTools to audit scope.
  • domain vs path — path controls URL prefix; domain controls host (advanced, use carefully).
  • Environment drift — different base paths in dev/staging break cookie sharing.

Browser Support

The path attribute on cookies is part of the original cookie specification and works in all browsers that support document.cookie.

Baseline · DOM Level 0

Cookie path attribute

Universal behavior in Chrome, Firefox, Safari, Edge, and Internet Explorer. Prefix matching rules are consistent; always verify scoped cookies in DevTools.

99% Universal attribute
Google Chrome All versions · Desktop & Mobile
Full support
Mozilla Firefox All versions · Desktop & Mobile
Full support
Apple Safari All versions · macOS & iOS
Full support
Microsoft Edge All versions · Chromium & Legacy
Full support
Internet Explorer IE 6+ · Legacy environments
Full support
Opera All modern versions
Full support
path Excellent

Bottom line: No polyfill needed. Standardize on path=/ for site-wide cookies and document intentional narrow paths in code comments or shared helpers.

Conclusion

The path attribute defines which URLs share a cookie. Use path=/ for site-wide data, narrower prefixes for isolated sections, and never change path casually when updating values.

When a cookie seems missing, check path in DevTools before rewriting your read logic—scope issues look like parsing bugs.

💡 Best Practices

✅ Do

  • Default to path=/ for global cookies
  • Reuse the same path on updates
  • Inspect path in DevTools when debugging
  • Document narrow paths in helpers
  • Keep paths consistent across environments

❌ Don’t

  • Omit path on deep URLs
  • Assume one name = one cookie
  • Change path to “fix” updates
  • Expect path in document.cookie
  • Over-narrow without a reason

Key Takeaways

Knowledge Unlocked

Five things to remember about cookie path

Scope cookies deliberately and avoid silent bugs.

5
Core concepts
🌐 02

path=/

Whole site.

Default
🛒 03

/shop

Section scope.

Narrow
04

Omitted

Current directory.

Trap
📋 05

Duplicates

Path mismatch.

Pitfall

❓ Frequently Asked Questions

path limits which URLs on your site send and expose the cookie. A cookie with path=/shop is included on /shop, /shop/cart, and /shop/checkout, but not on /blog or /.
The browser defaults to the directory of the page that set the cookie. A cookie set on /js/cookies/path without an explicit path is scoped to /js/cookies/ (or similar), not the whole site.
Use path=/ whenever the cookie should be readable and sent on every page of your origin—theme, language, cart ID, and most app-wide preferences.
No. document.cookie returns only name=value pairs. Inspect path in DevTools under Application → Cookies.
Usually different path (or domain) values. Updating username at path=/account does not replace username at path=/—the browser stores both.
Browsers match URL path prefixes. /app and /app/ behave similarly for paths like /app/settings, but stay consistent in your code—path=/ is the common site-wide choice.
Did you know?

Setting a cookie on the homepage with path=/ makes it visible everywhere, but setting the same cookie on a deep page without a path often limits it to that folder—the two assignments look identical in code except for one missing attribute.

Continue to Read Cookies

Learn how to parse document.cookie and recover stored values on matching paths.

Read cookies tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful