# Configure browser and server caching

- Check 06.09 · Performance and Core Web Vitals · Important
- Source: https://checklist-seo-geo.com/en/performance-core-web-vitals/configure-browser-server-caching
- Set Cache-Control, ETag and page caching on Apache, Nginx, LiteSpeed, Cloudflare, CloudFront, Varnish, Plesk, cPanel, WordPress, Laravel or Next.js.
- Updated on 2026-11-25
- Licence: CC BY 4.0. Credit “Checklist SEO & GEO” with a link to https://checklist-seo-geo.com/en/performance-core-web-vitals/configure-browser-server-caching.
- Plugin checklist-seo-geo: 1.3.1 · https://github.com/maximegaul/checklist-seo-geo

## In short

Caching avoids doing the same work twice. The browser cache keeps files the visitor has already downloaded (CSS, JavaScript, images, fonts); the server cache, or page cache, keeps HTML that has already been generated so it can be served again without running the application. Once this check is done, versioned static files carry `Cache-Control: public, max-age=31536000, immutable`, public HTML is served from a cache in a few tens of milliseconds, and personalized pages are never cached.

## Why it matters

Without instructions, each layer improvises. The browser requests files again or guesses a lifetime; the server regenerates the same page for every visitor, with the same database queries.

Three cache levels complement each other:

- **Browser**: controlled by response headers. It removes entire requests on subsequent pages and on return visits.
- **Shared cache** (CDN, for Content Delivery Network, or reverse proxy): a single response serves every visitor.
- **Page cache at the origin** (Nginx, Varnish, LiteSpeed, CMS plugin): HTML generated once is served again without PHP or the database.

Crawlers benefit too. Googlebot sends conditional requests (`If-None-Match`, `If-Modified-Since`): a server that responds `304 Not Modified` saves the transfer. Google recommends the `ETag` header for this.

## What it improves

- **Browsing and return visits**: cached files are no longer downloaded; subsequent pages display almost instantly.
- **TTFB (Time to First Byte)**: a page served from a cache responds much faster than a generated page, which directly benefits LCP (Largest Contentful Paint).
- **Load handling and costs**: less CPU, fewer database queries and less bandwidth.
- **Crawling**: faster responses and 304s for crawlers. A noticeable effect on large sites.
- **Lighthouse audit**: the diagnostic about cache lifetimes disappears.
- **Rankings**: no direct effect.

## How to check

A static file, then a page:

```bash
curl -sI https://example.com/build/assets/app-3f2a1c9b.css | grep -i -E "^(cache-control|etag|last-modified|age):"
curl -sI https://example.com/ | grep -i -E "^(cache-control|etag|age|set-cookie|cf-cache-status|x-cache|x-litespeed-cache|x-fastcgi-cache|x-vercel-cache):"
```

Compliant result:

- versioned file: `cache-control: public, max-age=31536000, immutable`;
- public page: `cache-control: no-cache` or a short lifetime, no `set-cookie`, and on the second request a `HIT` indicator if a page cache is in place;
- account or cart page: `cache-control: private, no-store`.

Test revalidation with the `ETag` value you received; the expected response is `304`:

```bash
curl -sI -H 'If-None-Match: "VALEUR_ETAG"' https://example.com/ | head -n 1
```

## How to implement

### Before you start

Target policy:

| Resource | Header | Why |
|---|---|---|
| CSS, JS, fonts with a versioned name (`app-3f2a1c9b.css`) | `public, max-age=31536000, immutable` | The name changes with every modification |
| Images and files with a stable name (`logo.png`) | `public, max-age=2592000` | One month, then revalidation with `ETag` |
| Public HTML | `no-cache`, or `public, max-age=0, s-maxage=600` | The browser revalidates; the shared cache keeps it ten minutes |
| Personalized pages, cart, account, admin | `private, no-store` | Never in a shared cache |

Directives to know: `max-age` (lifetime in seconds, all caches), `s-maxage` (shared caches only), `no-cache` (store but revalidate on every use), `no-store` (store nothing), `private` (browser only), `immutable` (do not revalidate, even on reload), `stale-while-revalidate` (serve the old version while updating).

Two rules:

- **Long lifetimes only on versioned URLs.** The file name contains a hash of its content, generated by the build tool (Vite, webpack) or, failing that, a `?v=` parameter. Without versioning, limit CSS and JavaScript to one day at most.
- **Page cache for anonymous visitors only.** GET requests, 200 responses, no session. Exclude cart, checkout, account, admin and internal search, and purge on every publication.

