Cache-Control: public vs private Directive
Understand the difference between public and private Cache-Control directives, when to use each, and how they affect CDN and proxy caching behavior.
Detailed Explanation
public vs private
The public and private directives control who is allowed to cache a response. They determine whether shared caches (CDNs, reverse proxies) can store the response alongside the end user's browser.
public
Cache-Control: public, max-age=86400
The public directive explicitly allows any cache — browser, CDN, proxy, gateway — to store the response. This is the right choice for content that is identical for all users.
Use public for:
- Static assets (CSS, JavaScript, images, fonts)
- Public API endpoints that return the same data for everyone
- Marketing pages and blog posts
private
Cache-Control: private, max-age=300
The private directive restricts caching to the end user's browser only. Shared caches (CDNs, corporate proxies) must not store the response.
Use private for:
- Personalized pages (dashboard, profile, account settings)
- Authenticated API responses containing user-specific data
- Responses that include session tokens or CSRF tokens
- Shopping cart contents
Default Behavior
If neither public nor private is specified:
- Responses without an
Authorizationheader are typically treated as cacheable by shared caches - Responses with an
Authorizationheader are treated as private unlesspublicis explicitly set
Common Mistake
A frequent error is setting public on authenticated API responses. This can cause CDNs to serve User A's private data to User B. Always use private when the response varies per user.
Use Case
When deploying a Next.js application behind a CDN like Cloudflare or Fastly, static assets (JS bundles, CSS, images) should use 'public, max-age=31536000, immutable' so the CDN caches them globally. API routes that return user-specific data (e.g., /api/me) must use 'private, max-age=0, must-revalidate' to prevent the CDN from accidentally serving one user's data to another. Getting this distinction right is critical for both performance and security.