Course contentsShow
← Web Development
Lesson 1602 of 2,98229. Web Authentication PatternsFree lesson

Domain and Path Restrictions for Cookies

Configure cookie domain and path attributes to limit token accessibility across your application.

Domain and Path Restrictions for Cookies

What you'll learn: How to use cookie Domain and Path attributes to control exactly where authentication tokens can be accessed in your application.

The Security Principle

When you store authentication tokens in cookies (as covered in earlier lessons), you need to ensure those cookies aren't accessible by every page or subdomain in your infrastructure. The Domain and Path attributes let you restrict cookie visibility, preventing unrelated parts of your application—or malicious actors—from reading sensitive tokens.

Domain Attribute

The Domain attribute controls which hosts can receive a cookie:

  • No domain specified: Cookie is only sent to the exact host that set it (www.example.com only)
  • Domain set explicitly: Cookie is sent to that domain and all subdomains (Domain=example.com means both api.example.com and www.example.com can access it)

Use case: If your frontend (app.example.com) and API (api.example.com) need to share authentication, set Domain=example.com. If they're completely separate domains, don't set this attribute.

Path Attribute

The Path attribute limits cookie access to specific URL paths:

  • Path=/api means the cookie only sends to /api/users, /api/posts, etc.
  • Path=/ (default) makes it available everywhere on the domain

Use case: If authentication tokens should only be sent to your API routes (/api/*), set Path=/api to prevent accidental exposure to public marketing pages.

Practical Configuration

Set-Cookie: token=abc123; Domain=example.com; Path=/api; Secure; HttpOnly; SameSite=Strict

This cookie only works on example.com and its subdomains, only for paths starting with /api, and includes all security flags from previous lessons.

Key Takeaway: Use Domain and Path attributes to apply the principle of least privilege—give your authentication cookies access to only the exact domains and paths they need, reducing your attack surface if other parts of your application are compromised.