> **Warning:** a poorly configured page cache can serve one visitor another visitor's cart or account. After each rule change, test logged in, logged out and with items in the cart.

### Apache

Versions: Apache 2.4.

Enable the module (`sudo a2enmod headers`), then add to the virtual host or the `.htaccess`:

```apache
<IfModule mod_headers.c>
    <FilesMatch "\.(?:css|js|mjs|woff2?|ttf|otf)$">
        Header set Cache-Control "public, max-age=31536000, immutable"
    </FilesMatch>

    <FilesMatch "\.(?:avif|webp|jpe?g|png|gif|svg|ico|mp4|webm|pdf)$">
        Header set Cache-Control "public, max-age=2592000"
    </FilesMatch>

    <FilesMatch "\.html?$">
        Header set Cache-Control "no-cache"
    </FilesMatch>
</IfModule>
```

If your CSS and JS are not versioned, replace the first value with `public, max-age=86400`. Apache emits `ETag` and `Last-Modified` for static files with no configuration.

For a page cache, `mod_cache` is configured in the virtual host (`sudo a2enmod cache cache_disk`):

```apache
<IfModule mod_cache_disk.c>
    CacheQuickHandler off
    CacheRoot /var/cache/apache2/mod_cache_disk
    CacheEnable disk /
    CacheHeader on
    CacheLock on
    CacheIgnoreHeaders Set-Cookie
    CacheDisable /wp-admin
</IfModule>
```

A dynamic page is only stored if the application declares a lifetime (`Cache-Control: s-maxage=600`). `mod_cache` does not take request cookies into account: reserve it for sites without a logged-in area, or prefer Varnish or a CMS plugin. The `X-Cache` header shows `HIT` or `MISS`. Reload with `sudo apachectl configtest && sudo systemctl reload apache2`.

### Nginx

Versions: Nginx 1.18 and later, including 1.30 (stable) and 1.31 (mainline).

Browser cache, in the `server` block:

```nginx
location ~* \.(?:css|js|mjs|woff2?|ttf|otf)$ {
    add_header Cache-Control "public, max-age=31536000, immutable";
    access_log off;
}

location ~* \.(?:avif|webp|jpe?g|png|gif|svg|ico|mp4|webm|pdf)$ {
    add_header Cache-Control "public, max-age=2592000";
    access_log off;
}
```

An `add_header` in a `location` block cancels those inherited from the `server` block: repeat your security headers there.

Page cache for PHP with `fastcgi_cache`. In the `http` context:

```nginx
fastcgi_cache_path /var/cache/nginx/pages levels=1:2 keys_zone=PAGES:100m max_size=1g inactive=60m use_temp_path=off;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
```

In the `server` block:

```nginx
set $sans_cache 0;

if ($request_method = POST) {
    set $sans_cache 1;
}

if ($request_uri ~* "/wp-admin/|/wp-login|/panier|/commande|/mon-compte|/cart|/checkout") {
    set $sans_cache 1;
}

if ($http_cookie ~* "wordpress_logged_in|comment_author|woocommerce_items_in_cart|PHPSESSID") {
    set $sans_cache 1;
}

location ~ \.php$ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass unix:/run/php/php8.4-fpm.sock;

    fastcgi_cache PAGES;
    fastcgi_cache_valid 200 301 10m;
    fastcgi_cache_bypass $sans_cache;
    fastcgi_no_cache $sans_cache;
    fastcgi_cache_use_stale error timeout updating http_500 http_503;
    fastcgi_cache_background_update on;
    fastcgi_cache_lock on;
    add_header X-FastCGI-Cache $upstream_cache_status always;
}
```

Adapt the socket path, the URLs and the excluded cookies. Nginx does not cache a response that contains `Set-Cookie` or `Cache-Control: private, no-cache, no-store`: an application that opens a session on every page will never be cached.

For an application behind `proxy_pass` (Node.js, Next.js, Python), keep the `$sans_cache` conditions and replace `fastcgi_cache` with `proxy_cache`:

