Skip to content
Back to blog

Blog

Browser Caching Basics for Faster Websites

6 min
Table of Contents

Every time someone opens your website, their browser faces a choice: download everything again, or reuse what it already has. Browser caching is how you nudge it towards the sensible option. Get it right and repeat visits feel almost instant. Get it wrong and you either waste bandwidth or spend an afternoon wondering why your CSS fix refuses to show up. We’ve all been there.

This guide covers how browser caching really works, the headers that matter, one simple policy that suits most sites, and ready-to-use setups for the stacks people actually run in 2026.

The short version

  • Give your CSS, JavaScript, images and fonts fingerprinted filenames (like app.4f9a1c.css), then cache them for a year with immutable.
  • Serve your HTML with no-cache, so it is always checked for freshness.
  • Anything whose filename never changes (like logo.png) gets a short cache time, not a long one.
  • no-cache does not mean “don’t cache”. That one trips up almost everybody.

How browser caching works

On the first visit, the browser downloads everything it needs. Each response can carry caching instructions in its HTTP headers, and the browser stores the files locally according to them.

On the next visit, one of three things happens:

  1. The file is still fresh. The max-age hasn’t run out, so the browser uses its stored copy and sends no request at all. In DevTools you’ll see (memory cache) or (disk cache).
  2. The file is stale, but unchanged. The browser asks the server, “Has this changed?” using the ETag it saved (sent as If-None-Match). If nothing has changed, the server replies with a tiny 304 Not Modified and no body, and the browser reuses its copy.
  3. The file is stale and changed. The server sends a fresh copy with a 200, and the cycle starts again.

If a response has no caching headers at all, browsers may guess how long to keep it, based on its Last-Modified date. Guessing is a bad strategy, so set explicit headers.

The headers that matter

HeaderWhat it doesNotes
Cache-ControlThe main caching policyTakes priority over Expires
ETagA version fingerprint used for revalidationPairs with If-None-Match and 304
Last-ModifiedA date-based validatorA fallback when there is no ETag
ExpiresAn absolute expiry dateLegacy. Ignored when Cache-Control has max-age
VarySays which request headers change the responseFor example Accept-Encoding

And the Cache-Control directives you’ll actually use:

DirectiveMeaning
max-age=NTreat the response as fresh for N seconds
immutableThis file will never change, so don’t bother revalidating it
public / privateShared caches (like a CDN) may store it / only the user’s browser may
no-cacheYou may store it, but check with the server before every reuse
no-storeDon’t store it at all. Use for sensitive, personal data
s-maxage=NLike max-age, but for shared caches such as CDNs
stale-while-revalidate=NServe the stale copy instantly while fetching a fresh one in the background

The classic mix-up is no-cache versus no-store. no-cache still stores the file and just insists on revalidating, which is cheap thanks to 304. no-store is the “never keep this” option.

The one policy I’d start with

ResourceCache-ControlWhy
Fingerprinted CSS, JS, images, fontspublic, max-age=31536000, immutableThe filename changes when the content does, so a year is safe
Unfingerprinted static files (logo.png, favicon.ico)public, max-age=86400You can’t force a refresh, so keep it short
HTML pagesno-cacheAlways revalidate, so users get new content straight away
Public API data that changes now and thenpublic, max-age=60, stale-while-revalidate=300Fast, but never very stale
Personal or sensitive responsesprivate, no-storeNothing should keep a copy

The golden rule: long cache times are only safe when the URL changes whenever the content changes. That is exactly what fingerprinting gives you.

Fingerprinting your files

html
<!-- Before: same URL forever, so you can't safely cache it long-term -->
<link href="/styles.css" rel="stylesheet">
 
<!-- After: the hash changes whenever the content changes -->
<link href="/styles.f93bca2c.css" rel="stylesheet">

Modern build tools (Vite, webpack, Next.js and friends) do this for you automatically. Your HTML points to the new filename after each deploy, and because the HTML is revalidated every time, visitors pick it up immediately.

Setting it up

Next.js

Next.js already serves everything under /_next/static/ with public, max-age=31536000, immutable, so your fingerprinted JS and CSS are covered. For your own routes, use headers() in your Next.js config:

js
// next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/api/stats',
        headers: [
          {
            key: 'Cache-Control',
            value: 'public, max-age=60, stale-while-revalidate=300',
          },
        ],
      },
      {
        source: '/images/:path*',
        headers: [{ key: 'Cache-Control', value: 'public, max-age=86400' }],
      },
    ]
  },
}

Check what your host adds on top, too. Some platforms override or extend these headers.

Cloudflare