```nginx
# http context
proxy_cache_path /var/cache/nginx/app levels=1:2 keys_zone=APP:100m max_size=1g inactive=60m use_temp_path=off;

# server block
location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;

    proxy_cache APP;
    proxy_cache_key "$scheme$request_method$host$request_uri";
    proxy_cache_valid 200 10m;
    proxy_cache_bypass $sans_cache;
    proxy_no_cache $sans_cache;
    proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
    proxy_cache_background_update on;
    proxy_cache_lock on;
    add_header X-Proxy-Cache $upstream_cache_status always;
}
```

Reload with `sudo nginx -t && sudo systemctl reload nginx`. To purge, empty the folder: `sudo find /var/cache/nginx/pages -type f -delete`.

### LiteSpeed

Versions: LiteSpeed Web Server 6.x, OpenLiteSpeed 1.7 and later.

LiteSpeed reads `mod_headers` and `mod_expires` directives: the Apache block works as is in the `.htaccess`.

The page cache is called LSCache. With a CMS, install the official LiteSpeed Cache plugin (WordPress, PrestaShop, Magento, Joomla, Drupal): it handles exclusions and purging. Without a plugin, in the `.htaccess`:

```apache
<IfModule LiteSpeed>
    CacheLookup on
    RewriteEngine On
    RewriteCond %{REQUEST_METHOD} ^(GET|HEAD)$
    RewriteCond %{HTTP_COOKIE} !(PHPSESSID|session) [NC]
    RewriteCond %{REQUEST_URI} !^/(admin|panier|compte) [NC]
    RewriteRule .* - [E=Cache-Control:max-age=600]
</IfModule>
```

Compliant: `x-litespeed-cache: hit` on the second request. The cache module must be enabled by the host.

### Caddy

Versions: Caddy 2.

```txt
example.com {
    root * /var/www/example

    @versionnes path *.css *.js *.mjs *.woff2 *.woff
    header @versionnes Cache-Control "public, max-age=31536000, immutable"

    @medias path *.avif *.webp *.jpg *.jpeg *.png *.gif *.svg *.ico
    header @medias Cache-Control "public, max-age=2592000"

    file_server
}
```

Caddy emits `ETag` and `Last-Modified` automatically. It has no built-in page cache: add the `cache-handler` module with an `xcaddy` build, or put a CDN in front. Reload with `sudo systemctl reload caddy`.

### IIS

Versions: IIS 10 (Windows Server 2016 to 2025).

In the `web.config`:

```xml
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" cacheControlCustom="public" />
    </staticContent>
    <caching enabled="true" enableKernelCache="true">
      <profiles>
        <add extension=".aspx" policy="CacheForTimePeriod" kernelCachePolicy="CacheForTimePeriod" duration="00:10:00" varyByQueryString="*" />
      </profiles>
    </caching>
  </system.webServer>
</configuration>
```

`clientCache` applies to every static file in the folder: put a second `web.config` with `365.00:00:00` in the folder of versioned files. The `caching` section enables output caching; with ASP.NET Core, use its output caching middleware instead.

### Cloudflare

Versions: Cloudflare dashboard, all plans, November 2026.

By default, Cloudflare caches static files based on their extension, respecting the origin's `Cache-Control`, and does not cache HTML (`cf-cache-status: DYNAMIC`).