Cloudflare caches common static file types at the edge by default, but not HTML. In Caching → Cache Rules you can set an Edge TTL (how long Cloudflare keeps the file) and a Browser TTL (how long visitors’ browsers keep it) separately. If your origin already sends good Cache-Control headers, choose the option to respect them rather than overriding.

Nginx

nginx
# Fingerprinted assets: cache for a year
location /assets/ {
    add_header Cache-Control "public, max-age=31536000, immutable" always;
}
 
# HTML: always revalidate
location / {
    add_header Cache-Control "no-cache" always;
}

Apache

This needs mod_headers enabled. mod_expires works too, but Cache-Control through Header gives you more control:

apache
<IfModule mod_headers.c>
    # Only use a year if your filenames are fingerprinted
    <FilesMatch "\.(css|js|woff2|avif|webp|png|jpe?g|svg)$">
        Header set Cache-Control "public, max-age=31536000, immutable"
    </FilesMatch>
 
    <FilesMatch "\.html$">
        Header set Cache-Control "no-cache"
    </FilesMatch>
</IfModule>

WordPress

Plugins such as WP Rocket, W3 Total Cache, WP Super Cache and LiteSpeed Cache can set these headers for you. One catch: WordPress usually versions files with a query string (style.css?ver=6.8) rather than in the filename, which some CDNs ignore. If you go for long cache times, test that updates actually reach visitors.

Myths that refuse to die

“Use a public CDN for jQuery so it’s already cached.” This used to work. Browsers now partition their caches by site, so a file cached for one website isn’t reused on another. Self-host your files and fingerprint them.

“Caching is a direct ranking factor.” Not quite. Core Web Vitals (LCP, INP and CLS) are part of Google’s page experience signals, but they are one signal among many, and relevant content still wins. Caching helps by making pages faster for returning visitors, which is a good thing in itself.

“Caching will fix my LCP.” Only partly. Caching mostly helps repeat visits. A visitor’s first load still depends on your server speed, image sizes and render-blocking resources. Treat caching as one part of performance, not the whole story.

Common pitfalls

  • Long max-age on HTML. Visitors can get stuck on an old page for a very long time. Keep HTML on no-cache.
  • Long max-age on files whose name never changes. You can’t take it back once it’s in someone’s browser. Fingerprint first, then cache long.
  • Confusing no-cache with no-store. The first revalidates, the second refuses to store. Use no-store for genuinely sensitive data.
  • Forgetting the CDN layer. After a deploy, your CDN may still serve the old version. Purge it, or use fingerprinted URLs so you never have to.
  • Inconsistent rules. Similar files should follow the same policy, otherwise debugging becomes a guessing game.

Testing your setup

  1. Browser DevTools. Open the Network tab and reload. Look for (memory cache) or (disk cache) in the Size column, and 304 in the Status column. Untick “Disable cache” first, otherwise you’re testing nothing.
  2. curl -I. Run curl -I https://yoursite.com/path/to/file.css to see the exact headers being sent.
  3. Lighthouse and PageSpeed Insights. Look for the audit about an efficient cache policy on static assets. Then check the real-user (field) data for LCP, INP and CLS.
  4. Your CDN’s analytics. This is where a “cache hit ratio” actually lives. It shows how many requests were served from the edge instead of your origin.

One small clarification on metrics: a browser cache hit never reaches the network, so it has no TTFB at all. TTFB for your HTML document improves through server and CDN caching, not browser caching.

Key takeaways

  • Fingerprint static files, then cache them for a year with immutable.
  • Serve HTML with no-cache and let ETag and 304 keep revalidation cheap.
  • Use short cache times for files whose names never change.
  • Use stale-while-revalidate for semi-dynamic data.
  • Test with DevTools and curl -I, and track real-user LCP, INP and CLS.

FAQs

What’s the difference between no-cache and no-store?

no-cache lets the browser store the file but forces it to check with the server before reusing it. no-store tells the browser not to store the response at all. Use no-store for sensitive data, and no-cache for HTML you want to stay fresh.

Why am I still seeing the old CSS after a deploy?

Usually it’s one of three things: the CSS file has a long max-age but an unchanged filename, your HTML is being cached too aggressively, or your CDN hasn’t been purged. Fingerprint your files, serve HTML with no-cache, and purge the CDN when needed. A hard refresh bypasses your own browser’s cache, but your visitors won’t know to do that.

Do I still need an ETag if I use max-age?

Yes. max-age decides how long a file stays fresh. Once it expires, the ETag lets the browser revalidate cheaply with a 304 instead of downloading the whole file again. Most servers add ETag automatically.

Why does the back button feel instant even with no-cache?

That’s usually the back/forward cache (bfcache), which keeps an entire page in memory so it can be restored instantly. It’s separate from the HTTP cache described in this post.

Further reading