**Browser cache**: in [`Caching > Configuration`](https://dash.cloudflare.com/?to=/:account/:zone/caching/configuration), set Browser Cache TTL to “Respect Existing Headers” so that your origin policy applies.

**HTML caching**: open the [Cache Rules](https://dash.cloudflare.com/?to=/:account/:zone/caching/cache-rules) page (in the `Caching` or `Rules` section depending on the dashboard version), then “Create rule”.

1. Custom filter expression, to adapt to your URLs and cookies:

```txt
(http.host eq "example.com" and not http.request.uri.path contains "/wp-admin" and not http.request.uri.path contains "/panier" and not http.cookie contains "wordpress_logged_in" and not http.cookie contains "woocommerce_items_in_cart")
```

2. Cache eligibility: “Eligible for cache”.
3. Edge TTL: respect the origin if it sends `s-maxage`, otherwise override with a lifetime, for example two hours.
4. Browser TTL: respect the origin.
5. Deploy, then check that `cf-cache-status` changes from `MISS` to `HIT`.

By default, Cloudflare does not cache a response carrying a `Set-Cookie`: your public pages must not send one. To give the CDN a lifetime different from the browser's without a rule, the origin can send the `Cloudflare-CDN-Cache-Control` header.

**Purge**: [`Caching > Configuration`](https://dash.cloudflare.com/?to=/:account/:zone/caching/configuration), purge by URL or purge everything. Via the API:

```bash
curl -X POST "https://api.cloudflare.com/client/v4/zones/ID_DE_ZONE/purge_cache" \
  -H "Authorization: Bearer JETON_API" \
  -H "Content-Type: application/json" \
  --data '{"files":["https://example.com/","https://example.com/blog/"]}'
```

Purge by URL on every publication; keep the full purge for template changes.

### AWS

Versions: CloudFront and S3 consoles, AWS CLI v2, November 2026.

**CloudFront** applies a cache policy per behavior:

- static files: managed `CachingOptimized` policy;
- HTML: custom policy with a minimum TTL of 0, so that the origin's `s-maxage` decides;
- admin, cart, private APIs: `CachingDisabled`.

Only forward to the origin the cookies, headers and parameters the page actually depends on: each one becomes part of the cache key and fragments it. If the origin does not send `Cache-Control`, add it with a response headers policy. Compliant: `x-cache: Hit from cloudfront`.

```bash
aws cloudfront create-invalidation --distribution-id IDENTIFIANT --paths "/" "/blog/*"
```

**S3** adds no `Cache-Control`: set it at upload time.

```bash
aws s3 sync ./dist s3://NOM_DU_BUCKET --exclude "*.html" --cache-control "public, max-age=31536000, immutable"
aws s3 sync ./dist s3://NOM_DU_BUCKET --exclude "*" --include "*.html" --cache-control "no-cache"
```

### Google Cloud

Versions: Cloud CDN and Cloud Storage, gcloud CLI, November 2026.

**Cloud CDN**, on the load balancer's backend service:

```bash
gcloud compute backend-services update NOM_DU_SERVICE --global \
  --enable-cdn --cache-mode=CACHE_ALL_STATIC \
  --default-ttl=3600 --client-ttl=3600 --max-ttl=86400

gcloud compute url-maps invalidate-cdn-cache NOM_URL_MAP --path "/*"
```

`CACHE_ALL_STATIC` caches static content and everything the origin declares cacheable; `USE_ORIGIN_HEADERS` relies entirely on the origin. Avoid `FORCE_CACHE_ALL` on a site with personalized pages.

**Cloud Storage**:

```bash
gcloud storage objects update "gs://NOM_DU_BUCKET/assets/**" --cache-control="public, max-age=31536000, immutable"
```

### Azure

Versions: Azure Front Door Standard and Premium, Static Web Apps, App Service, Azure CLI, November 2026.

**Azure Front Door**: enable caching on the route, then choose how query strings are handled. Front Door respects the origin's `Cache-Control`; a rule set lets you override it.

```bash
az afd endpoint purge --resource-group GROUPE --profile-name PROFIL --endpoint-name POINT_DE_TERMINAISON --content-paths "/*"
```

**Static Web Apps**, in `staticwebapp.config.json`:

```json
{
  "routes": [
    {
      "route": "/assets/*",
      "headers": { "Cache-Control": "public, max-age=31536000, immutable" }
    }
  ]
}
```

**App Service** on Windows follows the IIS configuration.

### Fastly

Versions: Fastly, all plans, November 2026.

Fastly reads `Surrogate-Control`, then `Cache-Control: s-maxage`, then `max-age`. The origin can therefore control the CDN and the browser separately:

```txt
Cache-Control: no-cache
Surrogate-Control: max-age=3600, stale-while-revalidate=60
Surrogate-Key: article-123 blog
```

Responses with `Set-Cookie` or `Cache-Control: private` are not cached by default. Purge by key or everything:

```bash
curl -X POST -H "Fastly-Key: JETON_API" https://api.fastly.com/service/ID_DU_SERVICE/purge/article-123
curl -X POST -H "Fastly-Key: JETON_API" https://api.fastly.com/service/ID_DU_SERVICE/purge_all
```

### Varnish

Versions: Varnish Cache 7.x to 9.x (VCL 4.1).

Varnish listens in front of the web server, moved here to port 8080. It does not handle TLS: put Nginx, Hitch or a CDN in front of it. File `/etc/varnish/default.vcl`:

```vcl
vcl 4.1;

backend default {
    .host = "127.0.0.1";
    .port = "8080";
}

acl purge {
    "127.0.0.1";
}

sub vcl_recv {
    if (req.method == "PURGE") {
        if (client.ip !~ purge) {
            return (synth(405, "Forbidden"));
        }
        return (purge);
    }

    if (req.method != "GET" && req.method != "HEAD") {
        return (pass);
    }

    if (req.url ~ "^/(wp-admin|wp-login|panier|commande|mon-compte)" ||
        req.http.Cookie ~ "wordpress_logged_in|woocommerce_items_in_cart|PHPSESSID") {
        return (pass);
    }

    unset req.http.Cookie;
    return (hash);
}

sub vcl_backend_response {
    if (bereq.uncacheable) {
        return (deliver);
    }

    unset beresp.http.Set-Cookie;

    if (beresp.http.Cache-Control !~ "max-?age|private|no-store|no-cache") {
        set beresp.ttl = 10m;
    }

    set beresp.grace = 6h;
}

sub vcl_deliver {
    if (obj.hits > 0) {
        set resp.http.X-Cache = "HIT";
    } else {
        set resp.http.X-Cache = "MISS";
    }
}
```

Anonymous visitors receive the cached page, without cookies; the others go straight to the server. Reload with `sudo systemctl reload varnish`. Purge a URL with `curl -X PURGE -H "Host: example.com" http://127.0.0.1/blog/` (add Varnish's listening port if it is not 80), or the whole site with `sudo varnishadm "ban req.http.host == example.com"`.

### Plesk

Versions: Plesk Obsidian 18.0 for Linux.

Open `Websites & Domains > your domain > Apache & nginx Settings` ([Plesk documentation](https://docs.plesk.com/en-US/obsidian/customer-guide/72320/)).

- **Page cache**: check “Enable nginx caching”, then set the size, the lifetime and the cookies that bypass the cache. Plesk generates the corresponding `proxy_cache` or `fastcgi_cache` configuration.
- **Browser cache**: paste the block from the Apache section into the `.htaccess`, then test a CSS file with `curl`. If the header does not appear, Nginx is serving static files without going through Apache: in that case, add to “Additional nginx directives”:

```nginx
location ~* \.(?:css|js|woff2?|avif|webp|jpe?g|png|gif|svg|ico)$ {
    add_header Cache-Control "public, max-age=2592000";
}
```

If Plesk reports a conflict, remove these extensions from the “Serve static files directly by nginx” option.

### cPanel

Versions: cPanel & WHM 110 and later, Jupiter theme.

cPanel has no screen for the browser cache: open `Files > File Manager` ([cPanel documentation](https://docs.cpanel.net/cpanel/files/file-manager/)), show hidden files and paste the block from the Apache section into `public_html/.htaccess`.

The page cache depends on the host: an “NGINX Caching” entry in the `Software` section if the server uses Nginx as a reverse proxy, or “LiteSpeed Web Cache Manager” on a LiteSpeed server. Otherwise, use your CMS cache.

### Shared hosting

The `.htaccess` from the Apache section works with most hosts; the `<IfModule>` blocks prevent any error if a module is missing. For the page cache, use a CMS plugin that writes static HTML files, or the host's server cache if its control panel offers one. Cloudflare in front of the site adds an edge cache without changing anything on the server.

### Vercel

Versions: Vercel, all plans, November 2026.

Compiled files with versioned names automatically get a long, immutable cache lifetime. For everything else, in `vercel.json`:

```json
{
  "headers": [
    {
      "source": "/fonts/(.*)",
      "headers": [{ "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }]
    }
  ]
}
```

To cache a function's response on the CDN, return `Cache-Control: s-maxage=600, stale-while-revalidate=60`. Compliant: `x-vercel-cache: HIT`. Each deployment has its own cache; to purge without redeploying, open `CDN > Caches` in the project, “Purge cache” section, and enter a cache tag or `*` for the whole project.

### Netlify

Versions: Netlify, all plans, November 2026.

Netlify serves everything with `cache-control: public, max-age=0, must-revalidate`: the browser revalidates every time, and each deployment invalidates the CDN automatically. Add a long cache lifetime to versioned files only, in a `_headers` file at the root of the publish directory:

```txt
/assets/*
  Cache-Control: public, max-age=31536000, immutable
```

### WordPress

Versions: WordPress 6.4 and later (checked on 7.1), caching plugins in their November 2026 versions.

- **Page cache**: a single plugin among WP Rocket, LiteSpeed Cache (LiteSpeed server), W3 Total Cache, WP Super Cache, WP Fastest Cache or Cache Enabler. On Apache and LiteSpeed, they also write browser cache rules to the `.htaccess` and purge on publication.
- **Nginx server**: plugins cannot modify the configuration. Apply `fastcgi_cache` and install Nginx Helper for purging.
- **Managed WordPress host** (Kinsta, WP Engine, WordPress.com): the server cache is already there; do not add a page caching plugin.
- **Object cache**: the Redis Object Cache plugin if Redis is available.
- **WooCommerce**: check that cart, checkout and account are excluded.
- **Check**: `Tools > Site Health` flags a missing page cache.

WordPress adds `?ver=` to files registered with `wp_enqueue_style` and `wp_enqueue_script`: this parameter acts as versioning.

### Shopify

Versions: Shopify, all plans, November 2026.

Automatic. Theme files called with the `asset_url` filter are served by Shopify's CDN with a versioned URL and a long cache lifetime; page caching is handled by the platform. Always go through `asset_url` rather than a hard-coded URL.

### PrestaShop

Versions: PrestaShop 8 and 9.

In `Advanced Parameters > Performance`:

- **Smarty**: template compilation set to “Never recompile template files” in production, cache enabled;
- **CCC**: enable the “Smart cache” options for CSS and for JavaScript;
- **Apache optimization**: set to Yes, to write browser cache rules to the `.htaccess`;
- **Caching** (Memcached, APCu): object cache, to test before leaving it on.

PrestaShop has no native page cache: use a dedicated module, LiteSpeed Cache or Varnish. Clear the cache after every theme or module change.

### Laravel

Versions: Laravel 11 to 13.

Vite produces versioned files in `public/build/assets`: give them a long cache lifetime at the web server level.

```nginx
location /build/assets/ {
    add_header Cache-Control "public, max-age=31536000, immutable";
    access_log off;
}
```

For HTML, the `cache.headers` middleware sets `Cache-Control` and `ETag` and responds 304 when nothing has changed:

```php
Route::middleware('cache.headers:public;max_age=0;s_maxage=600;etag')->group(function (): void {
    Route::get('/blog', [PostsController::class, 'index'])->name('blog');
});
```

The `web` group starts a session and sets cookies on every response, which prevents any shared caching: serve public pages without a session, or use an application-level response cache such as `spatie/laravel-responsecache`. On deployment, run `php artisan optimize`.

### Next.js

Versions: Next.js 15 and 16 (App Router).

Next.js sets the headers of compiled files itself: `/_next/static/*` gets `public, max-age=31536000, immutable`, which cannot be changed. For files in the `public` folder, add the headers in `next.config.js` (or `next.config.ts`):

```js
module.exports = {
  async headers() {
    return [
      {
        source: '/fonts/:path*',
        headers: [{ key: 'Cache-Control', value: 'public, max-age=31536000, immutable' }],
      },
    ];
  },
};
```

Page caching depends on the model you choose: Cache Components, stable since Next.js 16 and enabled with `cacheComponents: true`, replace the `export const revalidate` option, which is no longer accepted when they are active.

#### Next.js 16 with Cache Components

Declare caching in the page, or in the function that loads the data, with the `use cache` directive and a `cacheLife` duration:

```js
// app/blog/page.js
import { cacheLife, cacheTag } from 'next/cache';

export default async function BlogPage() {
  'use cache';
  cacheLife('hours');
  cacheTag('blog');

  const posts = await getPosts();

  return <PostList posts={posts} />;
}
```

The `hours` profile regenerates the content in the background at most once an hour. Invalidate on publication with `revalidateTag('blog', 'max')` from a Route Handler or a Server Action, or `updateTag('blog')` in a Server Action for an immediate update. When self-hosting on several instances, share this cache with the `cacheHandlers` option in `next.config.js`. Then check the `Cache-Control` header actually served with the `curl` command from the “How to check” section.

#### Next.js 15, and 16 without Cache Components

Next.js sets the page header according to how it is rendered:

- static or regenerated (ISR) pages: `s-maxage` equal to the revalidation period, with `stale-while-revalidate`;
- dynamically rendered pages: `private, no-cache, no-store`.

To make a page cacheable, set its revalidation:

```js
// app/blog/[slug]/page.js
export const revalidate = 3600;
```

Invalidate on publication with `revalidatePath('/blog')`, or by tag with `revalidateTag('blog', 'max')` on Next.js 16; on Next.js 15, `revalidateTag('blog')` takes only one argument. When self-hosting on several instances, share the cache with the `cacheHandler` option in `next.config.js`.

## Common mistakes

- **Long cache lifetime on an unversioned file**: visitors keep the old CSS for months, with no way to purge it.
- **Long `max-age` on HTML**: you cannot purge browsers. Put the long lifetime in `s-maxage`, on the shared cache side, and purge on publication.
- **Confusing `no-cache` and `no-store`**: the first allows storage with revalidation, the second forbids it.
- **Caching a personalized page**: one visitor sees another's cart or account. Test logged in and logged out after each rule change.
- **Setting a cookie on public pages** (session, CSRF, A/B test): most shared caches then refuse the response.
- **Stacking caches without a purge chain**: plugin, server and CDN each keep a different version.
- **Letting campaign parameters fragment the cache**: `utm_source` or `fbclid` create one entry per variant. Ignore them in the cache key when the platform allows it.
- **Sending `Vary: User-Agent` or `Vary: Cookie`**: the cache hit rate collapses.
- **Testing only the first request**: it is always a `MISS`.

## Frequently asked questions

### What cache lifetime should I choose for CSS and JavaScript files?

One year (max-age=31536000) with the immutable directive, but only if the file name changes with every modification, thanks to a hash added by the build tool or a ?v= parameter. Without such versioning, limit CSS and JavaScript to one day at most: a long cache lifetime on an unversioned file leaves visitors with the old version for months, with no way to purge it.

### What is the difference between no-cache and no-store?

The no-cache directive allows the browser or CDN to store the response, but requires it to revalidate with the server before each use, for example with the ETag: this is the recommended setting for public HTML. The no-store directive forbids any storage. Reserve it for personalized pages such as the cart, the account or the admin, together with private so that no shared cache keeps them.

### Can I cache the HTML pages of a WordPress or e-commerce site?

Yes, for anonymous visitors: GET requests, 200 responses and no session. Exclude the cart, checkout, account, admin and internal search, and purge on every publication. A poorly configured page cache can serve one visitor another visitor's cart or account: after each rule change, test logged in, logged out and with items in the cart.

### Does caching improve SEO?

Not directly: caching is not a ranking factor. A page served from a cache responds much faster than a generated page, which reduces TTFB and benefits LCP, and therefore Core Web Vitals. Googlebot also sends conditional requests: a server that responds 304 thanks to the ETag saves it transfers, an effect mainly noticeable on large sites.

## Resources

- [MDN: Cache-Control header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Cache-Control)
- [web.dev: HTTP cache](https://web.dev/articles/http-cache)
- [Google Search Central: HTTP caching and Google's crawlers](https://developers.google.com/search/blog/2024/12/crawling-december-caching)
- [Apache: mod_headers](https://httpd.apache.org/docs/2.4/mod/mod_headers.html) and [mod_cache](https://httpd.apache.org/docs/2.4/mod/mod_cache.html)
- [Nginx: fastcgi_cache](https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_cache) and [proxy_cache](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache)
- [Cloudflare: Cache Rules](https://developers.cloudflare.com/cache/how-to/cache-rules/), [default cache behavior](https://developers.cloudflare.com/cache/concepts/default-cache-behavior/) and [purging](https://developers.cloudflare.com/cache/how-to/purge-cache/)
- [Amazon CloudFront: Manage how long content stays in the cache](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html)
- [Google Cloud CDN: Cache modes](https://cloud.google.com/cdn/docs/using-cache-modes)
- [Varnish: documentation](https://varnish-cache.org/docs/)
- [Vercel: Cache-Control headers](https://vercel.com/docs/caching/cache-control-headers) and [Netlify: Caching](https://docs.netlify.com/platform/caching/)
- [Laravel: Cache headers](https://laravel.com/docs/responses#cache-control-middleware) and [Next.js: Self-hosting and caching](https://nextjs.org/docs/app/guides/self-hosting)

Next steps: [optimize hosting and CDN](https://checklist-seo-geo.com/en/performance-core-web-vitals/optimize-hosting-cdn) and [target TTFB ≤ 800 ms](https://checklist-seo-geo.com/en/performance-core-web-vitals/target-ttfb-800-ms-as-benchmark).
